获取堆栈溢出exception生成PDF

作为我之前问题的延续,我一直在试用PDF的页眉和页脚function。 经过一番讨论后,我在PdfPageEventHelper类上更改了很多代码。 以下是我所拥有的:

public class ReportHeaderFooter : PdfPageEventHelper { public string HeaderTitle { get; set; } public IReportsAccessor ReportsAccessor { get; set; } private Image footerImg; private Image headerImg; private BaseColor headerColor; private PdfPTable tblHeader; public ReportHeaderFooter(IReportsAccessor reportsAccessor) { this.ReportsAccessor = reportsAccessor; var rootPath = ConfigurationManager.AppSettings["SaveFileRootPath"]; headerColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#ffffff")); // Not really but I don't want to give away the color } public override void OnOpenDocument(PdfWriter writer, Document document) { base.OnOpenDocument(writer, document); // Set the initial header image... var headerImgInfo = ReportsAccessor.GetImage(4); headerImg = Image.GetInstance(headerImgInfo.ReportImage); // Set the initial footer image... var footerImgInfo = ReportsAccessor.GetImage(2); footerImg = Image.GetInstance(footerImgInfo.ReportImage); // Create the header table... tblHeader = new PdfPTable(2) { TotalWidth = document.Right, }; tblHeader.SetWidths(new float[2] { document.Right - 70f, 70f }); PdfPCell titleCell = new PdfPCell(new Phrase(HeaderTitle)) { BackgroundColor = headerColor }; tblHeader.AddCell(titleCell); PdfPCell imgCell = new PdfPCell(headerImg) { BackgroundColor = headerColor, HorizontalAlignment = PdfPCell.ALIGN_RIGHT, }; tblHeader.AddCell(imgCell); } public override void OnEndPage(PdfWriter writer, Document document) { base.OnEndPage(writer, document); // Add the header table to the tops of the documents... document.Add(tblHeader); // Create the image at the footer. footerImg.SetAbsolutePosition(0, document.Bottom); document.Add(footerImg); } 

但是,当我到达其中一个页面上的document.Add(tblHeader)行时(这是一个相当大的pdf(可能是10页))。 我得到一个堆栈溢出exception)。

我在这里做错了什么(如果有的话)? 最后一个问题,我问我收到了一个礼貌的RTM,然而,在阅读了大量文档之后,我看不出为什么相对简单的东西会导致堆栈溢出。 请帮我理解。

正如官方文档中所提到的, 严禁在页面事件中向document对象添加内容。 该document对象不是您在主代码中使用的Document对象。 相反,它是一个内部PdfDocument实例,它被传递给事件以供只读使用

如果要在页面事件中添加表,则应使用writeSelectedRows()方法。 请下载免费电子书StackOverflow上的最佳iText问题,并查看有关事件的章节。

您将找到以下问题的参考:

  • “OnEndPage”事件处理程序中的“’System.StackOverflowException” (您要问的是什么;阅读本书会对您有所帮助)
  • 使用itext在pdf footer中创建包含2行的表
  • 如何将表添加为标题?

阅读免费提供的文档可以为您(和我们)节省大量时间;-)