当前位置: 首页 > news >正文

SpringBoot 基于iText 根据PDF模板动态生成文件

SpringBoot 基于iText 根据PDF模板动态生成文件, 需要使用 adobe acrobat pro DC这个工具来自定义模板
支持根据PDF模板生成单页或多页PDF文件

adobe acrobat pro DC 自定义模板

下载地址

链接:https://pan.baidu.com/s/1Vn3bIQ5_D17sEZnkF2t7gg?pwd=n6o1 
提取码:n6o1

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

添加依赖

 <dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.4.2</version></dependency>

代码集成


import cn.hutool.core.io.resource.ClassPathResource;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** @author wang*/
@Slf4j
public class PdfUtil {private PdfUtil() {}/*** generatePdf* @param params    params* @param outputPath    outputPath* @return  String*/public static String generatePdf(Map<String, String> params, String outputPath) {ClassPathResource resource = new ClassPathResource("templates/test_certificate_temp.pdf");InputStream inputStream = resource.getStream();ByteArrayOutputStream bos = null;PdfReader reader = null;FileOutputStream fos = null;try {reader = new PdfReader(inputStream);bos = new ByteArrayOutputStream();writePdf(params, bos, reader);fos = new FileOutputStream(outputPath);bos.writeTo(fos);} catch (Exception e) {log.error(e.getMessage(), e);return null;} finally {try {assert bos != null;bos.close();reader.close();assert fos != null;fos.close();} catch (IOException e) {log.error(e.getMessage(), e);}}return outputPath;}/*** generateMultiPagePdf** @param paramsList paramsList* @param outputPath outputPath* @return String*/public static String generateMultiPagePdf(List<Map<String, String>> paramsList, String outputPath) {FileOutputStream fos = null;PdfCopy copy = null;Document document = null;try {ClassLoader classLoader = Thread.currentThread().getContextClassLoader();InputStream inputStream = classLoader.getResourceAsStream("templates/test_certificate_temp.pdf");// 将模板读取到字节数组中assert inputStream != null;byte[] templateBytes = inputStream.readAllBytes();inputStream.close();fos = new FileOutputStream(outputPath);document = new Document();copy = new PdfCopy(document, fos);document.open();for (Map<String, String> params : paramsList) {ByteArrayOutputStream bos = new ByteArrayOutputStream();InputStream templateStream = new ByteArrayInputStream(templateBytes);PdfReader reader = new PdfReader(templateStream);writePdf(params, bos, reader);reader.close();templateStream.close();PdfReader pageReader = new PdfReader(new ByteArrayInputStream(bos.toByteArray()));copy.addPage(copy.getImportedPage(pageReader, 1));pageReader.close();}} catch (Exception e) {e.printStackTrace();return null;} finally {try {if (document != null) {document.close();}if (copy != null) {copy.close();}if (fos != null) {fos.close();}} catch (IOException e) {e.printStackTrace();}}return outputPath;}private static void writePdf(Map<String, String> params, ByteArrayOutputStream bos, PdfReader reader) throws DocumentException, IOException {PdfStamper pdfStamper = new PdfStamper(reader, bos);AcroFields acroFields = pdfStamper.getAcroFields();BaseFont font = BaseFont.createFont();for (Map.Entry<String, String> param : params.entrySet()) {acroFields.setFieldProperty(param.getKey(), "textfont", font, null);acroFields.setField(param.getKey(), param.getValue());}pdfStamper.setFormFlattening(true);pdfStamper.close();}public static void main(String[] args) throws IOException {List<Map<String, String>> paramsList = new ArrayList<>();Map<String, String> params = new HashMap<>(16);params.put("hullId", "hullId_001");params.put("boatYear", "boatYear_001");params.put("boatBrand", "boatBrand_001");params.put("boatModel", "boatModel_001");paramsList.add(params);params = new HashMap<>(16);params.put("hullId", "hullId_002");params.put("boatYear", "boatYear_002");params.put("boatBrand", "boatBrand_002");params.put("boatModel", "boatModel_002");paramsList.add(params);String outputPath = "D:\\opt\\file_encode_zip\\target\\test_Certificate_8-20-24_target.pdf";String path = generateMultiPagePdf(paramsList, outputPath);
//        String path = generatePdf(params, outputPath);System.out.println(path);}
}

相关文章:

  • OSError: [E050] Can‘t find model ‘en_core_web_sm‘.
  • Python爬虫(一文通)
  • OverflowError: cannot convert float infinity to integer
  • Golang使用Quic-Go开源库实现Quic客户端和服务端
  • 企业数据治理之主数据---供应商主数据
  • Java核心API——io类缓冲流
  • 什么是杨氏模量
  • 22AP10 SS524 平替 海思HI3521DV200 可提供开发资料
  • IP-RDS-222、IP-PRZ-59-AM12、EG-TRZ-42-L、EG-TRZ-42-H比例减压阀放大器
  • Qt详解QHostInfo
  • 【python报错已解决】AttributeError: module ‘PIL.Image‘ has no attribute ‘ANTIALIAS‘
  • 对标GPT4o,智谱推出新一代基座大模型 GLM-4-Plus
  • JDBC和Mybatis中的批处理
  • 【Python数据分析】numpy中的npz和npy的用法和区别
  • scrapy框架--快速了解
  • Android框架之Volley
  • docker python 配置
  • es6要点
  • isset在php5.6-和php7.0+的一些差异
  • JavaScript HTML DOM
  • JavaScript创建对象的四种方式
  • JS字符串转数字方法总结
  • Mac 鼠须管 Rime 输入法 安装五笔输入法 教程
  • Meteor的表单提交:Form
  • mysql常用命令汇总
  • RxJS 实现摩斯密码(Morse) 【内附脑图】
  • Spring-boot 启动时碰到的错误
  • vue.js框架原理浅析
  • 阿里云Kubernetes容器服务上体验Knative
  • 动态规划入门(以爬楼梯为例)
  • 关于Android中设置闹钟的相对比较完善的解决方案
  • 前端_面试
  • 驱动程序原理
  • 我的业余项目总结
  • 字符串匹配基础上
  • 资深实践篇 | 基于Kubernetes 1.61的Kubernetes Scheduler 调度详解 ...
  • ​LeetCode解法汇总1410. HTML 实体解析器
  • #大学#套接字
  • #免费 苹果M系芯片Macbook电脑MacOS使用Bash脚本写入(读写)NTFS硬盘教程
  • (14)学习笔记:动手深度学习(Pytorch神经网络基础)
  • (Windows环境)FFMPEG编译,包含编译x264以及x265
  • (附源码)node.js知识分享网站 毕业设计 202038
  • (附源码)ssm码农论坛 毕业设计 231126
  • (经验分享)作为一名普通本科计算机专业学生,我大学四年到底走了多少弯路
  • (六) ES6 新特性 —— 迭代器(iterator)
  • (四)js前端开发中设计模式之工厂方法模式
  • (一)u-boot-nand.bin的下载
  • (转)Oracle 9i 数据库设计指引全集(1)
  • (转)创业家杂志:UCWEB天使第一步
  • .net 前台table如何加一列下拉框_如何用Word编辑参考文献
  • /etc/fstab和/etc/mtab的区别
  • @angular/cli项目构建--Dynamic.Form
  • @RequestBody详解:用于获取请求体中的Json格式参数
  • [ vulhub漏洞复现篇 ] ECShop 2.x / 3.x SQL注入/远程执行代码漏洞 xianzhi-2017-02-82239600
  • [ vulhub漏洞复现篇 ] GhostScript 沙箱绕过(任意命令执行)漏洞CVE-2019-6116