Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This will show you on what page(s) (0-based) the field appears:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...