PdfPTable as a header in iTextSharp

落爺英雄遲暮 提交于 2019-11-28 12:28:33
David Fox

Bingo! PdfPageEventHandler class worked for me.

I used the PdfPageEventHelper overriding the OnEndPage method:

class _events : PdfPageEventHelper
{
    public override void OnEndPage(PdfWriter writer, Document document)
    {
        PdfPTable table = new PdfPTable(1);
        //table.WidthPercentage = 100; //PdfPTable.writeselectedrows below didn't like this
        table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; //this centers [table]
        PdfPTable table2 = new PdfPTable(2);

        //logo
        PdfPCell cell2 = new PdfPCell(Image.GetInstance(@"C:\path\to\file.gif"));
        cell2.Colspan = 2;
        table2.AddCell(cell2);

        //title
        cell2 = new PdfPCell(new Phrase("\nTITLE", new Font(Font.HELVETICA, 16, Font.BOLD | Font.UNDERLINE)));
        cell2.HorizontalAlignment = Element.ALIGN_CENTER;
        cell2.Colspan = 2;
        table2.AddCell(cell2);

        PdfPCell cell = new PdfPCell(table2);
        table.AddCell(cell);

        table.WriteSelectedRows(0, -1, document.LeftMargin, document.PageSize.Height - 36, writer.DirectContent);
    }
}

then, build pdf

Document document = new Document(PageSize.A4, 36, 36, 36 + <height of table>, 36); // note height should be set here
_events e = new _events();
PdfWriter pw = PdfWriter.GetInstance(document, new FileStream("TableTest.pdf", FileMode.Create));
pw.PageEvent = e;
document.Open();

for(int i=0;i<100;i++)
{
    document.Add(new Phrase("TESTING\n"));
}

document.Close();

I used a a very simple approach to add a header row on each page, when creating a PdfPTable with 'n' rows, where 'n' could any integer. I am using iTextSharp 4.0.4.0.

So, you could create a table with 1000 rows or 2 rows or 5000 rows, but iTextSharp will automatically page the output for you. What iTextSharp will not do is automatically add a header to start of every page.

In order to add a header row for every page, all I did was add the single line of code after creating the PdfPTable with all its rows and cells, and then iTextSharp automatically paged the output with a header row. 'table' is the instance of PdfPTable that I created in my code before setting its HeaderRows property.

table.HeaderRows = 1; //this will automatically insert a header row 
                      //at start of every page. The first row you created
                      //in your code will be used as the header row in this case.

This will not work if you have more than one page. If you have more than one page, then you need to use the OnStartPage event instead of the onEndPage event.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!