Warm tip: This article is reproduced from serverfault.com, please click

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

(c# - How to position iTextSharp paragraph to bottom of the page?)

发布于 2020-06-02 23:31:09

我们使用iTextSharp5.5.5创建pdf并将文本放置在页面底部时出现问题。我想像图像一样设置绝对位置,但这没有用。如何在页面底部显示段落(以下代码中的paragraphCopyright)?

        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();
Questioner
nagiah s
Viewed
0
Raf 2020-12-09 02:35:19

你可以创建Footer类并使用它。

创建一个由继承的类PdfPageEventHelper

在此类中创建表并编写页脚内容。

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

来源文章

另一种方式-你可以在下面简单地添加代码

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