Introduction
Very often, when you generate company specific PDF documents, you have to repeatedly add blocks of information containing logos or security notices to each page, thus adding footer or header, or maybe both.
If you use the Flow layout API provided by Apitron PDF Kit for .NET PDF library for PDF generation, you can add headers and footers to each page automatically and in this article we’ll create a small app demonstrating it.
The code
We’ll add a logo and a block of text to the page header, and page number to the footer.
classProgram
{
staticvoid Main(string[] args)
{
// register doc's resources first
ResourceManager resourceManager = newResourceManager();
resourceManager.RegisterResource(
new Apitron.PDF.Kit.FixedLayout.Resources.XObjects.Image ("logo",
"../../data/logo.png"));
// create document
FlowDocument doc = newFlowDocument(){Margin = newThickness(10)};
// register styles
doc.StyleManager.RegisterStyle(".pageHeader",newStyle()
{Font = newFont(StandardFonts.TimesBold, 20)});
doc.StyleManager.RegisterStyle(".pageFooter",newStyle(){Align = Align.Right});
doc.StyleManager.RegisterStyle("hr",newStyle(){Height = 2,
Margin = newThickness(0,5,0,5)});
doc.StyleManager.RegisterStyle(".content",newStyle(){Align = Align.Justify,
Display = Display.InlineBlock});
// fill the header section
doc.PageHeader.Class = "pageHeader";
doc.PageHeader.Add(newImage("logo"){Width = 100, Height = 50});
doc.PageHeader.Add(newTextBlock("This document is intended for internal use
only"){TextIndent = 20});
doc.PageHeader.Add(newHr());
// fill the footer section
doc.PageFooter.Class = "pageFooter";
doc.PageFooter.Add(newHr());
doc.PageFooter.Add(newTextBlock((ctx)=>string.Format("Page {0}
from ",ctx.CurrentPage+1)));
doc.PageFooter.Add(newPageCount(3){Display = Display.Inline});
// add pages
for (int i = 0; i < 2; ++i)
{
doc.Add(newTextBlock(strings.LoremIpsum) {Class = "content"});
doc.Add(newPageBreak());
}
// generate PDF
using (Stream stream = File.Create("out.pdf"))
{
doc.Write(stream, resourceManager);
}
Process.Start("out.pdf");
}
}
This code adds two pages with dummy text. Please also note the use of PageCountelement in the footer section. It gets combined with page index to generate the “Page N from M” text.
The resulting document looks as follows:
![]() |
Pic. 1 Resulting PDF document |
Conclusion
Using the Flow layout you can automate insertion of page headers and footers to PDF documents with a few lines of code. The Apitron PDF Kit for .NET is a powerful PDF library offering you many unique features which are unlikely to be found anywhere else. Contact us if you have any questions or browse our GitHub repo to check out the described code sample.