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

How to position iTextSharp paragraph to bottom of the page?

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

We are using iTextSharp5.5.5 to create pdf and ran into issue when positioning text to the bottom of the page. I tried to set the absolute position just like the image but that didn't work. How to display paragraph(paragraphCopyright in below code) at the bottom of the page?

        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

You can create Footer class and use it.

Create a class that inherited by PdfPageEventHelper.

Create table in this class and write footer content.

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

After this

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

And another way - You can simply add code below

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