iTextSharp custom paper size

时光怂恿深爱的人放手 提交于 2019-12-06 13:16:57

You can use a custom PdfpageEvent to add text or a table or whatever to the footer.

Here is some code that adds a 4 column table to the footer (sorry it's in C#):

public override void OnEndPage(PdfWriter writer, iTextSharp.text.Document document)
{
    base.OnEndPage(writer, document);

    PdfContentByte cb = writer.DirectContent;

    var footerTable = new PdfPTable(4);

    var columnWidth = (document.Right - document.LeftMargin) / 4;

    footerTable.SetTotalWidth(new float[] { columnWidth, columnWidth, columnWidth, columnWidth });

    var cell1 = new PdfPCell();
    cell1.AddElement(new Paragraph("Date:"));
    cell1.AddElement(new Paragraph(DateTime.Now.ToShortDateString()));
    footerTable.AddCell(cell1);

    var cell2 = new PdfPCell();
    cell2.AddElement(new Paragraph("Data:"));
    cell2.AddElement(new Paragraph("123456789"));
    footerTable.AddCell(cell2);

    var cell3 = new PdfPCell();
    cell3.AddElement(new Paragraph("Date:"));
    cell3.AddElement(new Paragraph(DateTime.Now.ToShortDateString()));
    footerTable.AddCell(cell3);

    var cell4 = new PdfPCell();
    cell4.AddElement(new Paragraph("Page:"));
    cell4.AddElement(new Paragraph(document.PageNumber.ToString()));
    footerTable.AddCell(cell4);

    footerTable.WriteSelectedRows(0, -1, document.LeftMargin, cell4.Height + 50, cb);
}

and this is the code that would call the above code:

var pdfWriter = PdfWriter.GetInstance(pdf, new FileStream(fileName, FileMode.Create));
pdfWriter.PageEvent = new CustomPdfPageEvent();

Custom page size in iTextSharp:

Dim pgSize As New iTextSharp.text.Rectangle(myWidth, myHeight) 
Dim doc As New iTextSharp.text.Document(pgSize, leftMargin, rightMargin, topMargin, bottomMargin)

iTextSharp uses 72 pixels per inch, so if you know the height and width of your desired page size in inches, just multiply those numbers by 72 to get myWidth and myHeight.

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