如何将 iTextSharp 段落定位到页面底部?

How to position iTextSharp paragraph to bottom of the page?

我们使用 iTextSharp5.5.5 创建 pdf,运行 在将文本定位到页面底部时出现问题。我试图像图像一样设置绝对位置,但这没有用。 如何在页面底部显示段落(paragraphCopyright in below code)?

        var document = new Document(PageSize.A4.Rotate(), 10, 10, 10, 10);
        PdfWriter pdfWriter = PdfWriter.GetInstance(document, new FileStream("Sample.pdf", FileMode.Create));
        document.Open();

        var paragraphCopyright = new Paragraph("This text should be at the very bottom of the page", new Font(Font.FontFamily.HELVETICA, 20f, Font.BOLD)); // this text should be at the bottom
        paragraphCopyright.Alignment = 1;
        document.Add(paragraphCopyright);

        var imgLogo = iTextSharp.text.Image.GetInstance(@"logo.PNG");
        imgLogo.ScaleAbsolute(120, 80);
        imgLogo.SetAbsolutePosition(PageSize.A4.Rotate().Width - 140, 20);
        document.Add(imgLogo);

        document.Close();

您可以创建页脚 class 并使用它。

创建一个由 PdfPageEventHelper 继承的 class。

在此class中创建table并写入页脚内容。

public partial class Footer : PdfPageEventHelper
        {
            public override void OnEndPage(PdfWriter writer, Document doc)
            {
                Paragraph footer = new Paragraph("THANK YOU", FontFactory.GetFont(FontFactory.TIMES, 10, iTextSharp.text.Font.NORMAL));
                footer.Alignment = Element.ALIGN_RIGHT;
                PdfPTable footerTbl = new PdfPTable(1);
                footerTbl.TotalWidth = 300;
                footerTbl.HorizontalAlignment = Element.ALIGN_CENTER;
                PdfPCell cell = new PdfPCell(footer);
                cell.Border = 0;
                cell.PaddingLeft = 10;
                footerTbl.AddCell(cell);
                footerTbl.WriteSelectedRows(0, -1, 415, 30, writer.DirectContent);
            }
        }

之后

Document document = new Document(PageSize.A4, 50, 50, 25, 25);
var output = new FileStream(Server.MapPath("Demo.pdf"), FileMode.Create);
PdfWriter writer = PdfWriter.GetInstance(document, output);
// Open the Document for writing
document.Open();
//using footer class
writer.PageEvent = new Footer();.
Paragraph welcomeParagraph = new Paragraph("Hello, World!");
document.Add(welcomeParagraph);
document.Close();

Original article

另一种方法 - 您只需在下面添加代码

Paragraph copyright = new Paragraph("© 2020 AO XXX. All rights reserved.", calibri8Black);
PdfPTable footerTbl = new PdfPTable(1);
footerTbl.TotalWidth = 300;
PdfPCell cell = new PdfPCell(copyright);
cell.Border = 0;
footerTbl.AddCell(cell);
footerTbl.WriteSelectedRows(0, -1, 30, 30, writer.DirectContent);