SelectPdf for .NET - Modify Existing Pdf Document to Add Headers and Footers - VB.NET / ASP.NET MVC 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 SelectPdf
Imports System.Drawing

Namespace Controllers
    Public Class ExistingPdfHeadersAndFootersController
        Inherits Controller

        ' GET: ExistingPdfHeadersAndFooters
        Public Function Index() As ActionResult
            Return View()
        End Function

        Public Function SubmitAction(collection As FormCollection) As ActionResult
            ' 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}.",
            text1.ForeColor = System.Drawing.Color.Blue

            ' save pdf document
            Dim pdf As Byte() = doc.Save()

            ' close pdf document

            ' return resulted pdf document
            Dim fileResult As FileResult = New FileContentResult(pdf, "application/pdf")
            fileResult.FileDownloadName = "Document.pdf"
            Return fileResult
        End Function
    End Class
End Namespace