【发布时间】:2021-07-22 23:48:18
【问题描述】:
这篇文章 (How to extract images from a PDF with iText in the correct order?) 介绍了如何从常规 PDF 文件中提取图像。我需要提取用户在 PDF 表单域中输入的图像。
我使用 iText 7。我可以使用如下代码访问 iText 中的表单字段:
PdfReader reader = new PdfReader(new FileInputStream(new ClassPathResource("myFile.pdf").getFile()));
PdfDocument document = new PdfDocument(reader);
PdfAcroForm acroForm = PdfAcroForm.getAcroForm(document, false);
Map<String, PdfFormField> fields = acroForm.getFormFields();
PdfButtonFormField imageField = null;
PdfDictionary dictionary = null;
for (String fldName : fields.keySet()) {
PdfFormField field = fields.get(fldName);
if ("Image1_af_image".equals(fldName)) {
imageField = (PdfButtonFormField)fields.get("Image1_af_image");
dictionary = imageField.getPdfObject();
}
}
其中Image1_af_imgage 是表单中图像字段的默认名称。是否可以从PdfButtonFormField 或其关联的字典对象中提取图像流?
感谢您非常有帮助的回复。我已将您的代码合并如下:
public void iTextTest3() throws IOException {
PdfReader reader = new PdfReader(new FileInputStream(new ClassPathResource("templates/TestForm.pdf").getFile()));
PdfDocument document = new PdfDocument(reader);
String fieldname = "Image1_af_image";
PdfAcroForm acroForm = PdfAcroForm.getAcroForm(document, false);
PdfFormField imagefield = acroForm.getField(fieldname);
// get the appearance dictionary
PdfDictionary apDic = imagefield.getWidgets().get(0).getNormalAppearanceObject();
// get the xobject resources
PdfDictionary xObjDic = apDic.getAsDictionary(PdfName.Resources).getAsDictionary(PdfName.XObject);
for (PdfName key : xObjDic.keySet()) {
System.out.println(key);
PdfStream s = xObjDic.getAsStream(key);
// only process images
if (PdfName.Image.equals(s.getAsName(PdfName.Subtype))) { //*** code fails here ***
PdfImageXObject pixo = new PdfImageXObject(s);
byte[] imgbytes = pixo.getImageBytes();
String ext = pixo.identifyImageFileExtension();
// write the image to file
String fileName = null;
FileOutputStream fos = new FileOutputStream(fileName = key.toString().substring(1) + "." + ext);
System.out.println(("image fileName: " + fileName));
fos.write(imgbytes);
fos.close();
}
}
document.close();
}
代码失败,因为s.getAsName(PdfName.Subtype) 返回值"Form"。我猜我需要做的是按照您在帖子中的建议递归到 XObject 树中,但不确定该怎么做。我试过xObjDic.getAsDictionary(),但不确定PdfName 作为参数传入。
【问题讨论】:
-
您在没有说明版本的情况下提到了 iText。根据您的代码,我假设它是 iText 7 版本?
-
对不起,是 iText7。
-
@StephenSchultz 我根据您的问题编辑修改了我的答案。
标签: java forms pdf itext itext7