如何在 PDFBox API 2 中获取字段页面?
how to get field page in PDFBox API 2?
我正在尝试在我的项目中获取字段页面,
而且我不知道如何获取每个字段和字段的页码。
我有这个代码:
String formTemplate = "Template.pdf";
String filledForm = "filledForm.pdf";
PDDocument pdfDocument = PDDocument.load(new File(formTemplate));
PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
if (acroForm != null)
{
PDField field = acroForm.getField( "name" );
field.getAcroForm().setNeedAppearances(true);
field.setValue("my name");
acroForm.getField( "date" );
field.setValue("my date");
}
pdfDocument.save(filledForm);
pdfDocument.close();
}
如何获取字段的页码?
谢谢
罗恩
这将向您显示该字段出现在哪个页面(从 0 开始):
PDField field = acroForm.getField( "date" );
for (PDAnnotationWidget widget : field.getWidgets())
{
PDPage page = widget.getPage();
if (page == null)
{
// incorrect PDF. Plan B: try all pages to check the annotations.
for (int p = 0; p < doc.getNumberOfPages(); ++p)
{
List<PDAnnotation> annotations = doc.getPage(p).getAnnotations();
for (PDAnnotation ann : annotations)
{
if (ann.getCOSObject() == widget.getCOSObject())
{
System.out.println("found at page: " + p);
break;
}
}
}
continue;
}
int pageNum = pdfDocument.getPages().indexOf(page);
System.out.println("found at page: " + pageNum);
}
我正在尝试在我的项目中获取字段页面, 而且我不知道如何获取每个字段和字段的页码。 我有这个代码:
String formTemplate = "Template.pdf";
String filledForm = "filledForm.pdf";
PDDocument pdfDocument = PDDocument.load(new File(formTemplate));
PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
if (acroForm != null)
{
PDField field = acroForm.getField( "name" );
field.getAcroForm().setNeedAppearances(true);
field.setValue("my name");
acroForm.getField( "date" );
field.setValue("my date");
}
pdfDocument.save(filledForm);
pdfDocument.close();
}
如何获取字段的页码?
谢谢 罗恩
这将向您显示该字段出现在哪个页面(从 0 开始):
PDField field = acroForm.getField( "date" );
for (PDAnnotationWidget widget : field.getWidgets())
{
PDPage page = widget.getPage();
if (page == null)
{
// incorrect PDF. Plan B: try all pages to check the annotations.
for (int p = 0; p < doc.getNumberOfPages(); ++p)
{
List<PDAnnotation> annotations = doc.getPage(p).getAnnotations();
for (PDAnnotation ann : annotations)
{
if (ann.getCOSObject() == widget.getCOSObject())
{
System.out.println("found at page: " + p);
break;
}
}
}
continue;
}
int pageNum = pdfDocument.getPages().indexOf(page);
System.out.println("found at page: " + pageNum);
}