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

PDF嵌入隐藏的文字

所需依赖

<dependency><groupId>com.itextpdf</groupId><artifactId>itext-core</artifactId><version>9.0.0</version><type>pom</type>
</dependency>

源码

/*** PDF工具*/
public class PdfUtils {/*** 在 PDF 中嵌入字段* 在现有 PDF 文档中添加表单字段及其值** @param pdfBytes   原 PDF 文档的字节数组* @param filedName  要嵌入的字段名称* @param fieldValue 要嵌入的字段值* @return 嵌入字段后的 PDF 字节数组* @throws ServiceException 如果嵌入过程中发生错误*/public static byte[] embedField(byte[] pdfBytes, String filedName, String fieldValue) {try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {// 创建 PDF 文档对象,读取源 PDF 并指定输出流PdfDocument pdfDoc = new PdfDocument(new PdfReader(new ByteArrayInputStream(pdfBytes)),new PdfWriter(baos));// 获取 PDF 第一页对象PdfObject pdfObject = pdfDoc.getPdfObject(1);// 获取或创建 PDF 表单PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);// 创建表单字段PdfFormField pdfFormField = new PdfFormField((PdfDictionary) pdfObject);// 设置字段名称pdfFormField.setFieldName(filedName);// 设置字段值pdfFormField.setValue(fieldValue);// 设置字段为只读pdfFormField.setFieldFlags(PdfFormField.FF_READ_ONLY);// 将字段添加到表单中form.addField(pdfFormField);// 关闭文档并写入输出流pdfDoc.close();// 返回处理后的 PDF 字节数组return baos.toByteArray();} catch (Exception e) {// 发生异常时抛出服务异常throw new ServiceException(0, "嵌入PDF字段失败");}}/*** 从 PDF 中获取指定字段的值** @param pdfBytes  PDF 字节数组* @param filedName 要获取的字段名称* @return 字段值,如果字段不存在则返回 null* @throws ServiceException 如果获取过程中发生错误*/public static String getField(byte[] pdfBytes, String filedName) {try (PdfDocument pdfDoc = new PdfDocument(new PdfReader(new ByteArrayInputStream(pdfBytes)))) {// 获取 PDF 表单,不自动创建PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, false);if (form == null) {// 如果表单不存在,返回 nullreturn null;}// 获取指定名称的字段PdfFormField field = form.getField(filedName);if (field == null) {// 如果字段不存在,返回 nullreturn null;}// 返回字段值的字符串表示return field.getValueAsString();} catch (Exception e) {// 发生异常时抛出服务异常throw new ServiceException(0, "获取PDF字段处理失败");}}
}
http://www.dtcms.com/a/158947.html

相关文章:

  • Rule.resourceQuery(通过路径参数指定loader匹配规则)
  • PH热榜 | 2025-04-26
  • 百度Create大会深度解读:AI Agent与多模态模型如何重塑未来?
  • 如何删除Google Chrome中的所有历史记录【一键清除】
  • 【音视频】SDL窗口显示
  • Vue.js 核心特性解析:响应式原理与组合式API实践
  • IDEA 连接 Oracle 数据库
  • 《代码整洁之道》第7章 错误处理 - 笔记
  • SQLMesh 测试自动化:提升数据工程效率
  • 决策树随机深林
  • 国标GB28181视频平台EasyCVR助力打造太阳能供电远程视频监控系统
  • 高并发架构设计之缓存
  • 数模学习:二,MATLAB的基本语法使用
  • 安卓APP开发项目源码
  • Tauri打包时出现WixTools以及NSIS报错
  • 基于ArcGIS的洪水灾害普查、风险评估及淹没制图技术研究​
  • SpringBoot配置RestTemplate并理解单例模式详解
  • 硬盘损坏数据恢复后对python程序的影响
  • 【创新实训个人博客】multi-agent调研(2)
  • Ubuntu下MySQL的安装
  • LLM应用于自动驾驶方向相关论文整理(大模型在自动驾驶方向的相关研究)
  • IP地址如何切换到国内别的省份?一步步指导
  • 于键值(KV)的表
  • MyBatis DTD [Element type “if“ must be declared]
  • vue+neo4j+flask 音乐知识图谱推荐系统
  • EXCEL常用函数公式和VBA汇总第二篇
  • 机器学习-入门-线性模型(1)
  • 【MCP】从一个天气查询服务带你了解MCP
  • 学习笔记:Qlib 量化投资平台框架 — FIRST STEPS
  • Linux系统之设置开机启动运行桌面环境