当前位置:网站首页>Itext 7 生成PDF总结
Itext 7 生成PDF总结
2022-07-06 09:18:00 【Demon Lord(大魔王)】
前言:生成pdf有很多种方法,本文使用itextpdf 7 生成
1、根据PDF的需求分为静态数据动态数据以及特殊数据
1).静态数据是数据固定,所以我们采用模板的方式进行生成-----itextpdf + Adobe Acrobat DC 填充模板生成
Adobe Acrobat DC可以在网上下载绿色版
(1).先将文件通过WPS生成PDF文件
(2).用Adobe Acrobat DC打开文件进行准备表单
(3).配置好对应字段的表单域
(4).传入数据进行打印
2).动态数据是数据不固定的,需要采用代码生成的方式进行---itext 7API 的官方地址iText 7 7.1.5 API
(1).添加依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.5</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>kernel</artifactId>
<version>7.1.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>io</artifactId>
<version>7.1.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>layout</artifactId>
<version>7.1.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>forms</artifactId>
<version>7.1.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>pdfa</artifactId>
<version>7.1.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>sign</artifactId>
<version>7.1.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>barcodes</artifactId>
<version>7.1.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>hyph</artifactId>
<version>7.1.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>font-asian</artifactId>
<version>7.1.5</version>
</dependency>最后附上是我写好的第一版万能打印模板
Util工具类
/**
* @author f
* @date 2021/9/28 16:56
*/
public class PrintUtil {
/**
* 中文字体
*
* @return
* @throws IOException
*/
public static PdfFont typeface() throws IOException {
return PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H", true);
}
/**
* 模板数据
*
* @param map formFields
*/
public static void templateData(Map<String, String> map, Map<String, PdfFormField> formFields) throws IOException {
for (Map.Entry<String, String> entry : map.entrySet()) {
PdfFormField agreementId = formFields.get(entry.getKey());
if (agreementId != null) {
agreementId.setFont(typeface()).setFontSize(14);
agreementId.setValue(String.valueOf(entry.getValue()));
}
}
}
/**
* 模板数据集合
*
* @param list formFields
*/
public static void templateDatas(List<Map<String, String>> list, Map<String, PdfFormField> formFields) throws IOException {
int i = 0;
for (Map<String, String> map : list) {
i++;
for (Map.Entry<String, String> entry : map.entrySet()) {
PdfFormField agerrmentId = formFields.get(entry.getKey() + "_" + i);
if (agerrmentId != null) {
agerrmentId.setFont(typeface()).setFontSize(14);
agerrmentId.setValue(String.valueOf(entry.getValue()));
}
}
}
}
/**
* 需要翻译好字段 与模板配置完成的相匹配
*
* @param estimate formFields
*/
public static void estimate(Map<String, String> estimate, Map<String, PdfFormField> formFields) throws IOException {
for (Map.Entry<String, String> entry : estimate.entrySet()) {
PdfFormField agerrmentId1 = formFields.get(entry.getValue());
if (StringUtils.isNotBlank(entry.getValue()) && agerrmentId1 != null) {
agerrmentId1.setFont(typeface()).setFontSize(14);
agerrmentId1.setValue("√");
}
}
}
/**
* 表单标题
*
* @param header
* @throws IOException
*/
public static Paragraph header(String header) throws IOException {
return new Paragraph(header)
//设置字体
.setFont(typeface())
//设置字体大小
.setFontSize(20)
//字体加粗
.setBold()
//设置水平居中
.setTextAlignment(TextAlignment.CENTER)
//行高
.setFixedLeading(80);
}
/**
* 表单数据
*
* @return
* @throws IOException
*/
public static Table table(List<Map<String, String>> map, Map<String, String> biaotou) throws IOException {
//4.创建一个 Table 对象
int size = biaotou.entrySet().size();
UnitValue[] percentArray = UnitValue.createPercentArray(size);
Table table = new Table(percentArray)
.setFont(typeface())
//垂直居中
.setVerticalAlignment(VerticalAlignment.MIDDLE)
//水平居中
.setTextAlignment(TextAlignment.CENTER)
.setFontSize(18)
//自动布局
.setAutoLayout()
//动态列表超出表的宽度 使用固定布局
// .setFixedLayout()
//100%
.useAllAvailableWidth();
//表头
for (Map.Entry<String, String> entry : biaotou.entrySet()) {
table.addCell(entry.getValue());
}
for (Map<String, String> map1 : map) {
for (Map.Entry<String, String> entry : map1.entrySet()) {
table.addCell(entry.getValue());
}
}
return table;
}
/**
* 返回文件流
*
* @param newPDFPath
* @param response
* @throws IOException
*/
public static void file(String newPDFPath, HttpServletResponse response) throws IOException {
//读取路径下面的文件
File file = new File(newPDFPath);
//读取指定路径下面的文件
InputStream in = new FileInputStream(file);
response.setContentType("application/pdf");
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
//创建存放文件内容的数组
byte[] buff = new byte[1024];
//所读取的内容使用n来接收
int n;
//当没有读取完时,继续读取,循环
while ((n = in.read(buff)) != -1) {
//将字节数组的数据全部写入到输出流中
outputStream.write(buff, 0, n);
}
if ((n = in.read(buff)) == -1) {
//强制将缓存区的数据进行输出
outputStream.flush();
//关流
outputStream.close();
in.close();
}
}
}实体类
/**
* pdf模板视图实体类
*
* @author f
* @since 2021-09-17
*/
@Data
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "PrintVO对象", description = "pdf模板")
public class PrintVO extends Print {
private static final long serialVersionUID = -5917961640607855978L;
@ApiModelProperty(value = "模板数据")
private Map<String, String> map;
@ApiModelProperty(value = "模板数据集合")
private List<Map<String, String>> list;
@ApiModelProperty(value = "特殊数据")
private Map<String, String> estimate;
@ApiModelProperty(value = "表题")
private String header;
@ApiModelProperty(value = "表单表头")
private Map<String, String> biaotou;
@ApiModelProperty(value = "表单数据")
private List<Map<String, String>> table;
@ApiModelProperty(value = "表题1")
private String header1;
@ApiModelProperty(value = "表单表头")
private Map<String, String> biaotou1;
@ApiModelProperty(value = "表单数据")
private List<Map<String, String>> table1;
}controller层
/**
* 打印
*/
@PostMapping("/template")
@ApiOperationSupport(order = 9)
@ApiOperation(value = "打印", notes = "PDF模板")
public void template(@RequestBody PrintVO print, HttpServletResponse response, @RequestParam String id) {
printService.template(print, response, id);
}service层
/**
* PDF模板 服务实现类
*
* @author f
* @since 2021-09-17
*/
@Service
public class PrintServiceImpl extends ServiceImpl<PrintMapper, Print> implements IPrintService {
@Override
public void template(PrintVO print, HttpServletResponse response, String id) {
// 模板路径
Print print1 = new Print();
print1.setId(Long.valueOf(id));
Print detail = this.getOne(Condition.getQueryWrapper(print1));
String templatePath = detail.getFileName();
if (templatePath == null) {
throw new ServiceException("模板不存在");
}
// 生成的新文件路径
String newPDFPath = "\\模板.pdf";
try {
PdfDocument pdfDoc = new PdfDocument(new PdfReader(templatePath), new PdfWriter(newPDFPath));
PdfAcroForm pdfAcroForm = PdfAcroForm.getAcroForm(pdfDoc, true);
Map<String, PdfFormField> formFields = pdfAcroForm.getFormFields();
//模板数据
Map<String, String> map = print.getMap();
if (map != null) {
PrintUtil.templateData(map, formFields);
}
//模板数据集合
List<Map<String, String>> list = print.getList();
if (list != null) {
PrintUtil.templateDatas(list, formFields);
}
//特殊判断数据
Map<String, String> estimate = print.getEstimate();
if (estimate != null) {
PrintUtil.estimate(estimate, formFields);
}
//设置生成表单不可编辑
pdfAcroForm.flattenFields();
//生成表单标题
String ti = print.getHeader();
Document document = new Document(pdfDoc);
//表头数据
Map<String, String> biaotou = print.getBiaotou();
//表单数据
List<Map<String, String>> biaodan = print.getTable();
if (biaodan != null && biaotou != null) {
if (map != null || list != null || estimate != null) {
document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
}
Paragraph header = PrintUtil.header(ti);
document.add(header);
document.add(PrintUtil.table(biaodan, biaotou));
}
//第二个动态表单生成
String ti2 = print.getHeader();
if (ti2 != null) {
//表头数据
Map<String, String> biaotou1 = print.getBiaotou1();
//表单数据
List<Map<String, String>> biaodan1 = print.getTable1();
if (biaodan1 != null && biaotou1 != null) {
document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
Paragraph header = PrintUtil.header(ti2);
document.add(header);
document.add(PrintUtil.table(biaodan1, biaotou1));
}
}
//关闭
pdfDoc.close();
document.close();
PrintUtil.file(newPDFPath, response);
} catch (IOException e) {
e.printStackTrace();
}
}
}边栏推荐
- Force buckle 1189 Maximum number of "balloons"
- @Autowired 和 @Resource 的区别
- rtklib单点定位spp使用抗差估计遇到的问题及解决
- 第一人称视角的角色移动
- Remember an experience of ECS being blown up by passwords - closing a small black house, changing passwords, and changing ports
- How to improve the deletion speed of sequential class containers?
- Fabrication d'un sac à dos simple fairygui
- Solution to the problem of automatic login in Yanshan University Campus Network
- [Leetcode15]三数之和
- Compilation principle: preprocessing of source program and design and implementation of lexical analysis program (including code)
猜你喜欢

【干货】提升RTK模糊度固定率的建议之周跳探测

Pytorch: tensor operation (I) contiguous

Esp8266 connect onenet (old mqtt mode)

Easy to use shortcut keys in idea

程序设计大作业:教务管理系统(C语言)

CUDA C programming authoritative guide Grossman Chapter 4 global memory

Affichage du changement de valeur du Buff de gain de l'interface graphique de défaillance

Mysql database reports an error: row size too large (> 8126) Changing some columns to TEXT or BLOB or using ROW_ FORMAT=DY

FairyGUI条子家族(滚动条,滑动条,进度条)

地球围绕太阳转
随机推荐
KF UD分解之UD分解基础篇【1】
Gateway 根据服务名路由失败,报错 Service Unavailable, status=503
By v$rman_ backup_ job_ Oracle "bug" caused by details
The service robots that have been hyped by capital and the Winter Olympics are not just a flash in the pan
What is the maximum length of MySQL varchar field
燕山大学校园网自动登录问题解决方案
Vulnhub target: hacknos_ PLAYER V1.1
[offer9]用两个栈实现队列
Unity scene jump and exit
JS Title: input array, exchange the largest with the first element, exchange the smallest with the last element, and output array.
Fairygui gain buff value change display
Office提示您的许可证不是正版弹框解决
Fabrication of fairygui simple Backpack
FairyGUI人物状态弹窗
FairyGUI增益BUFF數值改變的顯示
[leetcode622] design circular queue
PRIDE-PPPAR源码解析
idea中好用的快捷键
It has been solved by personal practice: MySQL row size too large (> 8126) Changing some columns to TEXT or BLOB or using ROW_ FORMAT
Lean product development - Lean Software Development & lean product development