所需依赖
xml
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-core</artifactId>
<version>9.0.0</version>
<type>pom</type>
</dependency>
源码
java
/**
* 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) {
// 如果表单不存在,返回 null
return null;
}
// 获取指定名称的字段
PdfFormField field = form.getField(filedName);
if (field == null) {
// 如果字段不存在,返回 null
return null;
}
// 返回字段值的字符串表示
return field.getValueAsString();
} catch (Exception e) {
// 发生异常时抛出服务异常
throw new ServiceException(0, "获取PDF字段处理失败");
}
}
}