- maven导包
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
<version>1.0.6</version>
</dependency>
- 工具类
import java.awt.Color;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import com.lowagie.text.pdf.BaseFont;
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.lowagie.text.Font;
import fr.opensagres.xdocreport.itext.extension.font.IFontProvider;
public class WordToPdfUtil {
public static void wordConverterToPdf(InputStream source, OutputStream target,final String typeFaceUrl) throws Exception {
PdfOptions options = PdfOptions.create();
options.fontProvider(new IFontProvider() {
public Font getFont(String familyName, String encoding, float size, int style, Color color) {
try {
BaseFont bfChinese = BaseFont.createFont(typeFaceUrl, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, size, style, color);
if (familyName != null)
fontChinese.setFamily(familyName);
return fontChinese;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
});
PdfConverter.getInstance().convert(new XWPFDocument(source), target,options);
}
public static void wordToPdf(String filepath,String outpath,String typeFaceUrl) {
InputStream source;
OutputStream target;
try {
source = new FileInputStream(filepath);
target = new FileOutputStream(outpath);
wordConverterToPdf(source, target,typeFaceUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
}