最近項目需要實現(xiàn)pdf下載的功能,由于沒有這方面的經(jīng)驗,從網(wǎng)上花了很長時間查找了相關(guān)的資料。整理之后,發(fā)現(xiàn)有幾個框架可以實現(xiàn)這個功能。
1. 開源框架支持
- itext,生成pdf文檔,還支持將xml、html文件轉(zhuǎn)化為pdf文件;
- apache pdfbox,生成、合并pdf文檔;
- docx4j,生成docx文檔,支持轉(zhuǎn)換為pdf格式。
2. 實現(xiàn)方案
比較了一番后,采用了freemarker+docx4j+apache pdfbox的方案:
maven依賴
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
<!-- 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文檔對應(yīng)的word(docx)制作出來
2 把word文檔另存為xml文件
另存為xml
3 將xml文件制作為freemarker模版(ftl)文件
制作模版文件
4 將數(shù)據(jù)和ftl文件組裝為xml文本
1
2
3
4
5
6
7
8
|
map<string, object> map = new hashmap<>(); map.put( "name" , "小明" ); map.put( "address" , "北京市朝陽區(qū)" ); stringwriter stringwriter = new stringwriter(); bufferedwriter writer = new bufferedwriter(stringwriter); template.process(map, writer); string xmlstr = stringwriter.tostring(); |
5 使用docx4j將xml文本加載為word文檔對象
1
2
|
bytearrayinputstream in = new bytearrayinputstream(xmlstr.getbytes()); wordprocessingmlpackage wordmlpackage = wordprocessingmlpackage.load(in); |
6 使用docx4j將word文檔轉(zhuǎn)存為pdf文檔
1
2
|
string outputfilepath = "/users/xiaoming/簡歷.pdf" ; docx4j.topdf(wordmlpackage, new fileoutputstream( new file(outputfilepath))); |
7 使用apache pdfbox將多個pdf文檔合為一個
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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()); |
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.jianshu.com/p/b89f6ea30585