我使用此处提供的代码How to Add Page number in Footer in PDF by Itextsharp使用iTextSharp创建页码编号的页眉和页脚。 Visual Studio特别指出了PageEventHelper'不包含' RunDateFont'的定义没有扩展方法' RunDateFont'接受类型' PageEventHelper'的第一个参数。可以找到(你错过了使用指令或程序集引用吗?) 我错过了什么?
以下是我的代码的简化版本:
namespace MyWebApp {
public partial class _Default : Page
{
protected void Button_Click(object sender, EventArgs e)
{
using (MemoryStream myMemoryStream = new MemoryStream())
{
Document document = new iTextSharp.text.Document();
PdfWriter myPDFWriter = PdfWriter.GetInstance(document, myMemoryStream);
PageEventHelper pageEventHelper = new PageEventHelper();
myPDFWriter.PageEvent = pageEventHelper;
var response = HttpContext.Current.Response;
response.Clear();
response.ContentType = "application/pdf";
// myPDFWriter.PageEvent = new Footer();
document.Open();
document.Add(clienttable);
document.NewPage();//page break OR New Page
document.Add(new Paragraph("This is a second page."));
document.Close();
byte[] content = myMemoryStream.ToArray();
myPDFWriter.Flush();
response.OutputStream.Write(myMemoryStream.GetBuffer(), 0, myMemoryStream.GetBuffer().Length);
response.OutputStream.Flush();
response.OutputStream.Close();
response.End();
}
}
// some other functions
}
public class PageEventHelper : PdfPageEventHelper
{
PdfContentByte cb;
PdfTemplate template;
public override void OnOpenDocument(PdfWriter myPDFWriter, Document document)
{
cb = myPDFWriter.DirectContent;
template = cb.CreateTemplate(50, 50);
}
public override void OnEndPage(PdfWriter myPDFWriter, Document document)
{
base.OnEndPage(myPDFWriter, document);
int pageN = myPDFWriter.PageNumber;
String text = "Page " + pageN.ToString() + " of ";
float len = this.RunDateFont.BaseFont.GetWidthPoint(text, this.RunDateFont.Size);
iTextSharp.text.Rectangle pageSize = document.PageSize;
cb.SetRGBColorFill(100, 100, 100);
cb.BeginText();
cb.SetFontAndSize(this.RunDateFont.BaseFont, this.RunDateFont.Size);
cb.SetTextMatrix(document.LeftMargin, pageSize.GetBottom(document.BottomMargin));
cb.ShowText(text);
cb.EndText();
cb.AddTemplate(template, document.LeftMargin + len, pageSize.GetBottom(document.BottomMargin));
}
public override void OnCloseDocument(PdfWriter myPDFWriter, Document document)
{
base.OnCloseDocument(myPDFWriter, document);
template.BeginText();
template.SetFontAndSize(this.RunDateFont.BaseFont, this.RunDateFont.Size);
template.SetTextMatrix(0, 0);
template.ShowText("" + (myPDFWriter.PageNumber - 1));
template.EndText();
}
}