下面给你一个在 Spring Boot 中实现 Word 转 PDF​ 的完整思路与示例,覆盖主流可行方案推荐做法以及注意事项,你可以按项目需求选择。

一、总体方案对比

方案是否收费转换质量依赖环境推荐指数
docx4j + Plutext PDF Converter商业需授权⭐⭐⭐⭐⭐无(Java)✅✅✅
LibreOffice(命令行)免费⭐⭐⭐⭐需安装LibreOffice✅✅✅
Apache POI + iText(间接)免费⭐⭐复杂
Aspose.Words for Java商业⭐⭐⭐⭐⭐✅(有钱)

生产环境最推荐

  • Windows/Linux 服务器:LibreOffice
  • 企业级高质量:docx4j + Plutext(或 Aspose)

二、方案一:LibreOffice(最常用、免费)

原理

Spring Boot 调用服务器上的 soffice命令将 .docx.pdf

安装 LibreOffice

# Ubuntu
sudo apt install libreoffice
# CentOS
yum install libreoffice
# Windows
下载安装 LibreOffice

Spring Boot 示例代码

Maven 依赖(无需额外)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

Service 示例

import java.io.*;

@Service
public class WordToPdfService {

    public void convert(String wordPath, String pdfPath) throws Exception {
        String command = "libreoffice --headless --convert-to pdf "
                + wordPath + " --outdir " + new File(pdfPath).getParent();

        Process process = Runtime.getRuntime().exec(command);
        int exitCode = process.waitFor();

        if (exitCode != 0) {
            throw new RuntimeException("Word转PDF失败");
        }
    }
}

优点

  • 免费
  • 支持 .doc / .docx
  • 格式还原度高

注意

  • Linux 必须安装字体(否则中文乱码)
  • 不支持并发过高(建议队列或限制线程)

三、方案二:docx4j + Plutext(企业级)

Maven 依赖

<dependency>
    <groupId>org.docx4j</groupId>
    <artifactId>docx4j</artifactId>
    <version>11.4.9</version>
</dependency>
<dependency>
    <groupId>org.plutext</groupId>
    <artifactId>plutext-pdf-converter</artifactId>
    <version>3.3.0</version>
</dependency>

转换代码

import org.docx4j.Docx4J;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;

import java.io.FileOutputStream;

public void convert() throws Exception {
    WordprocessingMLPackage wordMLPackage =
            WordprocessingMLPackage.load(new File("input.docx"));

    Docx4J.toPDF(wordMLPackage, new FileOutputStream("output.pdf"));
}

优点

  • 纯 Java
  • 不依赖外部软件
  • 样式还原好

缺点

  • Plutext 商用需授权
  • 对复杂表格/页眉页脚偶有偏差

四、方案三:Aspose.Words(最强但贵)

Maven

<dependency>
    <groupId>com.aspose</groupId>
    <artifactId>aspose-words</artifactId>
    <version>23.12</version>
</dependency>

代码示例

import com.aspose.words.Document;

Document doc = new Document("input.docx");
doc.save("output.pdf");

五、常见问题 & 解决方案

中文乱码

Linux 安装中文字体

yum install wqy-microhei-fonts

并发问题

  • LibreOffice 不建议多线程同时转换
  • 可使用线程池 + 队列

Web 接口示例

@PostMapping("/convert")
public ResponseEntity<?> convert(MultipartFile file) throws Exception {
    // 保存word
    // 调用转换
    // 返回pdf流
}

六、推荐选型总结

场景推荐方案
普通后台系统LibreOffice
企业文档系统docx4j + Plutext
金融/合同/报表Aspose.Words

觉得上面的内容有用吗?快来点个赞吧!

点赞() 我要打赏

温馨提示 : 本站内容来自会员投稿以及互联网,所有源码及教程均为作者总结编辑,请大家在使用过程中提前做好备份,以免发生无法预知的错误,源码类教程请勿直接用于生产环境!

 可能感兴趣的文章