我正在创建包含3个页面的PDF,所有3个页面应该有3个不同的标题。我在文档中遇到了一个示例 VaraibleHeader. 但是下面的工作原理不是我的代码。
public class ReportPdfHeaderFooter : PdfPageEventHelper
{
public void SetHeader(string header)
{
this._header = header;
}
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
PdfPTable table = new PdfPTable(1);
table.AddCell(title);
footer.WriteSelectedRows(0, -1, Pdf.MarginLeft, document.Bottom, writer.DirectContent);
}
}
public CreatePdf()
{
private Document _doc;
private MemoryStream _memStream;
private PdfWriter _pdfWriter;
this._doc = new Document();
this._memStream = new MemoryStream();
this._pdfWriter = PdfWriter.GetInstance(this._doc, _memStream);
var reportPdfHeaderFooter = new ReportPdfHeaderFooter();
_pdfWriter.PageEvent = headerFooter;
reportPdfHeaderFooter.SetHeader("Header 1");
_doc.Open();
reportPdfHeaderFooter.SetHeader("Header 2");
_doc.NewPage();
_doc.Close();
}
我完成了文档中提到的任何内容,但我仍然在两个页面中都将Header 2作为标题。
答案 0 :(得分:2)
虽然您看起来已经走上了正确的轨道,但上面的ReportPdfHeaderFooter
课程必须是一个糟糕的复制/粘贴,不会按原样编译。
这是一个简单的工作示例,可以帮助您入门。
首先是PdfPageEventHelper
实施:
public class PageEventHeader : PdfPageEventHelper
{
public string HeaderText { get; set; }
public override void OnEndPage(PdfWriter writer, Document document)
{
float cellHeight = document.TopMargin;
Rectangle page = document.PageSize;
PdfPTable table = new PdfPTable(1) { TotalWidth = page.Width };
table.AddCell(new PdfPCell(new Phrase(HeaderText))
{
Border = PdfPCell.NO_BORDER,
FixedHeight = cellHeight,
HorizontalAlignment = Element.ALIGN_CENTER
});
table.WriteSelectedRows(
0, -1, 0,
page.Height - cellHeight + table.TotalHeight,
writer.DirectContent
);
}
}
其次,测试PDF文件创建:
using (var stream = new MemoryStream())
{
var header = new PageEventHeader();
using (Document document = new Document())
{
var writer = PdfWriter.GetInstance(document, stream);
document.Open();
writer.PageEvent = header;
header.HeaderText = "Header 0";
document.Add(new Phrase("Header 0"));
document.NewPage();
header.HeaderText = "Header 1";
document.Add(new Phrase("Header 1"));
}
File.WriteAllBytes(OUTPUT_FILE, stream.ToArray());
}