注意这里使用的poi版本为3.14,高版本会引起问题,请慎重引用!
调用方式可参考如下
//模板文件地址 String realPath=""; String inputUrl = realPath+"/test0.docx"; //新生产的模板文件 String outputUrl =realPath+"/report"+System.currentTimeMillis()+".docx"; //生成word //表格参数 List<String[]> list = new ArrayList<String[]>(); //先生成word Map<String, Object> testMap = new HashMap<String, Object>(); testMap.put("name","监测站"); //图片参数 String fileImg=""; Map<String,Object> picture = new HashMap<String, Object>(); picture.put("width", 618); picture.put("height", 516); picture.put("type", "png"); picture.put("content", WordUtils.inputStream2ByteArray(new FileInputStream(fileImg), true)); testMap.put("header",picture); WordUtils.changWord(inputUrl, outputUrl, testMap, list); //转pdf File file = new File(outputUrl); String pdfNameUrl = this.itextDocx2Pdf(realPath, file); //获取文件流给前端预览下载 File filePdf = new File(pdfNameUrl); /** * docx的word转pdf * @param localPath * @param inputWordFile */ public String itextDocx2Pdf (String localPath, File inputWordFile) { String docxPath = localPath + "/" + inputWordFile.getName(); String pdfName = inputWordFile.getName(); pdfName = localPath + "/" + pdfName.substring(0, pdfName.indexOf("."))+ ".pdf"; String imageDir = localPath + "/image/"; String docxHtml = itextpdf.docx2Html(docxPath, imageDir); docxHtml = itextpdf.formatHtml(docxHtml); itextpdf.htmlToPdf(docxHtml, pdfName); return pdfName; }
代码中使用的demo在如下资源中CSDN
需要引入的pom依赖
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.14</version> </dependency>
<!-- word转pdf itextpdf window、linux环境 begin --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.14</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>3.14</version> </dependency> <dependency> <groupId>fr.opensagres.xdocreport</groupId> <artifactId>xdocreport</artifactId> <version>1.0.6</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>ooxml-schemas</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.11</version> </dependency> <dependency> <groupId>com.itextpdf.tool</groupId> <artifactId>xmlworker</artifactId> <version>5.5.11</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency> <!-- jsoup --> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.11.3</version> </dependency>