Java使用IText根据pdf模板创建pdf文件

2024-04-26 10:04
文章标签 java 模板 使用 创建 pdf itext

本文主要是介绍Java使用IText根据pdf模板创建pdf文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.导包

 <dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.10</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.11.0</version>
</dependency>

2.绘制pdf模板
在这里插入图片描述
3.示例代码

/*** 读取pdf模板填充生成pdf文件并转为字节数组* @return*/
public byte[] createPdf() {//获取源数据(一般从数据库查询,此处通过构造数据简化处理)List<Plan> plans = this.getPlans();final int size = plans.size();//临时文件final String outputFilePath = "D:/" + System.currentTimeMillis() + ".pdf";OutputStream os = null;PdfStamper ps = null;PdfReader reader = null;PdfReader reader2 = null;Document document = null;ByteArrayOutputStream byteArrayOutputStream = null;PdfCopy pdfNew = null;try {//读入pdf表单reader = new PdfReader(this.getClass().getResourceAsStream("/template/test.pdf"));//根据表单生成一个新的pdfos = Files.newOutputStream(new File(outputFilePath).toPath());ps = new PdfStamper(reader, os);//获取pdf表AcroFields form = ps.getAcroFields();form.setField("contractNo", "HT2024042501");//合同号form.setField("paymentDate", "2022-12-01");//放款日期form.setField("expiredDate", "2023-12-01");//到期日期ps.setFormFlattening(true);List<AcroFields.FieldPosition> table = form.getFieldPositions("table");Rectangle rect = table.get(0).position;PdfPTable pTable = new PdfPTable(8);BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);Font fontZH = new Font(bfChinese, 10f, 0);pTable.getDefaultCell().setHorizontalAlignment(1);pTable.setWidthPercentage(100.0f);float totalWidth = rect.getRight() - rect.getLeft() - 1;//计算表格宽度float[] columnWidth = {(float) (totalWidth * 0.05), (float) (totalWidth * 0.15), (float) (totalWidth * 0.15), (float) (totalWidth * 0.15), (float) (totalWidth * 0.15), (float) (totalWidth * 0.13), (float) (totalWidth * 0.13), (float) (totalWidth * 0.09)};pTable.setTotalWidth(columnWidth);pTable.setLockedWidth(true);for (Plan plan : plans) {Integer periodNo = plan.getPeriodNo();int border = (periodNo % 12 == 0 || periodNo == size) ? Rectangle.BOTTOM : Rectangle.NO_BORDER;pTable.addCell(generateCell(String.valueOf(periodNo), border, fontZH));pTable.addCell(generateCell(plan.getMatchDate(), border, fontZH));pTable.addCell(generateCell(plan.getRepayOriginal(), border, fontZH));pTable.addCell(generateCell(plan.getPenalty(), border, fontZH));pTable.addCell(generateCell(plan.getRepayAmount(), border, fontZH));pTable.addCell(generateCell(plan.getRestOriginal(), border, fontZH));pTable.addCell(generateCell(plan.getRepayDate(), border, fontZH));pTable.addCell(generateCell(plan.getRepayStatus(), border, fontZH));}pTable.setKeepTogether(true);pTable.setSplitLate(false);pTable.setSplitRows(true);//计算需要分页的总页数int totalpage = size % 12 == 0 ? size / 12 : size / 12 + 1;if (totalpage == 1) {//获table页面PdfContentByte under = ps.getOverContent(1);//添加tablepTable.writeSelectedRows(0, -1, rect.getLeft(), rect.getTop(), under);} else {for (int i = 1; i <= totalpage; i++) {PdfContentByte under = ps.getOverContent(i);if (i == 1) {pTable.writeSelectedRows(0, 12, rect.getLeft(), rect.getTop(), under);} else {pTable.writeSelectedRows((i - 1) * 12, i * 12, rect.getLeft(), rect.getTop(), under);}}}ps.close();reader2 = new PdfReader(outputFilePath);document = new Document(reader2.getPageSizeWithRotation(1));byteArrayOutputStream = new ByteArrayOutputStream();pdfNew = new PdfCopy(document, byteArrayOutputStream);document.open();PdfImportedPage page;for (int i = 1; i <= totalpage; i++) {page = pdfNew.getImportedPage(reader2, i);pdfNew.addPage(page);}document.close();os.close();pdfNew.close();reader.close();reader2.close();FileUtils.delete(new File(outputFilePath));return byteArrayOutputStream.toByteArray();} catch (Exception e) {e.printStackTrace();} finally {try {if (ps != null) {ps.close();}if (reader != null) {reader.close();}if (os != null) {os.close();}if (document != null) {document.close();}if (pdfNew != null) {pdfNew.close();}if (reader2 != null) {reader2.close();}if (byteArrayOutputStream != null) {byteArrayOutputStream.close();}} catch (Exception e) {e.printStackTrace();}}return null;
}private List<Plan> getPlans() {List<Plan> plans = new ArrayList<Plan>();for(int i=1;i<=12;i++) {plans.add(new Plan(i,"2023-"+String.format("%02d", i)+"-01","999","-", "999","0","2023-"+String.format("%02d", i)+"-01", "已结清"));}return plans;
}private PdfPCell generateCell(String value, int border, Font fontZH) {PdfPCell cell = new PdfPCell(new Phrase(value, fontZH));cell.setBorder(border);cell.setHorizontalAlignment(Element.ALIGN_CENTER);return cell;}public static void main(String [] args) throws FileNotFoundException, IOException {//将字节流转为pdf文件放于D盘OutputStream fileOut = new FileOutputStream("D:/a.pdf");fileOut.write(new TestPdf().createPdf());}

4.执行结果
在这里插入图片描述
5.所用到jar包下载地址
itextpdf-5.5.10.jar

欢迎大家积极留言交流学习心得,点赞的人最美丽!

这篇关于Java使用IText根据pdf模板创建pdf文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/937285

相关文章

SpringBoot 获取请求参数的常用注解及用法

《SpringBoot获取请求参数的常用注解及用法》SpringBoot通过@RequestParam、@PathVariable等注解支持从HTTP请求中获取参数,涵盖查询、路径、请求体、头、C... 目录SpringBoot 提供了多种注解来方便地从 HTTP 请求中获取参数以下是主要的注解及其用法:1

HTTP 与 SpringBoot 参数提交与接收协议方式

《HTTP与SpringBoot参数提交与接收协议方式》HTTP参数提交方式包括URL查询、表单、JSON/XML、路径变量、头部、Cookie、GraphQL、WebSocket和SSE,依据... 目录HTTP 协议支持多种参数提交方式,主要取决于请求方法(Method)和内容类型(Content-Ty

深度解析Java @Serial 注解及常见错误案例

《深度解析Java@Serial注解及常见错误案例》Java14引入@Serial注解,用于编译时校验序列化成员,替代传统方式解决运行时错误,适用于Serializable类的方法/字段,需注意签... 目录Java @Serial 注解深度解析1. 注解本质2. 核心作用(1) 主要用途(2) 适用位置3

sky-take-out项目中Redis的使用示例详解

《sky-take-out项目中Redis的使用示例详解》SpringCache是Spring的缓存抽象层,通过注解简化缓存管理,支持Redis等提供者,适用于方法结果缓存、更新和删除操作,但无法实现... 目录Spring Cache主要特性核心注解1.@Cacheable2.@CachePut3.@Ca

C#下Newtonsoft.Json的具体使用

《C#下Newtonsoft.Json的具体使用》Newtonsoft.Json是一个非常流行的C#JSON序列化和反序列化库,它可以方便地将C#对象转换为JSON格式,或者将JSON数据解析为C#对... 目录安装 Newtonsoft.json基本用法1. 序列化 C# 对象为 JSON2. 反序列化

深入浅出Spring中的@Autowired自动注入的工作原理及实践应用

《深入浅出Spring中的@Autowired自动注入的工作原理及实践应用》在Spring框架的学习旅程中,@Autowired无疑是一个高频出现却又让初学者头疼的注解,它看似简单,却蕴含着Sprin... 目录深入浅出Spring中的@Autowired:自动注入的奥秘什么是依赖注入?@Autowired

Spring 依赖注入与循环依赖总结

《Spring依赖注入与循环依赖总结》这篇文章给大家介绍Spring依赖注入与循环依赖总结篇,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. Spring 三级缓存解决循环依赖1. 创建UserService原始对象2. 将原始对象包装成工

Java中如何正确的停掉线程

《Java中如何正确的停掉线程》Java通过interrupt()通知线程停止而非强制,确保线程自主处理中断,避免数据损坏,线程池的shutdown()等待任务完成,shutdownNow()强制中断... 目录为什么不强制停止为什么 Java 不提供强制停止线程的能力呢?如何用interrupt停止线程s

SpringBoot请求参数传递与接收示例详解

《SpringBoot请求参数传递与接收示例详解》本文给大家介绍SpringBoot请求参数传递与接收示例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋... 目录I. 基础参数传递i.查询参数(Query Parameters)ii.路径参数(Path Va

SpringBoot路径映射配置的实现步骤

《SpringBoot路径映射配置的实现步骤》本文介绍了如何在SpringBoot项目中配置路径映射,使得除static目录外的资源可被访问,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一... 目录SpringBoot路径映射补:springboot 配置虚拟路径映射 @RequestMapp