使用poi根据模板生成word以及word转pdf的demo

注意这里使用的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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值