Michael Zhang
Michael Zhang

Reputation: 47

Get pdf page number by acrofield using itext7 with C#

With iText7, I like to get pdf page number by form field but I can't find method or property of getting page number.

IDictionary<String, PdfFormField> fields = form.GetFormFields();
PdfFormField field = fields["fieldName"];
field.page <-- there is no property

I found this one:

PdfPage page = field.GetWidgets().First().GetPage();

But I have no idea of how to get page number from PdfPage.

It looks like iText5 has this one (in Java):

int page = form.getFieldPositions(name).get(0).page;

And how can I do it with iText 7 in C#

Upvotes: 3

Views: 5811

Answers (1)

mkl
mkl

Reputation: 95918

Essentially your problem is

I have no idea of how to get page number from PdfPage.

The class PdfDocument has a method GetPageNumber for this:

/// <summary>Gets page number by page.</summary>
/// <param name="page">the page.</param>
/// <returns>page number.</returns>
public virtual int GetPageNumber(PdfPage page)

Thus, you can retrieve the page number of a page widget like this:

using (PdfReader reader = new PdfReader(formDocumentFile))
using (PdfDocument pdf = new PdfDocument(reader))
{
    PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);
    PdfFormField field = form.GetField(fieldName);
    PdfPage page = field.GetWidgets().First().GetPage();
    int number = pdf.GetPageNumber(page);
    Console.WriteLine("Determined page number: {0}", number);
}

Beware:

  • field.GetWidgets().First() implicitly assumes that the field has at least one widget. This is not guaranteed, there may be invisible fields without any widgets. In general you should check this.

  • ....GetPage() may return null if the widget annotation is not associated with any page (i.e. neither its own P entry is set nor is it referenced from any current page). In general you should check this.

Upvotes: 6

Related Questions