我想要获得使用iTextSharp 5.0.2.0生成的pdf的每一页的页码。
现在代码的一部分是
e.FooterText = writer.CurrentPageNumber.ToString();但当我这样做时,它会显示页码,但问题是它在所有页面中都显示相同的页码。就像所有页面中的"1“。如何在iTextSharp 5.0.2.0版本中获取pdf文件的页码?
发布于 2019-09-20 15:32:44
你必须使用iTextSharp打开PDF,然后按照下面的代码进行操作。
public void AddPageNumberToPDF(string physicalDocPath, bool showPageOfPage)
{
byte[] Fbytes = File.ReadAllBytes(physicalDocPath);
PdfReader reader = new PdfReader(Fbytes);
int n = reader.NumberOfPages;
using (var fileStream = new FileStream(physicalDocPath, FileMode.Create, FileAccess.Write))
{
var document = new Document(reader.GetPageSizeWithRotation(1));
var writer = PdfWriter.GetInstance(document, fileStream);
document.Open();
PdfContentByte cb = writer.DirectContent;
int p = 0;
for (int page = 1; page <= reader.NumberOfPages; page++)
{
document.NewPage();
p++;
PdfImportedPage importedPage = writer.GetImportedPage(reader, page);
cb.AddTemplate(importedPage, 0, 0);
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.BeginText();
cb.SetFontAndSize(bf, 10);
if (showPageOfPage)
{
cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, p.ToString()+"/"+n.ToString(), 575, 17, 0);
}
else
{
cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, p.ToString(), 575, 17, 0);
}
cb.EndText();
}
document.Close();
writer.Close();
}
}发布于 2019-09-20 16:55:19
正如@bradbury9所述,OnEndPage事件就是您的目标。
下面的代码示例将在每次触发OnPageEnd事件时在所需的页面位置添加所需的页脚文本
public class MyPdfPageEventHandler: PdfPageEventHelper
{
const float horizontalPosition = 0.5f; // %50 of the page width, starting from the left
const float verticalPosition = 0.1f; // %10 of the page height starting from the bottom
public override void OnEndPage(PdfWriter writer, Document document)
{
var footerText = new Phrase(writer.CurrentPageNumber.ToString());
float posX = writer.PageSize.Width * horizontalPosition;
float posY = writer.PageSize.Height * verticalPosition;
float rotation = 0;
ColumnText.ShowTextAligned(writer.DirectContent, Element.PHRASE, footerText, posX, posY, rotation);
}
}下面是一些关于如何使其工作的示例代码
static void Main(string[] args)
{
FileStream fs = new FileStream("NewDocument.pdf", FileMode.Create, FileAccess.Write, FileShare.None);
Document doc = new Document();
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
writer.PageEvent = new MyPdfPageEventHandler(); //This will trigger the code above
doc.Open();
doc.Add(new Paragraph("First Page"));
doc.NewPage();
doc.Add(new Paragraph("Second Page"));
doc.NewPage();
doc.Add(new Paragraph("Thid Page"));
doc.Close();
}您可以使用MyPdfPageEventHandler类覆盖其他页面事件,如OnStartPage等。
https://stackoverflow.com/questions/58023553
复制相似问题