iTextSharp custom paper size

倾然丶 夕夏残阳落幕 提交于 2020-01-02 13:33:10

问题


I'm using iTextsharp library to create PDF files. I can declare for A4 Landscape paper like this:

 Dim pdfTable As New PdfPTable(9)
pdfTable.WidthPercentage = 100
Dim pdfDoc As New Document(PageSize.A4.Rotate())

I'm wondering how I can set Height of pdfTable or A4 Height manually. Because there's a lot more margin left at the bottom, and I need to put some text at that margin. Right now, I put a line of text at the bottom, the line's got pushed to the new page.

Q1: How can I override the height of A4 paper provied by iTextsharp?

Q2: How can I create a custom size paper, say Width = 29cm, Height = 22cm?

Thank you.


回答1:


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();



回答2:


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.



来源:https://stackoverflow.com/questions/2493564/itextsharp-custom-paper-size

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