首页 文章

iTextSharp自定义纸张尺寸

提问于
浏览
2

我正在使用iTextsharp库来创建PDF文件 . 我可以像这样声明A4风景纸:

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

我想知道如何手动设置pdfTable或A4高度的高度 . 因为底部留下了更多的边距,我需要在该边缘放置一些文字 . 现在,我在底部放了一行文字,这条线被推到了新的页面 .

Q1:如何覆盖iTextsharp提供的A4纸的高度?

Q2:如何创建自定义尺寸纸张,例如宽度= 29厘米,高度= 22厘米?

谢谢 .

2 回答

  • 8

    您可以使用自定义PdfpageEvent向页脚添加文本或表格或其他内容 .

    下面是一些代码,它向页脚添加了一个4列表(抱歉,它在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);
    }
    

    这是调用上面代码的代码:

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

    iTextSharp中的自定义页面大小:

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

    iTextSharp每英寸使用72个像素,因此如果您知道所需页面大小的高度和宽度(以英寸为单位),只需将这些数字乘以72即可得到myWidth和myHeight .

相关问题