java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot Word转PDF​

SpringBoot实现Word转PDF​的完整思路与示例代码详解

作者:每日技术

本文介绍了在SpringBoot中实现将Word转换为PDF的多种方案,包括docx4j、LibreOffice、ApachePOI+iText等主流方案,针对不同需求提供了详细的方案对比,代码示例以及注意事项,希望对大家有所帮助

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

一、总体方案对比

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

生产环境最推荐

二、方案一: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失败");
        }
    }
}

优点

注意

三、方案二: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"));
}

优点

缺点

四、方案三: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

并发问题

Web 接口示例

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

六、推荐选型总结

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

到此这篇关于SpringBoot实现Word转PDF​的完整思路与示例代码详解的文章就介绍到这了,更多相关SpringBoot Word转PDF​内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文