Header And Footer

This example demonstrates how to add header and footer.

Every document which have a header and fotter helps in explanting the topic and make all the pages connected in a document

Clicking on the generate button will launch a pdf with preset header and fotter.

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using OfficeComponent.Pdf;
using OfficeComponent.Pdf.Fields;
using OfficeComponent.Pdf.Graphics;

namespace OfficeComponent.Samples
{
    class HeaderAndFooterExample : ExampleBase
    {
        private bool _paginateStart = true;
        RectangleF _bounds;

        public HeaderAndFooterExample(string commonDataPath, string outputDir)
            : base(commonDataPath, outputDir)
        {
        }

        public HeaderAndFooterExample(string commonDataPath, string outputDir, string xmlFile)
            : base(commonDataPath, outputDir, xmlFile)
        {
        }

        public override string Execute()
        {
            // Create a new instance of PdfDocument class.
            PdfDocument doc = new PdfDocument();


            // Set document's information.
            doc.DocumentInformation.Author = "OfficeComponent";
            doc.DocumentInformation.Producer = "OfficeComponent";
            doc.DocumentInformation.Creator = "OfficeComponent";
            doc.DocumentInformation.Title = Title;

            //Add a page
            PdfPage page = doc.Pages.Add();

            //Create font
            PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 11.5f);

            Font ttf = new Font("Calibri", 14f, FontStyle.Bold);
            PdfTrueTypeFont heading = new PdfTrueTypeFont(ttf, true);

            //Adding Header
            AddHeader(doc, "OfficeComponent OfficeComponentPdf", "Header and Footer Demo");

            //Adding Footer
            AddFooter(doc, "@Copyright " + DateTime.Now.Year);

            //Set formats
            PdfStringFormat format = new PdfStringFormat();
            format.Alignment = PdfTextAlignment.Justify;
            string expath = CommonDataPath + "\\About.txt";
            StreamReader reader = new StreamReader(expath, Encoding.ASCII);
            string text = reader.ReadToEnd();
            reader.Close();

            RectangleF column = new RectangleF(0, 20, page.Graphics.ClientSize.Width - 10f, page.Graphics.ClientSize.Height);
            _bounds = column;

            //Create text element to control the text flow
            PdfTextElement element = new PdfTextElement(text, font);
            element.Brush = new PdfSolidBrush(Color.Black);
            element.StringFormat = format;
            PdfLayoutSettings layoutFormat = new PdfLayoutSettings();
            layoutFormat.Break = PdfLayoutBreakType.FitPage;
            layoutFormat.Layout = PdfLayoutType.Paginate;

            //Get the remaining text that flows beyond the boundary.
            PdfTextLayoutResult result = element.Draw(page, _bounds, layoutFormat);

            expath = CommonDataPath + "\\OfficeComponentPdf.txt";
            reader = new StreamReader(expath, Encoding.ASCII);
            text = reader.ReadToEnd();
            reader.Close();

            element = new PdfTextElement(text, font);
            element.Brush = new PdfSolidBrush(Color.Black);
            element.StringFormat = format;

            // Next paragraph flow from last line of the previous paragraph.
            _bounds.Y = result.LastLineBounds.Y + 35f;

            //Raise the event when the text flows to next page.
            element.BeforePageLayout += BeginPageLayout2;

            //Raise the event when the text reaches the end of the page.
            element.AfterPageLayout += EndPageLayout2;
            result.Page.Graphics.DrawString("OfficeComponentPdf", heading, PdfBrushes.DarkBlue, new PointF(_bounds.X, _bounds.Y));

            _bounds.Y = result.LastLineBounds.Y + 60f;
            element.Draw(result.Page, new RectangleF(_bounds.X, _bounds.Y, _bounds.Width, -1), layoutFormat);

            if (!Directory.Exists(CommonDataPath))
                Directory.CreateDirectory(CommonDataPath);

            // Save and close the document.
            var outputPath = Path.Combine(OutputDir, this.GetType().Name + "_" + Guid.NewGuid().ToString() + ".pdf");
            doc.Save(outputPath);
            doc.Close(true);

            return outputPath;
        }
        private static void EndPageLayout2(object sender, AfterPageLayoutEventArgs e)
        {
            AfterTextPageLayoutEventArgs args = (AfterTextPageLayoutEventArgs)e;
            PdfTextLayoutResult tlr = args.Result;
            args.NextPage = tlr.Page;
        }
        private void BeginPageLayout2(object sender, BeforePageLayoutEventArgs e)
        {

            RectangleF bounds = e.Bounds;

            // First column.
            if (!_paginateStart)
            {
                bounds.X = bounds.Width + 20f;
                bounds.Y = 10f;
            }
            else
            {
                // Second column.
                bounds.X = 0f;
                _paginateStart = false;
            }

            e.Bounds = bounds;
        }

        private void AddHeader(PdfDocument doc, string title, string description)
        {
            RectangleF rect = new RectangleF(0, 0, doc.Pages[0].GetClientSize().Width, 50);

            //Create page template
            PdfPageTemplateElement header = new PdfPageTemplateElement(rect);
            Color activeColor = Color.FromArgb(44, 71, 120);
            SizeF imageSize = new SizeF(252f * 0.8f, 34f * 0.8f);
            //Locating the logo on the right corner of the Drawing Surface
            PointF imageLocation = new PointF(doc.Pages[0].GetClientSize().Width - imageSize.Width - 20, 11);

            PdfImage img = new PdfBitmap(CommonDataPath + "\\Logo.gif");

            //Draw the image in the Header.
            header.Graphics.DrawImage(img, imageLocation, imageSize);

            PdfSolidBrush brush = new PdfSolidBrush(activeColor);

            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 16, PdfFontStyle.Bold);

            //Set formattings for the text
            PdfStringFormat format = new PdfStringFormat();
            format.Alignment = PdfTextAlignment.Left;
            format.LineAlignment = PdfVerticalAlignment.Middle;

            //Draw title
            header.Graphics.DrawString(title, font, brush, new RectangleF(0, 0, header.Width, header.Height), format);
            brush = new PdfSolidBrush(Color.Gray);
            font = new PdfStandardFont(PdfFontFamily.Helvetica, 6, PdfFontStyle.Bold);

            format = new PdfStringFormat();
            format.Alignment = PdfTextAlignment.Left;
            format.LineAlignment = PdfVerticalAlignment.Bottom;

            //Draw description
            header.Graphics.DrawString(description, font, brush, new RectangleF(0, 0, header.Width, header.Height - 8), format);

            //Draw some lines in the header
            PdfPen pen = new PdfPen(Color.DarkBlue, 0.7f);
            header.Graphics.DrawLine(pen, 0, 0, header.Width, 0);
            pen = new PdfPen(Color.DarkBlue, 2f);
            header.Graphics.DrawLine(pen, 0, 03, header.Width + 3, 03);
            pen = new PdfPen(Color.DarkBlue, 2f);
            header.Graphics.DrawLine(pen, 0, header.Height - 3, header.Width, header.Height - 3);
            header.Graphics.DrawLine(pen, 0, header.Height, header.Width, header.Height);

            //Add header template at the top.
            doc.Template.Top = header;

        }

        private static void AddFooter(PdfDocument doc, string footerText)
        {
            RectangleF rect = new RectangleF(0, 0, doc.Pages[0].GetClientSize().Width, 50);

            //Create a page template
            PdfPageTemplateElement footer = new PdfPageTemplateElement(rect);

            PdfSolidBrush brush = new PdfSolidBrush(Color.Gray);

            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 6, PdfFontStyle.Bold);
            PdfStringFormat format = new PdfStringFormat();
            format.Alignment = PdfTextAlignment.Center;
            format.LineAlignment = PdfVerticalAlignment.Middle;
            footer.Graphics.DrawString(footerText, font, brush, new RectangleF(0, 18, footer.Width, footer.Height), format);

            format = new PdfStringFormat();
            format.Alignment = PdfTextAlignment.Right;
            format.LineAlignment = PdfVerticalAlignment.Bottom;

            //Create page number field
            PdfPageNumberField pageNumber = new PdfPageNumberField(font, brush);

            //Create page count field
            PdfPageCountField count = new PdfPageCountField(font, brush);

            PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumber, count);
            compositeField.Bounds = footer.Bounds;
            compositeField.Draw(footer.Graphics, new PointF(470, 40));

            //Add the footer template at the bottom
            doc.Template.Bottom = footer;

        }
    }
}
Imports System.IO
Imports System.Text
Imports OfficeComponent.Pdf
Imports OfficeComponent.Pdf.Fields
Imports OfficeComponent.Pdf.Graphics

Namespace OfficeComponent.Samples
	Friend Class HeaderAndFooterExample
		Inherits ExampleBase
		Private _paginateStart As Boolean = True
		Private _bounds As RectangleF

		Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String)
			MyBase.New(commonDataPath, outputDir)
		End Sub

		Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String, ByVal xmlFile As String)
			MyBase.New(commonDataPath, outputDir, xmlFile)
		End Sub

		Public Overrides Function Execute() As String
			' Create a new instance of PdfDocument class.
			Dim doc As New PdfDocument()


			' Set document's information.
			doc.DocumentInformation.Author = "OfficeComponent"
			doc.DocumentInformation.Producer = "OfficeComponent"
			doc.DocumentInformation.Creator = "OfficeComponent"
			doc.DocumentInformation.Title = Title

			'Add a page
			Dim page As PdfPage = doc.Pages.Add()

			'Create font
			Dim font As New PdfStandardFont(PdfFontFamily.Helvetica, 11.5F)

			Dim ttf As New Font("Calibri", 14F, FontStyle.Bold)
			Dim heading As New PdfTrueTypeFont(ttf, True)

			'Adding Header
			AddHeader(doc, "OfficeComponent OfficeComponentPdf", "Header and Footer Demo")

			'Adding Footer
			AddFooter(doc, "@Copyright " & Date.Now.Year)

			'Set formats
			Dim format As New PdfStringFormat()
			format.Alignment = PdfTextAlignment.Justify
			Dim expath As String = CommonDataPath & "\About.txt"
			Dim reader As New StreamReader(expath, Encoding.ASCII)
			Dim text As String = reader.ReadToEnd()
			reader.Close()

			Dim column As New RectangleF(0, 20, page.Graphics.ClientSize.Width - 10F, page.Graphics.ClientSize.Height)
			_bounds = column

			'Create text element to control the text flow
			Dim element As New PdfTextElement(text, font)
			element.Brush = New PdfSolidBrush(Color.Black)
			element.StringFormat = format
			Dim layoutFormat As New PdfLayoutSettings()
			layoutFormat.Break = PdfLayoutBreakType.FitPage
			layoutFormat.Layout = PdfLayoutType.Paginate

			'Get the remaining text that flows beyond the boundary.
			Dim result As PdfTextLayoutResult = element.Draw(page, _bounds, layoutFormat)

			expath = CommonDataPath & "\OfficeComponentPdf.txt"
			reader = New StreamReader(expath, Encoding.ASCII)
			text = reader.ReadToEnd()
			reader.Close()

			element = New PdfTextElement(text, font)
			element.Brush = New PdfSolidBrush(Color.Black)
			element.StringFormat = format

			' Next paragraph flow from last line of the previous paragraph.
			_bounds.Y = result.LastLineBounds.Y + 35F

			'Raise the event when the text flows to next page.
			AddHandler element.BeforePageLayout, AddressOf BeginPageLayout2

			'Raise the event when the text reaches the end of the page.
			AddHandler element.AfterPageLayout, AddressOf EndPageLayout2
			result.Page.Graphics.DrawString("OfficeComponentPdf", heading, PdfBrushes.DarkBlue, New PointF(_bounds.X, _bounds.Y))

			_bounds.Y = result.LastLineBounds.Y + 60F
			element.Draw(result.Page, New RectangleF(_bounds.X, _bounds.Y, _bounds.Width, -1), layoutFormat)

			If Not Directory.Exists(CommonDataPath) Then
				Directory.CreateDirectory(CommonDataPath)
			End If

			' Save and close the document.
			Dim outputPath = Path.Combine(OutputDir, Me.GetType().Name & "_" & Guid.NewGuid().ToString() & ".pdf")
			doc.Save(outputPath)
			doc.Close(True)

			Return outputPath
		End Function
		Private Shared Sub EndPageLayout2(ByVal sender As Object, ByVal e As AfterPageLayoutEventArgs)
			Dim args As AfterTextPageLayoutEventArgs = CType(e, AfterTextPageLayoutEventArgs)
			Dim tlr As PdfTextLayoutResult = args.Result
			args.NextPage = tlr.Page
		End Sub
		Private Sub BeginPageLayout2(ByVal sender As Object, ByVal e As BeforePageLayoutEventArgs)

			Dim bounds As RectangleF = e.Bounds

			' First column.
			If Not _paginateStart Then
				bounds.X = bounds.Width + 20F
				bounds.Y = 10F
			Else
				' Second column.
				bounds.X = 0F
				_paginateStart = False
			End If

			e.Bounds = bounds
		End Sub

		Private Sub AddHeader(ByVal doc As PdfDocument, ByVal title As String, ByVal description As String)
			Dim rect As New RectangleF(0, 0, doc.Pages(0).GetClientSize().Width, 50)

			'Create page template
			Dim header As New PdfPageTemplateElement(rect)
			Dim activeColor As Color = Color.FromArgb(44, 71, 120)
			Dim imageSize As New SizeF(252F * 0.8F, 34F * 0.8F)
			'Locating the logo on the right corner of the Drawing Surface
			Dim imageLocation As New PointF(doc.Pages(0).GetClientSize().Width - imageSize.Width - 20, 11)

			Dim img As PdfImage = New PdfBitmap(CommonDataPath & "\Logo.gif")

			'Draw the image in the Header.
			header.Graphics.DrawImage(img, imageLocation, imageSize)

			Dim brush As New PdfSolidBrush(activeColor)

			Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 16, PdfFontStyle.Bold)

			'Set formattings for the text
			Dim format As New PdfStringFormat()
			format.Alignment = PdfTextAlignment.Left
			format.LineAlignment = PdfVerticalAlignment.Middle

			'Draw title
			header.Graphics.DrawString(title, font, brush, New RectangleF(0, 0, header.Width, header.Height), format)
			brush = New PdfSolidBrush(Color.Gray)
			font = New PdfStandardFont(PdfFontFamily.Helvetica, 6, PdfFontStyle.Bold)

			format = New PdfStringFormat()
			format.Alignment = PdfTextAlignment.Left
			format.LineAlignment = PdfVerticalAlignment.Bottom

			'Draw description
			header.Graphics.DrawString(description, font, brush, New RectangleF(0, 0, header.Width, header.Height - 8), format)

			'Draw some lines in the header
			Dim pen As New PdfPen(Color.DarkBlue, 0.7F)
			header.Graphics.DrawLine(pen, 0, 0, header.Width, 0)
			pen = New PdfPen(Color.DarkBlue, 2F)
			header.Graphics.DrawLine(pen, 0, 03, header.Width + 3, 03)
			pen = New PdfPen(Color.DarkBlue, 2F)
			header.Graphics.DrawLine(pen, 0, header.Height - 3, header.Width, header.Height - 3)
			header.Graphics.DrawLine(pen, 0, header.Height, header.Width, header.Height)

			'Add header template at the top.
			doc.Template.Top = header

		End Sub

		Private Shared Sub AddFooter(ByVal doc As PdfDocument, ByVal footerText As String)
			Dim rect As New RectangleF(0, 0, doc.Pages(0).GetClientSize().Width, 50)

			'Create a page template
			Dim footer As New PdfPageTemplateElement(rect)

			Dim brush As New PdfSolidBrush(Color.Gray)

			Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 6, PdfFontStyle.Bold)
			Dim format As New PdfStringFormat()
			format.Alignment = PdfTextAlignment.Center
			format.LineAlignment = PdfVerticalAlignment.Middle
			footer.Graphics.DrawString(footerText, font, brush, New RectangleF(0, 18, footer.Width, footer.Height), format)

			format = New PdfStringFormat()
			format.Alignment = PdfTextAlignment.Right
			format.LineAlignment = PdfVerticalAlignment.Bottom

			'Create page number field
			Dim pageNumber As New PdfPageNumberField(font, brush)

			'Create page count field
			Dim count As New PdfPageCountField(font, brush)

			Dim compositeField As New PdfCompositeField(font, brush, "Page {0} of {1}", pageNumber, count)
			compositeField.Bounds = footer.Bounds
			compositeField.Draw(footer.Graphics, New PointF(470, 40))

			'Add the footer template at the bottom
			doc.Template.Bottom = footer

		End Sub
	End Class
End Namespace