java生成pdf文件·pdfbox

PDF生成方案比较

开源框架支持

  • iText:生成PDF文档,还支持将XML、Html文件转化为PDF文件

  • Apache PDFBox:生成、合成PDF文档

  • docx4j:生成docx、pptx、xlsx文档,支持转换为PDF格式

比较

  • iText开源协议为AGPL,而其他两个框架协议均为Apache License V2.0
  • 使用PDFBox生成PDF就像画图似的,文字和图像根据页面坐标画上去的,需要根据字数手动换行
  • docx4j用来生成docx文档,提供了将WORD文档转换为PDF文档的功能,并不能直接生成PDF文档
应用 格式复杂 格式简单
数据量大 docx4j+freemarker docx4j或PDFBox
数据量小 docx4j PDFBox

鉴于iText的协议为AGPL具有极强的传染性,本文以Apache PDFBox为例来讲解

pdfbox通过pdf模板生成PDF文件

本人在项目中遇到的是基于pdf的form表单模板来生成pdf文件

通过Maven引入依赖

1
2
3
4
5
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-app</artifactId>
<version>2.0.22</version>
</dependency>

使用示例

  1. 准备好表单数据
  2. 加载pdf模板文件
  3. 加载自定义字体
  4. 遍历表单属性并填充值
  5. 导出PDF文件
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package com.panda.copyright;
import org.apache.fontbox.ttf.OTFParser;
import org.apache.fontbox.ttf.OpenTypeFont;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.image.CCITTFactory;
import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory;
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceStream;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.pdmodel.interactive.form.PDPushButton;
import org.apache.pdfbox.pdmodel.interactive.form.PDTextField;
import org.apache.pdfbox.util.filetypedetector.FileType;
import org.apache.pdfbox.util.filetypedetector.FileTypeDetector;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class PdfGenerate {
public static void main(String[] args) throws Exception{
//1. 准备表单数据
Map<String,String> mappers = new ConcurrentHashMap<>();
mappers.put("name", "幸福美少女");
mappers.put("authors","新的篇章");
mappers.put("publish_time","2021-02-04");
mappers.put("qr_code","/temp/pdfbox/images/3a7b285459e.png");
mappers.put("pro_file1","/temp/pdfbox/images/file1.jpg");
//2. 加载pdf模板文件
InputStream in = null;
try{
String outPath = "/temp/pdfbox/copyright_20210204.pdf";
in = PdfGenerate.class.getResourceAsStream("/template/copyright.pdf");
PDDocument document = PDDocument.load(in);
//3. 加载自定义字体
PDAcroForm form = document.getDocumentCatalog().getAcroForm();
//ttf字体,实际上还有PDType1Font,PDType3Font,一般ttf就用PDType0Font足以
PDFont ttfFont= PDType0Font.load(document, new File("/temp/fonts/Dengl.ttf"));
//otf字体
OTFParser otfParser = new OTFParser();
OpenTypeFont otf = otfParser.parse(PdfGenerate.class.getResourceAsStream("/template/copyright.otf"));
PDType0Font otfFont = PDType0Font.load(document,otf, false);
/* 设置全局默认字体 或某个页面设置字体:实例化字体对象了之后,将它添加到PDPage的Resource中。
PDPage page= new PDPage(PDRectangle.A4);
page.getResources().add(ttfFont);*/
PDResources resources = new PDResources();
//字体名称跟模板中设置的有关
resources.put(COSName.getPDFName("AdobeSongStd-Light"), otfFont);
resources.put(COSName.getPDFName("F4"), otfFont);
form.setDefaultResources(resources);
//可设置单个表单属性的字体及格式
String otffont_name = form.getDefaultResources().add(otfFont).getName();
//4. 遍历表单属性并填充值
List<PDField> fields = document.getDocumentCatalog().getAcroForm().getFields();
for (PDField field : fields) {
if ("qr_code".equals(field.getFullyQualifiedName())){
setImgField(document, field, certImg.get("qr_code"),1);
}else if ("pro_file1".equals(field.getFullyQualifiedName())){
setImgField(document, field, certImg.get("pro_file1"),1);
}else{
PDTextField textField = (PDTextField) field;
if("name".equals(field.getFullyQualifiedName()){
//设置字体 字号
textField.setDefaultAppearance(String.format("/%s 16 Tf 0 g", font_name));
}
if("authors".equals(field.getFullyQualifiedName()){
//修改位置
PDAnnotationWidget widget = textField.getWidgets().get(0);
PDRectangle rect = new PDRectangle(name.getLowerLeftX(),368.15F,name.getWidth(),name.getHeight());
widget.setRectangle(rect);
//设置字体 字号
textField.setDefaultAppearance(String.format("/%s 12 Tf 0 g", font_name));
}
//publish_time使用全局默认设置的字体
//设置值
if(mappers.containsKey(field.getFullyQualifiedName())){
field.setValue(mappers.get(field.getFullyQualifiedName()));
}
//设置只读,表单内容不可编辑
field.setReadOnly(true);
}
}
//5. 保持pdf文件
document.save(outPath);
//最后需要关闭它
document.close();
}catch(IOException){
e.printStackTrace();
}finally{
if(in!=null){
in.close();
}
}
}
/**
* 处理图片
*/
private static void setImgField(PDDocument document, PDField field, String filePath, int pageIndex) throws IOException{
File imageFile = new File(filePath);
if (imageFile.exists()){
/*
* BufferedImage bufferedImage = ImageIO.read(imageFile);
* PDImageXObject pdImageXObject = LosslessFactory.createFromImage(document, bufferedImage);
*/
PDImageXObject image = PDImageXObject.createFromFile(filePath, document);
PDRectangle rectangle = getFieldArea(field);
//float size = rectangle.getHeight();
float x = rectangle.getLowerLeftX();
float y = rectangle.getLowerLeftY();
float imageHeight = image.getHeight();
float imageWidth = image.getWidth();
float signRectHeight = rectangle.getHeight(), sighRectWidth = rectangle.getWidth();
PDPageContentStream contentStream = new PDPageContentStream(document, document.getPage(pageIndex), PDPageContentStream.AppendMode.APPEND, true);
float imgBi = imageWidth/imageHeight;
float signBi = sighRectWidth/signRectHeight;
float margin = 0;
if (imgBi > signBi){
float recHeight = sighRectWidth*imageHeight/imageWidth;
margin = (signRectHeight-recHeight)/2;
contentStream.drawImage(image, x, y + margin, sighRectWidth, recHeight);
}else{
float recWidth = signRectHeight*imageWidth/imageHeight;
margin = (sighRectWidth - recWidth)/2;
contentStream.drawImage(image, x + margin, y,recWidth, signRectHeight);
}
contentStream.close();
field.setReadOnly(true);
} else {
System.err.println("File " + filePath + " not found");
}
}
/**
* 获取文字坐标
*/
private static PDRectangle getFieldArea(PDField field) {
COSDictionary fieldDict = field.getCOSObject();
COSArray fieldAreaArray = (COSArray) fieldDict.getDictionaryObject(COSName.RECT);
return new PDRectangle(fieldAreaArray);
}
}