基于IText7 PDF模板填充?

2023-12-10 01:01
文章标签 模板 pdf itext7 填充

本文主要是介绍基于IText7 PDF模板填充?,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

引入依赖

<dependency><groupId>com.itextpdf</groupId><artifactId>itext7-core</artifactId><version>8.0.1</version><type>pom</type>
</dependency>
<dependency><groupId>com.itextpdf</groupId><artifactId>bouncy-castle-adapter</artifactId><version>8.0.1</version>
</dependency>

模板填充工具

import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormCreator;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.pdf.annot.PdfAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfWidgetAnnotation;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.muchenx.util.ImageCompressUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;/*** PDF 模板填充工具类(itext7)* <p>* 支持文本 及 图片 填充*/
@Slf4j
public final class PDFTemplateFillHandler {/*** 待填充的PDF模板文档*/private final transient PdfDocument templateDocument;/*** 填充后PDF文档数据*/private final transient ByteArrayOutputStream destByteOutStream;/*** 字体*/private transient PdfFont font;private PDFTemplateFillHandler(PdfDocument templateDocument, ByteArrayOutputStream destByteOutStream) {this.templateDocument = templateDocument;this.destByteOutStream = destByteOutStream;try {this.font = loadFont();} catch (IOException e) {log.warn("加载指定字体异常:{}", e.getMessage());}}public static PDFTemplateFillHandler loadTemplate(InputStream templateFileStream) {try {ByteArrayOutputStream dest = new ByteArrayOutputStream();PdfDocument pdfDocument = new PdfDocument(new PdfReader(templateFileStream), new PdfWriter(dest));return new PDFTemplateFillHandler(pdfDocument, dest);} catch (IOException e) {throw new RuntimeException(e);}}/*** 填充及返回填充后的数据** @param fillData - 待填充数据* @return - 填充后bytes数据*/public byte[] fill(Map<String, Object> fillData) {try {PdfAcroForm form = PdfAcroForm.getAcroForm(templateDocument, true);fillData.forEach((keyword, value) -> {Optional.ofNullable(form.getField(keyword)).ifPresent(templateFormField -> {if (value instanceof byte[]) {PdfArray pos = templateFormField.getWidgets().get(0).getRectangle();float x = pos.getAsNumber(0).floatValue();float y = pos.getAsNumber(1).floatValue();float width = pos.getAsNumber(2).floatValue() - x;float height = pos.getAsNumber(3).floatValue() - y;Rectangle rectangle = new Rectangle(x, y, width, height);PdfWidgetAnnotation widget = new PdfWidgetAnnotation(rectangle);PdfFormField formField = PdfFormCreator.createFormField(widget, templateDocument);PdfPage annotationPage = findAnnotationPage(keyword);if (annotationPage != null) {doFillFieldImage(annotationPage, formField, (byte[]) value);}} else {templateFormField.setValue(String.valueOf(value));if (font != null) {templateFormField.setFont(templateFormField.getFont());}}form.partialFormFlattening(keyword);});});form.flattenFields();} finally {if (templateDocument != null) {templateDocument.close();}}return destByteOutStream.toByteArray();}/*** 图片填充** @param newPage   - 当前页* @param formField - 表单文本域* @param imgBytes  - 图片文件字节数组*/private void doFillFieldImage(PdfPage newPage, PdfFormField formField, byte[] imgBytes) {Rectangle rtl = formField.getWidgets().get(0).getRectangle().toRectangle(); // 获取表单域的xy坐标PdfCanvas canvas = new PdfCanvas(newPage);ImageData img = ImageDataFactory.create(imgBytes);if (Float.compare(img.getWidth(), rtl.getWidth()) <= 0 && Float.compare(img.getHeight(), rtl.getHeight()) <= 0) {// 不处理canvas.addImageAt(img, rtl.getX(), rtl.getY(), true);} else {// 压缩图片。计算得到图片放缩的最大比例float scale = Math.max(img.getWidth() / rtl.getWidth(), img.getHeight() / rtl.getHeight());int imgWidth = Math.round(img.getWidth() / scale);int imgHeight = Math.round(img.getHeight() / scale);// 压缩图片byte[] compressImgBytes;try {compressImgBytes = ImageCompressUtils.resizeByThumbnails(imgBytes, imgWidth, imgHeight);} catch (IOException e) {throw new RuntimeException(e);}img = ImageDataFactory.create(compressImgBytes);canvas.addImageAt(img, rtl.getX(), rtl.getY(), true);}}/*** 根据表单域关键字查找当前关键字所在页对象(PdfPage)** @param keyword - 关键字* @return - page object*/private PdfPage findAnnotationPage(String keyword) {int pages = templateDocument.getNumberOfPages();for (int index = 1; index <= pages; index++) {PdfPage page = templateDocument.getPage(index);for (PdfAnnotation annotation : page.getAnnotations()) {PdfString title = annotation.getPdfObject().getAsString(PdfName.T);if (title != null && keyword.equals(String.valueOf(title))) {return page;}}}return null;}/*** 获取模板文件表单域关键字位置信息*/private Map<Integer, Map<String, float[]>> getFormKeywordsPos() {int pages = templateDocument.getNumberOfPages();Map<Integer, Map<String, float[]>> maps = new HashMap<>(pages);for (int index = 1; index <= pages; index++) {maps.putIfAbsent(index, new HashMap<>());PdfPage page = templateDocument.getPage(index);// 获取当前页的表单域int finalIndex = index;page.getAnnotations().forEach(anno -> {PdfString title = anno.getTitle();PdfArray rectangle = anno.getRectangle();float x = rectangle.getAsNumber(0).floatValue();float y = rectangle.getAsNumber(1).floatValue();float width = rectangle.getAsNumber(2).floatValue() - x;float height = rectangle.getAsNumber(3).floatValue() - y;maps.get(finalIndex).put(title.getValue(), new float[]{x, y, width, height});});}return maps;}/*** 加载字体*/private PdfFont loadFont() throws IOException {Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath*:/font/*.ttc");if (resources.length == 0) {return null;}PdfFontFactory.register(resources[0].getURL().getPath(), "SimSun");return PdfFontFactory.createRegisteredFont("SimSun", PdfEncodings.IDENTITY_H,PdfFontFactory.EmbeddingStrategy.PREFER_NOT_EMBEDDED);}
}

填充实例

LocalDate now = LocalDate.now();
// 图片文件
ByteArrayOutputStream catOutStream = new ByteArrayOutputStream();
File img = ResourceUtils.getFile("classpath:cat.png");
InputStream catInStream = Files.newInputStream(img.toPath());
IOUtils.copy(catInStream, catOutStream);
Map<String, Object> data = new HashMap<>();
data.put("username", "喵星人");
data.put("gender", "女");
data.put("nation", "狗");
data.put("school", "狗族大学");
data.put("describe", "千百年来,地球上一直住着一种外星生物,名叫喵星人。它们从遥远的喵星来到地球,化身为猫科动物,分散在世界每个角落。萌萌的外表,加上机智聪明的头脑,轻易就得到人类的宠爱。");
data.put("describe1", "千百年来,地球上一直住着一种外星生物,名叫喵星人。它们从遥远的喵星来到地球,化身为猫科动物,分散在世界每个角落。萌萌的外表,加上机智聪明的头脑,轻易就得到人类的宠爱。");
data.put("content", "千百年来,地球上一直住着一种外星生物,名叫喵星人。它们从遥远的喵星来到地球,化身为猫科动物,分散在世界每个角落。萌萌的外表,加上机智聪明的头脑,轻易就得到人类的宠爱。");
data.put("sign", catOutStream.toByteArray());
data.put("avatar", catOutStream.toByteArray());
data.put("year", String.valueOf(now.getYear()));
data.put("month", String.valueOf(now.getMonthValue()));
data.put("day", String.valueOf(now.getDayOfMonth()));String homePath = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath();
File template = ResourceUtils.getFile("classpath:fill_template.pdf");
byte[] filledDataBytes = PDFTemplateFillHandler.loadTemplate(Files.newInputStream(template.toPath())).fill(data);
IOUtils.write(filledDataBytes, Files.newOutputStream(Paths.get(homePath + "/" + System.nanoTime() + ".pdf")));

基于IText7 的 PDF表单域模板填充

这篇关于基于IText7 PDF模板填充?的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Java利用Spire.Doc for Java实现在模板的基础上创建Word文档

《Java利用Spire.DocforJava实现在模板的基础上创建Word文档》在日常开发中,我们经常需要根据特定数据动态生成Word文档,本文将深入探讨如何利用强大的Java库Spire.Do... 目录1. Spire.Doc for Java 库介绍与安装特点与优势Maven 依赖配置2. 通过替换

Python结合Free Spire.PDF for Python实现PDF页面旋转

《Python结合FreeSpire.PDFforPython实现PDF页面旋转》在日常办公或文档处理中,我们经常会遇到PDF页面方向错误的问题,本文将分享如何用Python结合FreeSpir... 目录基础实现:单页PDF精准旋转完整代码代码解析进阶操作:覆盖多场景旋转需求1. 旋转指定角度(90/27

使用C#实现将RTF转换为PDF

《使用C#实现将RTF转换为PDF》RTF(RichTextFormat)是一种通用的文档格式,允许用户在不同的文字处理软件中保存和交换格式化文本,下面我们就来看看如何使用C#实现将RTF转换为PDF... 目录Spire.Doc for .NET 简介安装 Spire.Doc代码示例处理异常总结RTF(R

SpringBoot集成iText快速生成PDF教程

《SpringBoot集成iText快速生成PDF教程》本文介绍了如何在SpringBoot项目中集成iText9.4.0生成PDF文档,包括新特性的介绍、环境准备、Service层实现、Contro... 目录SpringBoot集成iText 9.4.0生成PDF一、iText 9新特性与架构变革二、环

使用Python在PDF中绘制多种图形的操作示例

《使用Python在PDF中绘制多种图形的操作示例》在进行PDF自动化处理时,人们往往首先想到的是文本生成、图片嵌入或表格绘制等常规需求,然而在许多实际业务场景中,能够在PDF中灵活绘制图形同样至关重... 目录1. 环境准备2. 创建 PDF 文档与页面3. 在 PDF 中绘制不同类型的图形python

使用Python实现在PDF中添加、导入、复制、移动与删除页面

《使用Python实现在PDF中添加、导入、复制、移动与删除页面》在日常办公和自动化任务中,我们经常需要对PDF文件进行页面级的编辑,使用Python,你可以轻松实现这些操作,而无需依赖AdobeAc... 目录1. 向 PDF 添加空白页2. 从另一个 PDF 导入页面3. 删除 PDF 中的页面4. 在

OFD格式文件及如何适应Python将PDF转换为OFD格式文件

《OFD格式文件及如何适应Python将PDF转换为OFD格式文件》OFD是中国自主研发的一种固定版式文档格式,主要用于电子公文、档案管理等领域,:本文主要介绍OFD格式文件及如何适应Python... 目录前言什么是OFD格式文档?使用python easyofd库将PDF转换为OFD第一步:安装 eas

基于Java实现PPT到PDF的高效转换详解

《基于Java实现PPT到PDF的高效转换详解》在日常开发中,经常会遇到将PPT文档批量或单文件转换为PDF的需求,本文将详细介绍其使用流程、核心代码与常见问题解决方案,希望对大家有所帮助... 目录一、环境配置Maven 配置Gradle 配置二、核心实现:3步完成PPT转PDF1. 单文件转换(基础版)

利用Python将PDF文件转换为PNG图片的代码示例

《利用Python将PDF文件转换为PNG图片的代码示例》在日常工作和开发中,我们经常需要处理各种文档格式,PDF作为一种通用且跨平台的文档格式,被广泛应用于合同、报告、电子书等场景,然而,有时我们需... 目录引言为什么选择 python 进行 PDF 转 PNG?Spire.PDF for Python

Python实现Word文档自动化的操作大全(批量生成、模板填充与内容修改)

《Python实现Word文档自动化的操作大全(批量生成、模板填充与内容修改)》在职场中,Word文档是公认的好伙伴,但你有没有被它折磨过?批量生成合同、制作报告以及发放证书/通知等等,这些重复、低效... 目录重复性文档制作,手动填充模板,效率低下还易错1.python-docx入门:Word文档的“瑞士