用docx4j生成word之后转成pdf

所需Jar包 (注意,jar不能少,版本也要对应,否则会报错,类似:org/plutext/jaxb/xslfo/ObjectFactory 这样的错误都是因为缺少jar包)

注意:下面字体格式设置可能不全,所以在word转成pdf出现乱码时,尽量把word模板的字体改成下面代码中有的字体。这样就不会乱码了。但是我的图片样式还是错位,欢迎知道怎么解决的小伙伴给我留言。

avalon-framework-4.1.5 
commons-io-2.4 
docx4j-2.7.1 
log4j-1.2.15 
serializer-2.7.1 
xmlgraphics-commons-1.3 
batik-util-1.6-1 
commons-logging-1.1.3 
fop-0.93 

xalan-2.7.1

-------------------------------------------------------------------------------------------------------------------------

/**
 * docx文档转换为PDF
 *
 * @param  docx文档
 * @param pdfPath PDF文档存储路径
 * @throws Exception 可能为Docx4JException, FileNotFoundException, IOException */
public static void convertDocxToPDF(String docxPath, String pdfPath) throws Exception {
   OutputStream os = null;
   try {
      InputStream is = new FileInputStream(new File(docxPath));
      WordprocessingMLPackage mlPackage = WordprocessingMLPackage.load(is);
      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"));

      mlPackage.setFontMapper(fontMapper);

      os = new java.io.FileOutputStream(pdfPath);

      FOSettings foSettings = Docx4J.createFOSettings();
      foSettings.setWmlPackage(mlPackage);
      Docx4J.toFO(foSettings, os, Docx4J.FLAG_EXPORT_PREFER_XSL);

   }catch(Exception ex){
      ex.printStackTrace();
   }finally {
      IOUtils.closeQuietly(os);
   }
}

你可能感兴趣的:(Docx4j)