Add footer with left and right aligned text on same line

Generate PDF
3/23/2016

Add a footer to a PDF document that has left aligned text with a page number and right aligned text on the same line.

footer-left-right.png

C#

1 Document pdf = new Document(); 2 Section section = pdf.Sections.Add(); 3 4 // this bottom margin of the section determines the space available for the footer 5 section.Margin.Bottom = 100; 6 double width = section.PageSize.Width - section.Margin.Left - section.Margin.Right; 7 8 // filler text 9 for (int i=0; i<100; i++) 10 { 11 TextParagraph text = new TextParagraph(); 12 text.SpacingAfter = 12; 13 section.Paragraphs.Add(text); 14 text.Fragments.Add(new Fragment("Generate PDF documents from scratch. Use code, XML/XSL or a combination.")); 15 } 16 17 Footer footer = new Footer(); 18 section.Footer = footer; 19 20 // the trick to have both left and right aligned 21 // text on the same line is to use a table 22 Table table = new Table(); 23 24 // the footer will be top-aligned so to move it down you need 25 // to add spacing before the first paragraph of the footer 26 table.SpacingBefore = 12; 27 footer.Paragraphs.Add(table); 28 Row row = table.Rows.Add(); 29 30 // left text 31 Cell leftCell = row.Cells.Add(); 32 leftCell.PreferredWidth = width / 2; 33 TextParagraph leftText = new TextParagraph(); 34 leftCell.Paragraphs.Add(leftText); 35 Fragment pageNumber = new Fragment("Page #p"); 36 pageNumber.HasContextFields = true; 37 leftText.Fragments.Add(pageNumber); 38 39 // right text 40 Cell rightCell = row.Cells.Add(); 41 rightCell.PreferredWidth = width / 2; 42 TextParagraph rightText = new TextParagraph(); 43 rightText.HorizontalAlignment = HorizontalAlignment.Right; 44 rightCell.Paragraphs.Add(rightText); 45 Fragment title = new Fragment("TallPDF.NET"); 46 rightText.Fragments.Add(title); 47 48 string path = "out.pdf"; 49 using (FileStream file = new FileStream(path, FileMode.Create)) 50 { 51 pdf.Write(file); 52 } 53 54 System.Diagnostics.Process.Start(path);