1.引入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>
2. 新建工具类
package com.sida.lims.utils;
import cn.hutool.core.util.IdUtil;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import fr.opensagres.xdocreport.itext.extension.font.IFontProvider;
import lombok.extern.log4j.Log4j2;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import javax.servlet.ServletOutputStream;
import java.io.*;
/**
* @Author: lei
* @Date: 2024/03/21/17:04
* @Description: word转pdf工具类
*/
@Log4j2
public class WordToPDFUtils {
/**
* @param wordFilePath word文件路径
* @param PDFFilePath pdf文件路径
*/
public static void docxToPDF(String wordFilePath, String PDFFilePath) throws IOException {
XWPFDocument doc = new XWPFDocument(new FileInputStream(wordFilePath));// docx
PdfOptions options = PdfOptions.create();
// 中文字体处理
options.fontProvider(new IFontProvider() {
@Override
public Font getFont(String familyName, String encoding, float size, int style, java.awt.Color color) {
try {
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, 12, style, color);
if (familyName != null)
fontChinese.setFamily(familyName);
return fontChinese;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
});
PdfConverter.getInstance().convert(doc, new FileOutputStream(PDFFilePath), options);// pdf
}
/**
* @param wordFilePath word文件路径
* @param PDFFilePath pdf文件路径
*/
public static void docxToPDF1(String wordFilePath, String PDFFilePath) throws IOException {
fileExists(PDFFilePath);
OutputStream outPdf = new FileOutputStream(PDFFilePath);
InputStream fileInputStream = new FileInputStream(wordFilePath);
IConverter converter = LocalConverter.builder().build();
log.debug("开始转换");
converter.convert(fileInputStream).as(DocumentType.DOCX).to(outPdf).as(DocumentType.PDF).execute();
converter.shutDown();
log.debug("转换结束");
outPdf.close();
fileInputStream.close();
}
/**
* 判断文件路径是否存在(如若不存在,则创建该路径)
*
* @param filePath 文件路径
* @return
*/
private static File fileExists(String filePath) {
File desc = new File(filePath);
if (!desc.exists() && !desc.getParentFile().exists()) {
desc.getParentFile().mkdirs();
}
return desc;
}
}
方法1用的是poi实现,方法2使用的documents4j实现,因为方法1可能会出现jar包冲突等问题,所以推荐方法2.