c# - 找到 iTextSharp 对象的页码

标签 c# asp.net itext

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

例子: PDFFile1:图像在第 3 页,

PDFFile2:图片在第 6 页,

PDFFile3:图像出现在第 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());
            }
        }

最佳答案

正如我今天早上的评论中所指出的:

您已经使用了 FieldPosition 类的 position 成员:

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;

关于c# - 找到 iTextSharp 对象的页码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16801746/

相关文章:

javascript - 使用 javascript 更改窗口调整大小时的方向 Devexpress MenuBar 控件

java - Itext Arabic Font 以问号形式出现

java - 如何使用 iText PDF Java 库打开远程目录?

c# - 如何将 Xaml 代码转换为 C#(WPF 中的 Setter 属性)

c# - resx 回退系统中的额外级别

c# - 如何解决错误无法在 iis 7 中添加具有唯一键属性 'value' 的添加类型的重复集合条目

c# - 使用 ItextSharp C# 标记 PDF 的各个页面

c# - 检查列表中位置 [x] 处的元素是否存在

asp.net - iis 7.5 ASP.net 挂起请求

c# - WCF 服务引用是否跳过类型