Click or drag to resize
Pdf Library for .NET
Modify Existing Pdf Document to Add Headers and Footers

SelectPdf Library for .NET can be used to add headers and footers to existing PDF documents. With existing documents, the method described in Headers And Footers section cannot be used. That only works with newly created PDF files.

To add headers and footers to existing PDF documents, first a resize of the content is performed (using the method described in Resize/Scale Existing Pdf section) to create space for the header/footer and then PDF templates are added (using the method described in Pdf Templates section).

Code Sample

The sample code below shows how to modify an existing PDF document using SelectPdf to make space for headers and footers and how to add the header and footer to the existing pdf document.

protected void BtnCreatePdf_Click(object sender, EventArgs e)
{
    // the test file
    string filePdf = Server.MapPath("~/files/selectpdf.pdf");
    string imgFile = Server.MapPath("~/files/logo.png");

    // resize the content
    PdfResizeManager resizer = new PdfResizeManager();
    resizer.Load(filePdf);

    // add extra top and bottom margins
    resizer.PageMargins = new PdfMargins(0, 0, 90, 40);

    // add the header and footer to the existing (now resized pdf document)
    PdfDocument doc = resizer.GetDocument();

    // header template (90 points in height) with image element
    PdfTemplate header = doc.AddTemplate(doc.Pages[0].ClientRectangle.Width, 90);
    PdfImageElement img1 = new PdfImageElement(10, 10, imgFile);
    header.Add(img1);

    // footer template (40 points in height) with text element
    PdfTemplate footer = doc.AddTemplate(new RectangleF(0, 
        doc.Pages[0].ClientRectangle.Height - 40, 
        doc.Pages[0].ClientRectangle.Width, 40));

    // create a new pdf font
    PdfFont font2 = doc.AddFont(PdfStandardFont.Helvetica);
    font2.Size = 12;

    PdfTextElement text1 = new PdfTextElement(10, 10,
        "Generated by SelectPdf. Page number {page_number} of {total_pages}.", 
        font2);
    text1.ForeColor = System.Drawing.Color.Blue;
    footer.Add(text1);

    // save pdf document
    doc.Save(Response, false, "Sample.pdf");

    // close pdf document
    resizer.Close();

}
See Also