1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| @Slf4j public class WordUtils {
public static void main(String[] args) throws Exception { WordUtils.convertDocxToPdf("d://123.docx","d://123.pdf"); }
public static void convertDocxToPdf(String docxPath, String pdfPath) { FileOutputStream fileOutputStream = null; try { File file = new File(docxPath); fileOutputStream = new FileOutputStream(new File(pdfPath)); WordprocessingMLPackage mlPackage = WordprocessingMLPackage.load(file); log.info("docx转换:" + mlPackage); setFontMapper(mlPackage); Docx4J.toPDF(mlPackage, fileOutputStream); } catch (Exception e) { e.printStackTrace(); log.error("docx文档转换为PDF失败"); } finally { try { fileOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); } IOUtils.closeQuietly(fileOutputStream); } }
private static void setFontMapper(WordprocessingMLPackage mlPackage) throws Exception { Mapper fontMapper = new IdentityPlusMapper(); fontMapper.put("隶书", PhysicalFonts.get("LiSu")); fontMapper.put("宋体", PhysicalFonts.get("SimSun")); fontMapper.put("微软雅黑", PhysicalFonts.get("Microsoft Yahei")); fontMapper.put("黑体", PhysicalFonts.get("SimHei")); fontMapper.put("楷体", PhysicalFonts.get("KaiTi")); fontMapper.put("新宋体", PhysicalFonts.get("NSimSun")); fontMapper.put("华文行楷", PhysicalFonts.get("STXingkai")); fontMapper.put("华文仿宋", PhysicalFonts.get("STFangsong")); fontMapper.put("宋体扩展", PhysicalFonts.get("simsun-extB")); fontMapper.put("仿宋", PhysicalFonts.get("FangSong")); fontMapper.put("仿宋_GB2312", PhysicalFonts.get("FangSong_GB2312")); fontMapper.put("幼圆", PhysicalFonts.get("YouYuan")); fontMapper.put("华文宋体", PhysicalFonts.get("STSong")); fontMapper.put("华文中宋", PhysicalFonts.get("STZhongsong")); fontMapper.put("等线", PhysicalFonts.get("SimSun")); fontMapper.put("等线 Light", PhysicalFonts.get("SimSun")); fontMapper.put("华文琥珀", PhysicalFonts.get("STHupo")); fontMapper.put("华文隶书", PhysicalFonts.get("STLiti")); fontMapper.put("华文新魏", PhysicalFonts.get("STXinwei")); fontMapper.put("华文彩云", PhysicalFonts.get("STCaiyun")); fontMapper.put("方正姚体", PhysicalFonts.get("FZYaoti")); fontMapper.put("方正舒体", PhysicalFonts.get("FZShuTi")); fontMapper.put("华文细黑", PhysicalFonts.get("STXihei")); fontMapper.put("宋体扩展",PhysicalFonts.get("simsun-extB")); fontMapper.put("仿宋_GB2312",PhysicalFonts.get("FangSong_GB2312")); fontMapper.put("新細明體",PhysicalFonts.get("SimSun")); PhysicalFonts.put("PMingLiU", PhysicalFonts.get("SimSun")); PhysicalFonts.put("新細明體", PhysicalFonts.get("SimSun")); mlPackage.setFontMapper(fontMapper); } }
|