Imports SelectPdf
Imports System.Drawing

Namespace Controllers
    Public Class ExistingPdfHeadersAndFootersController
        Inherits Controller

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

        <HttpPost>
        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()
            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)
            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)
            header.Add(img1)

            ' 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
            footer.Add(text1)

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

            ' close pdf document
            resizer.Close()

            ' 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