PDF Header and Footer in Silverlight

  • Demo
  • App.xaml
  • App.xaml.cs
  • App.xaml.vb
  • MainPage.xaml
  • MainPage.xaml.cs
  • MainPage.xaml.vb

The sample demonstrates how to create PDF Header and Footer in Silverlight via Spire.PDF.

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
             x:Class="HeaderAndFooter_PDF.App">
             
    <Application.Resources>
        
    </Application.Resources>
</Application>

using System;
using System.Windows;

namespace HeaderAndFooter_PDF
{
    public partial class App : Application
    {

        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            this.RootVisual = new MainPage();
        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // the browser's exception mechanism. On IE this will display it a yellow alert 
            // icon in the status bar and Firefox will display a script error.
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
            }
        }

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }
    }
}

Imports System.Net
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Imports System.Windows.Input
Imports System.Windows.Media
Imports System.Windows.Media.Animation
Imports System.Windows.Shapes

Namespace HeaderAndFooter_PDF
	Partial Public Class App
		Inherits Application

		Public Sub New()
			AddHandler Me.Startup, AddressOf Application_Startup
			AddHandler Me.Exit, AddressOf Application_Exit
			AddHandler Me.UnhandledException, AddressOf Application_UnhandledException

			InitializeComponent()
		End Sub

		Private Sub Application_Startup(ByVal sender As Object, ByVal e As StartupEventArgs)
			Me.RootVisual = New MainPage()
		End Sub

		Private Sub Application_Exit(ByVal sender As Object, ByVal e As EventArgs)

		End Sub

		Private Sub Application_UnhandledException(ByVal sender As Object, ByVal e As ApplicationUnhandledExceptionEventArgs)
			' If the app is running outside of the debugger then report the exception using
			' the browser's exception mechanism. On IE this will display it a yellow alert 
			' icon in the status bar and Firefox will display a script error.
			If Not Debugger.IsAttached Then

				' NOTE: This will allow the application to continue running after an exception has been thrown
				' but not handled. 
				' For production applications this error handling should be replaced with something that will 
				' report the error to the website and stop the application.
				e.Handled = True
				Deployment.Current.Dispatcher.BeginInvoke(Sub() ReportErrorToDOM(e))
			End If
		End Sub

		Private Sub ReportErrorToDOM(ByVal e As ApplicationUnhandledExceptionEventArgs)
			Try
				Dim errorMsg As String = e.ExceptionObject.Message + e.ExceptionObject.StackTrace
				errorMsg = errorMsg.Replace(""""c, "'"c).Replace(vbCrLf, vbLf)

				System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(""Unhandled Error in Silverlight Application " & errorMsg & """);")
			Catch e1 As Exception
			End Try
		End Sub
	End Class
End Namespace

<UserControl x:Class="HeaderAndFooter_PDF.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White" Loaded="LayoutRoot_Loaded">
        <Button Content="Run" Height="23" HorizontalAlignment="Left" Margin="183,220,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    </Grid>
</UserControl>

using System.Windows;
using System.Windows.Controls;
using System.IO;

using Spire.Pdf;
using Spire.Pdf.Graphics;

namespace HeaderAndFooter_PDF
{
    public partial class MainPage : UserControl
    {

        public MainPage()
        {
            InitializeComponent();

        }

        private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {


        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "PDF Document (*.pdf)|*.pdf";

            bool? result = saveFileDialog.ShowDialog();
            if (!result.HasValue || !result.Value)
            {
                return;
            }

            //create a PDF document
            PdfDocument pdfDoc = new PdfDocument();

            // Create one page
            PdfPageBase page = pdfDoc.Pages.Add();
            PdfBrush brush = PdfBrushes.SkyBlue;

            // Draw the text
            page.Canvas.DrawString("This is a simple sample demonstrates how to add header and footer in a PDF document!",
                                   new PdfFont(PdfFontFamily.Helvetica, 12f), brush,
                                   10, 50);

            //create a margin
            PdfMargins margin = new PdfMargins();
            margin.Top = (float)2.54 * 19;
            margin.Bottom = margin.Top;
            margin.Left = (float)3.17 * 19;
            margin.Right = margin.Left;

            //draw the header and footer
            foreach (PdfPageBase pages in pdfDoc.Pages)
            {
                DrawPageHeaderAndFooter(pages, margin);
            }

            //save the pdf document
            using (Stream stream = saveFileDialog.OpenFile())
            {
                pdfDoc.SaveToStream(stream);
            }

            //close the PDF document  
            pdfDoc.Close();
        }

        private void DrawPageHeaderAndFooter(PdfPageBase page, PdfMargins margin)
        {
            page.Canvas.SetTransparency(0.5f);
            PdfBrush brush = PdfBrushes.Black;
            PdfPen pen = new PdfPen(brush, 0.75f);

            PdfFont font = new PdfFont(PdfFontFamily.Courier, 10f, PdfFontStyle.Italic);
            PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Right);
            format.MeasureTrailingSpaces = true;
            float space = font.Height * 0.75f;
            float x = margin.Left;
            float width = page.Canvas.ClientSize.Width - margin.Left - margin.Right;
            float height = page.Canvas.ClientSize.Height - margin.Left - margin.Right;
            float y = margin.Top + space;

            //draw the header
            page.Canvas.DrawString("header of page", font, brush, x + width, y, format);
            y = y + 1 + font.Height;
            page.Canvas.DrawLine(pen, x, y, x + width, y);

            //draw the footer           
            page.Canvas.DrawLine(pen, x, y + height, x + width, y + height);
            y = y + (font.Height / 2);
            page.Canvas.DrawString("footer of page", font, brush, x + width, y + height, format);
        }
    }
}

Imports System.Windows
Imports System.Windows.Controls
Imports System.IO

Imports Spire.Pdf
Imports Spire.Pdf.Graphics

Namespace HeaderAndFooter_PDF
	Partial Public Class MainPage
		Inherits UserControl

		Public Sub New()
			InitializeComponent()

		End Sub

		Private Sub LayoutRoot_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)


		End Sub

		Private Sub button1_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
			Dim saveFileDialog As New SaveFileDialog()
			saveFileDialog.Filter = "PDF Document (*.pdf)|*.pdf"

			Dim result? As Boolean = saveFileDialog.ShowDialog()
			If (Not result.HasValue) OrElse (Not result.Value) Then
				Return
			End If

			'create a PDF document
			Dim pdfDoc As New PdfDocument()

			' Create one page
			Dim page As PdfPageBase = pdfDoc.Pages.Add()
			Dim brush As PdfBrush = PdfBrushes.SkyBlue

			' Draw the text
			page.Canvas.DrawString("This is a simple sample demonstrates how to add header and footer in a PDF document!", New PdfFont(PdfFontFamily.Helvetica, 12f), brush, 10, 50)

			'create a margin
			Dim margin As New PdfMargins()
			margin.Top = CSng(2.54) * 19
			margin.Bottom = margin.Top
			margin.Left = CSng(3.17) * 19
			margin.Right = margin.Left

			'draw the header and footer
			For Each pages As PdfPageBase In pdfDoc.Pages
				DrawPageHeaderAndFooter(pages, margin)
			Next pages

			'save the pdf document
			Using stream As Stream = saveFileDialog.OpenFile()
				pdfDoc.SaveToStream(stream)
			End Using

			'close the PDF document  
			pdfDoc.Close()
		End Sub

		Private Sub DrawPageHeaderAndFooter(ByVal page As PdfPageBase, ByVal margin As PdfMargins)
			page.Canvas.SetTransparency(0.5f)
			Dim brush As PdfBrush = PdfBrushes.Black
			Dim pen As New PdfPen(brush, 0.75f)

			Dim font As New PdfFont(PdfFontFamily.Courier, 10f, PdfFontStyle.Italic)
			Dim format As New PdfStringFormat(PdfTextAlignment.Right)
			format.MeasureTrailingSpaces = True
			Dim space As Single = font.Height * 0.75f
			Dim x As Single = margin.Left
			Dim width As Single = page.Canvas.ClientSize.Width - margin.Left - margin.Right
			Dim height As Single = page.Canvas.ClientSize.Height - margin.Left - margin.Right
			Dim y As Single = margin.Top + space

			'draw the header
			page.Canvas.DrawString("header of page", font, brush, x + width, y, format)
			y = y + 1 + font.Height
			page.Canvas.DrawLine(pen, x, y, x + width, y)

			'draw the footer           
			page.Canvas.DrawLine(pen, x, y + height, x + width, y + height)
			y = y + (font.Height \ 2)
			page.Canvas.DrawString("footer of page", font, brush, x + width, y + height, format)
		End Sub
	End Class
End Namespace