找到iTextSharp对象的页码

时间:2013-05-28 21:24:54

标签: c# asp.net itextsharp

我正在尝试使用iTextSharp将图像写入pdf文件上的特定页面。不幸的是,我有大约10或15个不同的pdf文件,我需要将图像放在不同的页面上。

实施例: PDF文件1:图片在第3页上,

PDF文件2:图片在第6页,

PDF文件3:图片在第5页等...

我当前的代码拉取页数并在最后一页上写入图像。如何拉出文本框对象“图像”所在的页码?

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

1 个答案:

答案 0 :(得分:1)

正如我今天早上的评论所示:

您已使用position类的FieldPosition成员:

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

FieldPosition还有更多优惠;它被定义为:

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

因此,您要求的页码是

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