Java 生成PDF文档 Java 生成PDF文档的代码实例
翼小白 人气:0最近项目需要实现PDF下载的功能,由于没有这方面的经验,从网上花了很长时间查找了相关的资料。整理之后,发现有几个框架可以实现这个功能。
1. 开源框架支持
- iText,生成PDF文档,还支持将XML、Html文件转化为PDF文件;
- Apache PDFBox,生成、合并PDF文档;
- docx4j,生成docx文档,支持转换为PDF格式。
2. 实现方案
比较了一番后,采用了FreeMarker+docx4j+Apache PDFBox的方案:
maven依赖
<!-- pdfbox --> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.11</version> </dependency> <!-- docx4j --> <dependency> <groupId>org.docx4j</groupId> <artifactId>docx4j</artifactId> <version>3.3.7</version> </dependency> <dependency> <groupId>org.apache.xmlgraphics</groupId> <artifactId>batik-util</artifactId> <version>1.10</version> </dependency> <dependency> <groupId>org.docx4j</groupId> <artifactId>docx4j-export-fo</artifactId> <version>3.3.6</version> </dependency> <!-- https://mvnrepository.com/artifact/dom4j/dom4j --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <!-- image --> <dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.8</version> </dependency> <!-- json --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>
步骤
1 把pdf文档对应的word(docx)制作出来
2 把word文档另存为xml文件
另存为xml
3 将xml文件制作为freemarker模版(ftl)文件
制作模版文件
4 将数据和ftl文件组装为xml文本
Map<String, Object> map = new HashMap<>(); map.put("name", "小明"); map.put("address", "北京市朝阳区"); map.put("email", "xiaoming@abc.com"); StringWriter stringWriter = new StringWriter(); BufferedWriter writer = new BufferedWriter(stringWriter); template.process(map, writer); String xmlStr = stringWriter.toString();
5 使用docx4j将xml文本加载为word文档对象
ByteArrayInputStream in = new ByteArrayInputStream(xmlStr.getBytes()); WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(in);
6 使用docx4j将word文档转存为pdf文档
String outputfilepath = "/Users/xiaoming/简历.pdf"; Docx4J.toPDF(wordMLPackage, new FileOutputStream(new File(outputfilepath)));
7 使用Apache PDFbox将多个pdf文档合为一个
String folderName = "/Users/xiaoming/pdfs"; String destPath = "/Users/xiaoming/all.pdf"; PDFMergerUtility mergePdf = new PDFMergerUtility(); String[] filesInFolder = getFiles(folderName); Arrays.sort(filesInFolder, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareTo(o2); } }); for (int i = 0; i < filesInFolder.length; i++) { mergePdf.addSource(folderName + File.separator + filesInFolder[i ]); } mergePdf.setDestinationFileName(destPath); mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
加载全部内容