我正在尝试使用 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/