As a continuation to my earlier question I have been trying out the header and footer functions for my PDF. After a little discussion I have changed quite a lot of code on the PdfPageEventHelper class. Below is what I have:
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);
}
However, when I get to the document.Add(tblHeader) line on one of the pages (this is a reasonably large pdf (probably 10 pages)). I get a stack overflow exception).
What am I doing wrong here (if anything)? Last question that I asked I received a polite RTM, however, having read a lot of documentation, I can't see why something relatively simple would be causing a stack overflow. Please help me to understand.