- 背景
基于Java-documents4j库代码实现的word转pdf
网上查询了很多资料要么依赖缺省 要么收费 要么配置复杂 一言难尽…
重要提示 这个方案需要Microsoft Word或LibreOffice作为转换引擎。下面提供简洁、可直接运行的代码,并解决依赖问题。
注意:documents4j需要本机安装Microsoft Word或LibreOffice。这里我们假设使用Microsoft Word(转换质量更高)。
1.环境准备
SpringBoot 2.7.3
Jdk 11
maven 3.6.2
2.导入maven依赖
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.0.3</version>
</dependency>
3. 代码示例
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
public static void convert(String inputPath, String outputPath) {
File inputFile = new File(inputPath);
File outputFile = new File(outputPath);
try (InputStream in = new FileInputStream(inputFile);
OutputStream out = new FileOutputStream(outputFile)) {
// 使用系统默认安装的MS Word
IConverter converter = LocalConverter.builder()
.build();
converter.convert(in)
.as(DocumentType.DOCX)
.to(out)
.as(DocumentType.PDF)
.execute();
System.out.println("文档转换成功: " + outputPath);
converter.shutDown();
} catch (Exception e) {
System.err.println("转换失败: " + e.getMessage());
// 自动回退到LibreOffice
if (e.getMessage().contains("Microsoft Word")) {
System.out.println("尝试使用LibreOffice...");
convertWithLibreOffice(inputPath, outputPath);
}
}
}
private static void convertWithLibreOffice(String inputPath, String outputPath) {
try (InputStream in = new FileInputStream(inputPath);
OutputStream out = new FileOutputStream(outputPath)) {
IConverter converter = LocalConverter.builder()
.build();
converter.convert(in)
.as(DocumentType.DOCX)
.to(out)
.as(DocumentType.PDF)
.execute();
System.out.println("使用LibreOffice转换成功");
} catch (Exception e) {
System.err.println("LibreOffice转换失败: " + e.getMessage());
}
}
public static void main(String[] args) {
// 示例用法 - 更改配置直接调用
convert("your input file path", "your output file path");
}
4.扩展
也可以基于SpringMVC 进行web集成直接输出响应流
完毕…