我使用ITextSharp将页码添加到pdf文档的底部 问题是,它由4或5个不同的PDF组成,这些PDF通过整个过程组合在一起,并且有一些动态添加的页面,因此PDF的大小可能会有所不同。我无法调用document.PageCount,因为它“缺少get访问器”。
我做了一个计数器来跟踪我所在的页面,并且可以在最后一页上说“第9页,共9页”,但其余的只是说“第7页”。 我想我可以通过PdfReader运行整个文件来调用reader.NumberOfPages并重新运行每个页面并在底部添加最终的数字,但我不知道如何从iTextSharp.text.Document类型中创建一个,也不知道如何事后再去做。
这是一个由其他人创建的项目,之前我几乎没有触及过iTextSharp,我无法重新上课,因为它太大了。
有谁知道我能做什么?或者如何将这1个数字添加到iTextSharp.text.Document的每个页面?
答案 0 :(得分:0)
发现它们:D
所以每当你创作作家时:
using (MemoryStream MS = new MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(doc, MS);
writer.ViewerPreferences = PdfWriter.PageModeUseOutlines;
PdfFooter eventHandler = new PdfFooter();
writer.PageEvent = eventHandler;
ect.
}
对于PdfFooter:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using iTextSharp.text.pdf;
using iTextSharp.text;
public class PdfFooter : PdfPageEventHelper
{
// This is the contentbyte object of the writer
PdfContentByte cb;
// we will put the final number of pages in a template
PdfTemplate template;
// this is the BaseFont we are going to use for the header / footer
BaseFont bf = null;
// This keeps track of the creation time
DateTime PrintTime = DateTime.Now;
#region Properties
private string _Title;
public string Title
{
get { return _Title; }
set { _Title = value; }
}
private string _HeaderLeft;
public string HeaderLeft
{
get { return _HeaderLeft; }
set { _HeaderLeft = value; }
}
private string _HeaderRight;
public string HeaderRight
{
get { return _HeaderRight; }
set { _HeaderRight = value; }
}
private Font _HeaderFont;
public Font HeaderFont
{
get { return _HeaderFont; }
set { _HeaderFont = value; }
}
private Font _FooterFont;
public Font FooterFont
{
get { return _FooterFont; }
set { _FooterFont = value; }
}
#endregion
// we override the onOpenDocument method
public override void OnOpenDocument(PdfWriter writer, Document document)
{
try
{
PrintTime = DateTime.Now;
bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb = writer.DirectContent;
template = cb.CreateTemplate(50, 50);
}
catch (DocumentException de)
{
}
catch (System.IO.IOException ioe)
{
}
}
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
int pageN = writer.PageNumber;
String text = "Page " + pageN + " of ";
float len = bf.GetWidthPoint(text, 8);
Rectangle pageSize = document.PageSize;
cb.SetRGBColorFill(100, 100, 100);
cb.BeginText();
cb.SetFontAndSize(bf, 8);
cb.SetTextMatrix(pageSize.GetRight(70), pageSize.GetBottom(15));
cb.ShowText(text);
cb.EndText();
cb.AddTemplate(template, pageSize.GetRight(70) + len, pageSize.GetBottom(15));
}
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
template.BeginText();
template.SetFontAndSize(bf, 8);
template.SetTextMatrix(0, 0);
template.ShowText("" + (writer.PageNumber - 1));
template.EndText();
}
}
希望这可以帮助将来的某个人:)