Timmy Rainyeid
Timmy Rainyeid

Reputation: 45

Locate page number of an iTextSharp Object

I'm trying to write an image to a specific page on a pdf file using iTextSharp. Unfortunately, I have about 10 or 15 different pdf files in which I need to place the image on a different page.

Example: PDFFile1: Image goes on page 3,

PDFFile2: Image goes on page 6,

PDFFile3: Image goes on page 5 etc...

My current code pulls the number of pages and writes the image on the very last page. How can I pull the page number where the textbox object "Image" is located?

    private void writePDF(string PhysicalName)
    { 
   try
            {
            string pdfTemplate = HttpContext.Current.Server.MapPath("Documents\\" + PhysicalName);
            string ConsentTemplateName = PhysicalName.Replace(".pdf", "");
            string newFile = HttpContext.Current.Server.MapPath("Documents\\").ToString() + ConsentTemplateName + Session["Number"].ToString() + ".pdf";
string NewConsentPhysicalPath;
            NewConsentPhysicalPath = newFile;
            PdfReader pdfReader = new PdfReader(pdfTemplate);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
            pdfStamper.SetEncryption(PdfWriter.STANDARD_ENCRYPTION_128, null, null, PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING);
            AcroFields pdfFormFields = pdfStamper.AcroFields;

iTextSharp.text.Rectangle rect = pdfStamper.AcroFields.GetFieldPositions("Image")[0].position;
            string imageFilePath = HttpContext.Current.Server.MapPath("Documents\\Images" + Convert.ToInt64(Session["Number"].ToString()) + ".png");
            iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(imageFilePath);
            png.ScaleAbsolute(rect.Width, rect.Height);
            png.SetAbsolutePosition(rect.Left, rect.Bottom);
            int numOfPages = pdfReader.NumberOfPages;
            pdfStamper.GetOverContent(numOfPages).AddImage(png); //Get page number of "Image"
            pdfStamper.Close();    
   }
            catch (Exception ex)
            {
                Response.Write(ex.Message.ToString());
            }
        }

Upvotes: 2

Views: 2907

Answers (1)

mkl
mkl

Reputation: 95918

As already indicated in my comment this morning:

You already make use of the position member of the FieldPosition class:

Rectangle rect = pdfStamper.AcroFields.GetFieldPositions("Image")[0].position;

FieldPosition has more to offer, though; it is defined as:

public class FieldPosition {
    public int page;
    public Rectangle position;
}

Thus, the page number you ask for is

int page = pdfStamper.AcroFields.GetFieldPositions("Image")[0].page;

Upvotes: 1

Related Questions