所需依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-core</artifactId>
<version>9.0.0</version>
<type>pom</type>
</dependency>
源码
public class PdfUtils {
public static byte[] embedField(byte[] pdfBytes, String filedName, String fieldValue) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
PdfDocument pdfDoc = new PdfDocument(
new PdfReader(new ByteArrayInputStream(pdfBytes)),
new PdfWriter(baos)
);
PdfObject pdfObject = pdfDoc.getPdfObject(1);
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();
return baos.toByteArray();
} catch (Exception e) {
throw new ServiceException(0, "嵌入PDF字段失败");
}
}
public static String getField(byte[] pdfBytes, String filedName) {
try (PdfDocument pdfDoc = new PdfDocument(new PdfReader(new ByteArrayInputStream(pdfBytes)))) {
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, false);
if (form == null) {
return null;
}
PdfFormField field = form.getField(filedName);
if (field == null) {
return null;
}
return field.getValueAsString();
} catch (Exception e) {
throw new ServiceException(0, "获取PDF字段处理失败");
}
}
}