Add Header and Footer for PDF using iTextsharp

后端 未结 9 1697
情歌与酒
情歌与酒 2020-11-27 04:04

How can I add header and footer for each page in the pdf.

Headed will contain just a text Footer will contain a text and pagination for pdf (Page : 1 of 4)

H

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 04:20

    This link will help you out completely(the Shortest and Most Elegant way):

    Header Footer with PageEvent

            PdfPTable tbheader = new PdfPTable(3);
            tbheader.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
            tbheader.DefaultCell.Border = 0;
            tbheader.AddCell(new Paragraph());
            tbheader.AddCell(new Paragraph());
            var _cell2 = new PdfPCell(new Paragraph("This is my header", arial_italic));
            _cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
            _cell2.Border = 0;
            tbheader.AddCell(_cell2);
            float[] widths = new float[] { 20f, 20f, 60f };
            tbheader.SetWidths(widths);
            tbheader.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetTop(document.TopMargin), writer.DirectContent);
    
            PdfPTable tbfooter = new PdfPTable(3);
            tbfooter.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
            tbfooter.DefaultCell.Border = 0;
            tbfooter.AddCell(new Paragraph());
            tbfooter.AddCell(new Paragraph());
            var _cell2 = new PdfPCell(new Paragraph("This is my footer", arial_italic));
            _cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
            _cell2.Border = 0;
            tbfooter.AddCell(_cell2);
            tbfooter.AddCell(new Paragraph());
            tbfooter.AddCell(new Paragraph());
            var _celly = new PdfPCell(new Paragraph(writer.PageNumber.ToString()));//For page no.
            _celly.HorizontalAlignment = Element.ALIGN_RIGHT;
            _celly.Border = 0;
            tbfooter.AddCell(_celly);
            float[] widths1 = new float[] { 20f, 20f, 60f };
            tbfooter.SetWidths(widths1);
            tbfooter.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent);
    

提交回复
热议问题