1. 先word转成xml–template.xml(可自行搜索转法)
  2. 代码转成word
  3. 代码获取word转成pdf
  4. License 文件网上很多

如下图:

word转pdf ,亲测-好用,欢迎尝试!!_xml


xml 格式如下图:

word转pdf ,亲测-好用,欢迎尝试!!_文件名_02

String fileName = TempleteEnum.getNameByCode(contractApplyDto.getContractTemplete()) ;

fileName = new String(fileName.getBytes(“utf-8”),“ISO8859-1”) +“.docx”;

Writer out = null;

File outFile = new File(fileName);

out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),“UTF-8”));

    Template t = null;

   //文件名,获取模板

   t = configuration.getTemplate("template.xml", "utf-8");

   t.process(dataMap, out);

   out.close();


   if (!getLicense()) {

       // 验证License 若不验证则转化出的pdf文档会有水印产生

       throw new CommonException("未通过License验证...");

   }


   FileOutputStream os = null;

   File file = null;

   try {

       // word转pdf

       String fileNameComm = TempleteEnum.getNameByCode(contractApplyDto.getContractTemplete());

       InputStream inStreamFile = new FileInputStream(outFile);

       long oldTime = System.currentTimeMillis();

       // 新建一个空白pdf文档

       file = new File(fileNameComm + ".pdf");

       os = new FileOutputStream(file);

       // Address是将要被转化的word文档

       Document doc = new Document(inStreamFile);

       // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,

       doc.save(os, SaveFormat.PDF);

       // EPUB, XPS, SWF 相互转换

       long nowTime = System.currentTimeMillis();

       // 转化用时

       log.info("pdf转换成功,共耗时:" + ((nowTime - oldTime) / 1000.0) + "秒");


       // pdf下载转换

       fileNameComm = new String(fileNameComm.getBytes("utf-8"),"ISO8859-1") +".pdf";

       InputStream inStream = new FileInputStream(file);

       response.setContentType("application/ms-excel;charset=UTF-8");

       response.setHeader("Content-Disposition","attachment;filename="+ fileNameComm);

       // 循环取出流中的数据

       byte[] b = new byte[1024];

       int len;

       while ((len = inStream.read(b)) > 0) {

           response.getOutputStream().write(b, 0, len);

       }

       inStream.close();

       response.getOutputStream().close();

       inStreamFile.close();

       outFile.delete();

       file.delete();


   } catch (Exception e) {

       e.printStackTrace();

   }finally {

       if (os != null) {

           try {

               os.flush();

               os.close();

               outFile.delete();

               file.delete();

           } catch (IOException e) {

               e.printStackTrace();

           }

       }

   }