SelectPdf for .NET - Modify Existing Pdf Document to Add Headers and Footers - VB.NET / ASP.NET Sample

This sample 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.

Headers and footers are designed using pdf templates. Header is displayed at the top of the page. Footer is displayed at the bottom of the page. They contain elements that repeat on each page of the pdf document.

Note: doc.Header and doc.Footer properties must not be used in this case, as they only work for new pdf documents or new pdf pages.

The sample uses the following (existing) test PDF:
Test PDF document

Sample Code Vb.Net

Imports System.Drawing

Public Class existing_pdf_headers_and_footers
    Inherits System.Web.UI.Page

    Protected Sub BtnCreatePdf_Click(sender As Object, e As EventArgs) _
        Handles BtnCreatePdf.Click

        ' the test file
        Dim filePdf As String = Server.MapPath("~/files/selectpdf.pdf")
        Dim imgFile As String = Server.MapPath("~/files/logo.png")

        ' resize the content
        Dim resizer As New PdfResizeManager()

        ' 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)
        Dim doc As PdfDocument = resizer.GetDocument()

        ' header template (90 points in height) with image element
        Dim header As PdfTemplate = doc.AddTemplate(doc.Pages(0).ClientRectangle.Width, 90)
        Dim img1 As New PdfImageElement(10, 10, imgFile)

        ' footer template (40 points in height) with text element
        Dim footer As PdfTemplate = doc.AddTemplate( _
            New RectangleF(0, doc.Pages(0).ClientRectangle.Height - 40, _
                           doc.Pages(0).ClientRectangle.Width, 40))

        ' create a new pdf font
        Dim font2 As PdfFont = doc.AddFont(PdfStandardFont.Helvetica)
        font2.Size = 12

        Dim text1 As New PdfTextElement(10, 10, _
            "Generated by SelectPdf. Page number {page_number} of {total_pages}.", font2)
        text1.ForeColor = System.Drawing.Color.Blue

        ' save pdf document
        doc.Save(Response, False, "Sample.pdf")

        ' close pdf document

    End Sub

End Class