1、word文档转pdf
参考文章:https://www.cnblogs.com/luxiaoxun/p/16506045.html
1)maven依赖
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.poi.xwpf.converter.pdf-gae</artifactId>
<version>2.0.1</version>
</dependency>
2)测试代码
package com.obs.obsintf.yyxt.utils;
import com.google.code.appengine.awt.Color;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import fr.opensagres.xdocreport.itext.extension.font.IFontProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import java.io.*;
@Slf4j
public class WordToPDF {
public static void main(String[] args) {
WordToPDF.toPDF();
}
public static void toPDF(){
InputStream ins = null;
XWPFDocument xdoc = null;
OutputStream outs = null;
try {
ins = new FileInputStream("D:\\pdf测试_20220906170705.docx");//
xdoc = new XWPFDocument(ins);
PdfOptions options = PdfOptions.create();
//支持中文 无此代码 不显示中文
options.fontProvider(new IFontProvider() {
@Override
public Font getFont(String familyName, String encoding, float size, int style, Color color) {
try {
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, size, style, color);
if (familyName != null) {
fontChinese.setFamily(familyName);
}
return fontChinese;
} catch (Exception e) {
return null;
}
}
});
outs = new FileOutputStream("D:\\pdf文件.pdf");//
PdfConverter.getInstance().convert(xdoc, outs, options);
} catch (Exception e) {
e.printStackTrace();
}finally {
if(outs!=null){
try {outs.close();} catch (IOException e) {e.printStackTrace();}
}
if(xdoc!=null){
try {xdoc.close();} catch (IOException e) {e.printStackTrace();}
}
if(ins!=null){
try {ins.close();} catch (IOException e) {e.printStackTrace();}
}
}
}
}