I want to add a PdfPTable as page footer only to the last page of the generated PDF document. The table will have 4 columns of the same width. I have tried other solutions I found here and in other sites to no avail. I have set the bottom margin to different values to leave space to the footer and I have tried several tips to add a PDF footer, but still nothing is shown. Any help is appreciated.
Here is my code:
// The document creation
Document prDoc = new Document(PageSize.A4, 15f, 15f, 10f, 50f);
PdfWriter pdfWriter = PdfWriter.GetInstance(prDoc, Response.OutputStream);
// The event manager
prPageEvent pdfEvent = new prPageEvent();
pdfWriter.PageEvent = pdfEvent;
prDoc.Open();
.
.
.
public class prPageEvent : PdfPageEventHelper {
public PdfTemplate template;
public PdfContentByte cb;
BaseFont bf = null;
public override void OnOpenDocument(PdfWriter writer, Document document) {
try {
bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb = writer.DirectContent;
template = cb.CreateTemplate(PageSize.A4.Width, 50);
}
catch (DocumentException de) {
}
catch (System.IO.IOException ioe) {
}
}
public override void OnCloseDocument(PdfWriter writer, Document document) {
base.OnCloseDocument(writer, document);
PdfPTable f = new PdfPTable(4);
f.TotalWidth = document.PageSize.Width - document.LeftMargin;
f.AddCell(new PdfPCell(new Phrase("first")));
f.AddCell(new PdfPCell(new Phrase("second")));
f.AddCell(new PdfPCell(new Phrase("third")));
f.AddCell(new PdfPCell(new Phrase("fourth")));
f.WriteSelectedRows(0, -1, document.LeftMargin+5, document.PageSize.Height-35, writer.DirectContent);
// Only the following simple text has worked so far, but I cannot set
// the exact width to each column with this approach.
//template.BeginText();
// template.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 8);
// template.SetTextMatrix(0, 40);
// template.ShowText("first second third fourth");
//template.EndText();
}
public override void OnEndPage(PdfWriter writer, Document document) {
base.OnEndPage(writer, document);
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
System.String text = "OnEndPage";
float len = bf.GetWidthPoint(text, 8);
iTextSharp.text.Rectangle pageSize = document.PageSize;
cb.BeginText();
cb.SetFontAndSize(bf, 8);
cb.SetTextMatrix(pageSize.GetLeft(40), pageSize.GetBottom(30));
cb.EndText();
cb.AddTemplate(template, pageSize.GetLeft(40) + len, pageSize.GetBottom(30));
}
}