I am using the latest version of iTextSharp (5.4.3). When defining an even simple page header the header gets out of vertical alignment if the document contains large tables that do not fit on one page. The alignment on the first page a large table is displayed is fine, but on subsequent pages the header is displayed further down and overlays the table.
My code is below. Would be nice to get a workaround or an idea what could be wrong.
By the way: When adding paragraphs that cause an automatic page break I get the page headers as expected.
Here's my test code:
const string pdfFileName = "iTestSharp Table Split Test.pdf";
using (var pdfFileStream = File.Create(pdfFileName))
{
using (Document document = new Document(PageSize.A4, 25, 25, 30, 30))
{
PdfWriter pdfWriter = PdfWriter.GetInstance(document, pdfFileStream);
pdfWriter.PageEvent = new PageEventHelper();
document.Open();
// When adding a large table the page heading for pages automatically created
// by the table are out of alignment
const int numberOfRows = 50;
PdfPTable table = new PdfPTable(1)
{
TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin,
LockedWidth = true
};
for (int i = 1; i <= numberOfRows; i++)
{
table.AddCell(i.ToString());
}
document.Add(table);
// Adding more paragraphs than fit on one page creates page headers as expected
document.NewPage();
for (int i = 1; i <= numberOfRows; i++)
{
document.Add(new Paragraph("Line " + i));
}
}
}
And here's the (very simple) PageEventHelper class:
public class PageEventHelper : PdfPageEventHelper
{
public override void OnStartPage(PdfWriter writer, Document document)
{
base.OnStartPage(writer, document); // Does actually nothing
document.Add(new Paragraph("Page Heading"));
}
}
Result Page 1:
Result Page 2: Edit:
LineSeparator
s added in PdfPageEventHelper.OnStartPage
are displayed correctly as long as they are not inside a Chunk
. Chunk
and Paragraph
objects get out of alignment (even if a LineSeparator
is before and/or after them). It looks like paragraphs are correctly added (the lines are in the header) but only the text inside them is printed out in a wrong place.
In
OnStartPage
andOnEndPage
you are not supposed to add anything to the givenDocument
instance. Instead headers and footers shall be added to the direct content of the givenPdfWriter
. Cf. The iText(Sharp) samples, e.g.