简体   繁体   English

如何在 PDFBox API 2 中获取字段页面?

[英]how to get field page in PDFBox API 2?

i'm trying to get the field page in my project, and i dont know how to get the page number for each field and field.我试图在我的项目中获取字段页面,但我不知道如何获取每个字段和字段的页码。 i have this code:我有这个代码:

    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();
}

How do I get the page numbers of the fields?如何获取字段的页码?

thanks ron谢谢罗恩

This will show you on what page(s) (0-based) the field appears:这将显示该字段出现在哪个页面(从 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM