跪拜 Guibai
← Back to the summary

kkFileView: The Open-Source Swiss Army Knife for In-Browser File Previews

Foreword

The most mature file preview solution in the open-source community, bar none.

I wonder if you've encountered these scenarios during development:

How to solve this?

Answer: Directly deploy a set of kkFileView.

In less than half an hour, all document formats can be opened directly in the browser.

Users no longer need the "download → open → save → upload" workflow.

kkFileView is becoming a standard component in more and more Java projects. It has accumulated over 9.9k Stars on GitHub and is the most mature online file preview solution in the open-source community.

In this article, I'll break down, from start to finish, why more and more people are using kkFileView.

I hope it helps you.

For more project practices, visit the Java Commando Team website: susan.net.cn/project

1. What Makes File Preview So Difficult?

Before discussing kkFileView, let's first understand a fundamental question—why is file preview so tricky?

Office documents like Word, Excel, and PPT are essentially not "plain text files" but extremely complex compressed packages.

A docx file, when unpacked, is a bunch of XML, images, stylesheets, and font files. To display it faithfully in a browser is equivalent to implementing a lightweight Office suite inside the browser.

CAD drawings are even more troublesome, requiring a dedicated graphics engine for rendering.

PDFs are slightly better, as browsers can open them directly, but PDFs themselves are often converted from other formats.

In an enterprise, file formats are diverse—Word, Excel, PPT, PDF, images, CAD, compressed archives, audio/video... each format has its own set of parsing rules.

Problems with traditional solutions:

Frankly, what enterprises need is not just "the ability to open a file," but "all files can be opened directly in the browser."

2. What Exactly Is kkFileView?

kkFileView is an open-source project solution for online file document preview built with Spring Boot.

It provides RESTful API interfaces, supporting cross-language, cross-platform file preview functionality.

In a nutshell: kkFileView is an independent file preview microservice. Once deployed, any format file can be previewed directly in the browser by calling it via an HTTP interface.

Its underlying layer relies on LibreOffice/OpenOffice to convert documents to PDF, which is then displayed by front-end components like PDF.js.

It doesn't matter if you don't understand the internal structure of Office documents; kkFileView handles it for you.

Core Features:

3. Understanding the Overall Architecture of kkFileView at a Glance

Before diving into deployment, let's build a holistic understanding.

image

kkFileView adopts a "Parsing-Conversion-Rendering" three-layer architecture design.

The core is divided into four major modules:

The system adopts a "Conversion-Caching-Display" pipeline processing model, converting files into web-friendly formats and then caching them, effectively reducing server load and improving response speed.

This process is like "file translation"—files of different formats are like documents in different languages, and kkFileView acts as the translator, unifying them into a format the browser can recognize.

4. Workflow

When a user requests a preview of a Word document, kkFileView internally goes through the following stages:

4.1 Format Identification

The system uses dual verification of file magic numbers and extensions to accurately determine the file type. This step prevents users from disguising malicious files as other formats.

4.2 File Download

If the file is not stored locally, the system automatically downloads it to a temporary directory.

4.3 Cache Check

The system checks the cache based on the hash value of the file content to see if a conversion result already exists. If so, it returns the cache directly, avoiding redundant conversions.

4.4 Conversion Processing

Dedicated conversion services are called for different file types:

4.5 Rendering and Display

After conversion, professional libraries like PDF.js and FlexPaper are used for smooth previewing on the front end.

4.6 Cache Result

The conversion result is cached. The next time the same file is requested for preview, it hits the cache directly and opens instantly.

5. Core Features

kkFileView supports online preview of over 100 file formats.

Type Supported Formats Scenario
Office Docs doc, docx, xls, xlsx, ppt, pptx Contracts, reports, slides
WPS/Domestic wps, et, dps, ofd Xinchuang/domestic scenarios
PDF Docs pdf, ofd Official docs, e-licenses
Text Files txt, html, xml, json, md, log, java, py, c, cpp, sql, sh Code preview, log viewing
Image Files jpg, jpeg, png, gif, bmp, ico, webp Design drafts, product pics
Archives zip, rar, jar, tar, gzip, 7z Batch file packaging
CAD Drawings dwg, dxf, stl, ifc Engineering drawings, arch.
3D Models obj, 3ds, gltf, glb, stl, ply, fbx Product design, modeling
Audio/Video mp3, wav, mp4, avi, mov, mkv, webm, ogg Teaching videos, recordings

kkFileView is deeply adapted for domestic operating systems (Kylin, UOS, NeoKylin) and domestic file formats (OFD, UOF), perfectly supporting WPS documents.

6. Getting kkFileView Running in 3 Steps

Theory isn't enough; let's see how to get started quickly.

6.1 Step 1: Deploy the kkFileView Service

Method A: Docker Deployment (Highly Recommended)

# Pull the official image
docker pull keking/kkfileview

# Start the service
docker run -d -p 8012:8012 --name kkfileview --memory=2g keking/kkfileview

After starting, visit http://your_server_ip:8012. Seeing the kkFileView demo homepage indicates the service started successfully.

Method B: Traditional Deployment (Windows/Linux)

Download the installation package from the official Gitee releases page (e.g., kkFileView-4.4.0-SNAPSHOT.tar.gz):

Windows: Extract, enter the bin directory, and double-click startup.bat Linux: Extract, enter the bin directory, and run ./startup.sh

Pitfall: The first startup will automatically install LibreOffice, requiring an internet connection. If the server is in a pure intranet environment, you need to prepare the LibreOffice installation package in advance.

6.2 Step 2: Integrate Preview in Spring Boot

Once the kkFileView service is running, your Spring Boot application just needs to know how to call it.

Preview interface rule:

http://{kkFileView_service_address}:8012/onlinePreview?url={Base64_encoded_file_download_link}

Code Implementation:

import org.springframework.stereotype.Service;
import org.springframework.web.util.UriUtils;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Service
public class FilePreviewService {
    
    // kkFileView service address
    private static final String KK_FILE_VIEW_BASE_URL = "http://localhost:8012";
    
    /**
     * Generate the preview URL for a file
     * @param fileUrl The actual download link of the file
     * @return The complete preview URL
     */
    public String generatePreviewUrl(String fileUrl) {
        try {
            // 1. Base64 encode the file URL
            String encodedUrl = Base64.getEncoder()
                .encodeToString(fileUrl.getBytes(StandardCharsets.UTF_8));
            
            // 2. URL encode the Base64 string
            String finalEncodedUrl = UriUtils.encode(
                encodedUrl, StandardCharsets.UTF_8.toString()
            );
            
            // 3. Concatenate the final preview URL
            return KK_FILE_VIEW_BASE_URL + "/onlinePreview?url=" + finalEncodedUrl;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

Call in Controller:

@RestController
public class FileController {
    
    @Autowired
    private FilePreviewService filePreviewService;
    
    @GetMapping("/preview/{fileId}")
    public String preview(@PathVariable String fileId) {
        // Get the actual download link of the file
        String fileUrl = fileService.getFileUrl(fileId);
        // Generate the preview URL
        return filePreviewService.generatePreviewUrl(fileUrl);
    }
}

After the front end gets the preview URL, it can directly redirect or open it in an iframe.

6.3 Step 3: Production-Level Configuration

Achieve configuration persistence by mounting volumes:

mkdir -p /opt/kkfileview/{config,log,file}

docker run -d -p 8012:8012 \
  --name kkfileview \
  -v /opt/kkfileview/config:/opt/kkFileView/config \
  -v /opt/kkfileview/file:/opt/kkFileView/file \
  -v /opt/kkfileview/log:/opt/kkFileView/log \
  keking/kkfileview

Configure in application.properties:

# Watermark settings
watermark.txt=Company Name
# Trusted domain whitelist
trust.host=https://yourdomain.com
# Cache cleanup strategy (every day at 2 AM)
cache.clean.cron=0 0 2 * * ?

7. Performance Optimization

7.1 Caching Strategy

Generates cache keys based on file content hash values, achieving precise caching and avoiding redundant conversions. Frequently accessed files hit the cache directly and open instantly.

7.2 Asynchronous Processing

Implements asynchronous file conversion processing using Spring Boot's @Async annotation, so users don't have to wait idly.

7.3 Paginated Preview

Adopts a paginated loading strategy for long documents to improve the first-screen loading speed. Users see the first page first, and the rest loads gradually.

7.4 Memory Management

Implements segmented processing for large files to avoid memory overflow.

7.5 Multi-Instance Horizontal Scaling

Deploy multiple kkFileView instances and achieve high availability and performance improvement through load balancing.

8. Comparing kkFileView with Other Solutions

Comparison Dimension kkFileView Pure Front-end Solution Commercial Solution
Deployment Cost Zero-cost open-source Zero-cost Charged per concurrency
Office Preview Quality ✅ High fidelity ❌ Layout easily distorted ✅ High fidelity
Number of Formats 100+ Limited (5-8 types) Rich, but requires license
CAD/3D Support ✅ Supported ❌ Not supported ✅ Supported
Deployment Complexity Medium Low Medium
Enterprise Ops ⚠️ Self-maintained ✅ Technical support

Pure front-end solutions might work well for simple documents, but when encountering real enterprise documents—especially contracts, official documents, approval materials, bidding documents, complex tables, and formal reports—issues like layout shifts, pagination inconsistencies, image misplacement, and table disarray are common.

Commercial solutions are powerful but charge per concurrency.

For small and medium-sized enterprises and teams with limited budgets, kkFileView's free and open-source strategy is clearly more friendly.

kkFileView's open-source positioning is more pragmatic: the architecture is relatively centralized, mainly built around mature components like LibreOffice, emphasizing deployment experience and community accessibility.

9. Pros and Cons

Pros

1. Broad Format Support Supports over 100 file formats, covering almost all scenarios of daily enterprise office work.

2. Simple Integration Provides RESTful APIs, easily integrable by applications in any language.

3. Out-of-the-Box One-click Docker deployment, no need to write complex code.

4. Open Source and Free Zero-cost deployment, commercially friendly.

5. Good Conversion Quality Relies on LibreOffice for document conversion, ensuring the quality of the preview effect.

6. Domestic Adaptation Deeply adapted for domestic operating systems like Kylin and UOS, perfectly supporting WPS documents and OFD format.

7. Mature Community Launched early, has a large user base, and high project maturity.

Cons

1. Requires Independent Deployment Needs an additional kkFileView service to be maintained, increasing operational complexity.

2. Conversion Depends on LibreOffice The conversion quality of LibreOffice directly affects the preview effect; some complex documents may have formatting deviations.

3. Slow First-Time Conversion Without a cache, the first conversion of a large file requires waiting.

4. Limited Enterprise-Level Ops Capabilities Enterprise-level capabilities like monitoring, alerting, and high availability need to be built independently.

5. High Memory Consumption Memory consumption increases significantly during multi-user concurrent previews. For production environments, 4GB of memory or more is recommended.

10. Applicable Scenarios

Scenario Recommendation Level Reason
OA Office Systems ✅✅✅ Highly Recommended Official docs, contracts, attachments; full format, good effect
Knowledge Bases/Doc Mgmt ✅✅✅ Highly Recommended Unified preview entry, no download needed
Enterprise Network Drives ✅✅✅ Highly Recommended Online viewing of multi-format files
Education Platforms ✅✅✅ Highly Recommended Online preview of lesson plans, courseware, materials
Medical Imaging Systems ✅✅ Recommended Supports DICOM medical image preview
Govt/SOE Xinchuang Projects ✅✅✅ Highly Recommended Deep domestic adaptation
Personal/Small-Medium Projects ✅✅✅ Highly Recommended Zero cost, quick integration
Ultra-Large Enterprise Deployments ⚠️ Evaluation Needed Commercial solutions might offer better support

For more project practices, visit the Java Commando Team website: susan.net.cn/project

11. Final Words

Back to the original question: Why are more and more people using kkFileView?

The answer is actually not complicated—it solves the core contradiction in the high-frequency scenario of enterprise file preview: needing broad format support, simple deployment, and free open-source availability.

Pure front-end solutions are simple to deploy but collapse when encountering complex Office document layouts.

Commercial solutions are powerful but charge per concurrency.

Building your own conversion service requires high investment and is difficult to maintain.

kkFileView has taken a "third path"—built on Spring Boot, using LibreOffice as the conversion engine, exposing services via RESTful API, and deployed with a single Docker command.

100+ format support, zero-cost open-source, online in half an hour.

It's not that "one particular feature is exceptionally strong," but rather "it has everything that's needed, and everything is above the passing line."

For individual developers, small to medium projects, and internal systems, kkFileView can fill the file preview capability gap at a relatively low cost.

Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

增量编译

AI is so powerful now, why hasn't anyone built a pure frontend JS/WASM component for previewing arbitrary files (or common file formats)?