1. 产品
  2.   字处理
  3.   Java
  4.   documents4j
 
  

免费 Java API 将高质量 Word 文档转换为 PDF

领先的开源库使 Java 开发者能够使用本地应用程序以高精度转换 MS Office DOCX、XLSX 和 PDF 文件。

什么是 Documents4j ?

documents4j 是一个强大的开源 Java 库,旨在将文档在不同格式之间转换,例如将 DOCX 转换为 PDF 或将 XLSX 转换为 PDF。与许多传统库不同,documents4j 将转换过程委托给本地应用程序,如 Microsoft Word 和 Excel,从而在最小化格式问题的同时确保高质量输出。该库采用了不同的方式。它不是重新实现转换逻辑,而是充当桥梁,将繁重的工作委托给已经完全理解这些格式的本地应用程序(如 Microsoft Word 或 Excel)。这确保了输出文档——例如从 Word 文件生成的 PDF——看起来就像您在 MS Office 中手动点击 “另存为” 一样。

documents4j 的主要价值在于其精度。对于需要专业级文档、每个边距和字体必须保持完整的企业来说,依赖开源解析器可能存在风险。documents4j 对于从模板生成发票或报告、在基于 Windows 的环境中自动化文档工作流以及通过远程服务器设置将转换逻辑与主应用程序解耦特别有用。通过利用本地应用程序,它提供了传统库无法比拟的精确度。其对本地和远程处理、并发执行以及负载均衡的支持,使其非常适合企业级系统。

Previous Next

开始使用 Documents4j

首先,您需要在系统上安装 Java Development Kit(JDK)。在基于 Maven 的 Java 项目中引用 Docs-to-PDF-Converter 更加简单。只需在 pom.xml 中添加以下依赖,让您的 IDE 下载并引用 Docs-to-PDF-Converter 的 Jar 文件即可。

documents4j 的 Maven 仓库


// Here’s a commonly used dependency (Local converter): 

<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.1.13</version>
</dependency>

//If you only need the API:
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-api</artifactId>
<version>1.1.13</version>
</dependency>

在 GitHub 上安装 documents4j


git clone https://github.com/documents4j/documents4j.git
cd documents4j
cd documents4j-local-demo
mvn jetty:run

通过 Java 库将 Word 转换为 PDF

开源的 Docs-to-PDF-Converter 允许软件开发人员在 Java 应用程序中将多种文档类型转换为 PDF。该库支持 Micro Word(DOC、DOCX)、Excel(XLS、XLSX)、PowerPoint(PPT、PPTX)、RTF、OpenDocument 格式等。广泛的格式兼容性确保了多种使用场景下的无缝文档转换。以下是一个简单示例,演示软件开发人员如何使用 Java 命令将 Word 文档(.docx)转换为 PDF。

如何通过 Java 库将 Word 转换为 PDF?

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;

import java.io.File;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class DocumentConverter {
    public static void main(String[] args) {
        // 1. Specify the source and target files
        File wordFile = new File("C:/documents/input.docx");
        File targetFile = new File("C:/documents/output.pdf");

        // 2. Initialize the converter (Local instance)
        IConverter converter = LocalConverter.builder()
                .workerPool(20, 25, 2, TimeUnit.SECONDS)
                .processTimeout(5, TimeUnit.SECONDS)
                .build();

        // 3. Execute the conversion fluently
        boolean success = converter.convert(wordFile).as(DocumentType.MS_WORD)
                                   .to(targetFile).as(DocumentType.PDF)
                                   .execute();

        if (success) {
            System.out.println("Conversion completed successfully!");
        }

        // 4. Always shut down the converter to release native resources
        converter.shutDown();
    }
}

带有 REST API 服务器的远程转换器

开源的 Docs-to-PDF-Converter 库允许软件开发人员在将文档转换为 PDF 时自定义 PDF 输出。例如,开发人员可以控制页面尺寸(A4、Letter 等)、页边距、方向(纵向或横向)以及页眉/页脚。此外,他们还能对 HTML 内容应用 CSS 样式,以实现精确的视觉控制,管理字体系列、颜色、大小等。以下代码片段展示了如何对库生成的 PDF 应用各种设置。

如何在 Java 应用中执行远程 Word 文档转换?

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.RemoteConverter;

import java.io.*;
import java.util.concurrent.TimeUnit;

public class RemoteConverterExample {

    public static void main(String[] args) throws Exception {

        // The RemoteConverter connects to the standalone server
        IConverter converter = RemoteConverter.builder()
                .baseFolder(new File("/tmp/documents4j"))
                .workerPool(10, 20, 5, TimeUnit.SECONDS)
                // Timeout for each HTTP conversion request
                .requestTimeout(30, TimeUnit.SECONDS)
                // URI of the running conversion server
                .baseUri("http://192.168.1.100:9998")
                .build();

        // Convert using InputStream / OutputStream — recommended for RemoteConverter
        // because data is already serialized for HTTP transport
        try (InputStream source = new FileInputStream("/input/contract.docx");
             OutputStream target = new FileOutputStream("/output/contract.pdf")) {

            boolean success = converter
                    .convert(source).as(DocumentType.MS_WORD)
                    .to(target).as(DocumentType.PDF)
                    .execute();

            System.out.println("Remote conversion success: " + success);
        }

        converter.shutDown();
    }
}          

SSL 加密和基本身份验证

Docs-to-PDF-Converter 库使 Java 开发者能够轻松创建动态且复杂的 PDF 文档。它会自动检测输入文件的格式并相应处理。无论是 Word、Excel、PowerPoint 还是 RTF 文件,库都能在无需额外配置的情况下无缝转换为 PDF。以下示例展示了软件开发人员如何在 Java 应用程序中将 Markdown 文件转换为 PDF。

异步和优先级处理

Conversions can be resource-intensive. documents4j allows you to schedule conversions to run in the background (asynchronously) using a Future return type. Furthermore, it supports a prioritization mechanism. If your application handles a high volume of requests, you can assign a higher priority to critical documents to ensure they are moved to the front of the internal job queue.

 中国人