工作中时常遇到word文档转换为pdf的需求,poi提供了一套现成的方法:
package com.zzp.springboot.utils;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* word to pdf
*/
public class WordToPDF {
public void docToPDF(){
String inPath = "D:\\testWord.docx";
String outPath = "D:\\testPdf.pdf";
try{
Long start = System.currentTimeMillis();
InputStream docx = new FileInputStream(inPath);
XWPFDocument xwpfDocument = new XWPFDocument(docx);
PdfOptions pdf = PdfOptions.create();
OutputStream os = new FileOutputStream(outPath);
PdfConverter.getInstance().convert(xwpfDocument,os,pdf);
docx.close();
os.close();
Long end = System.currentTimeMillis();
System.out.println("生成pdf成功,耗时:" + (end -start) + "毫秒");
}catch(Exception e){
}
}