PDF Page Lable in Silverlight

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

The sample demonstrates how to set PDF Page Label in Silverlight.

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

using System;
using System.Windows;

namespace PageLabel
{
    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 PageLabel
	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="PageLabel.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="288,258,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    </Grid>
</UserControl>

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

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

namespace PageLabel
{
    public partial class MainPage : UserControl
    {
        //create a saveFileDialog to save the PDF file
        private SaveFileDialog saveFileDialog = null;

        //create a pdf document
        private PdfDocument pdfDoc = new PdfDocument();

        private string text = "This is the first page"; 
        public MainPage()
        {
            InitializeComponent();

            //initialize the saveFileDialog
            this.saveFileDialog = new SaveFileDialog();
            this.saveFileDialog.Filter = "PDF Document (*.pdf)|*.pdf";
        }

        private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {
           
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //create a margin
            PdfMargins margin = new PdfMargins(62f, 50.8f, 62f, 50.8f);

            //add one section to the PDF file
            PdfSection section = this.pdfDoc.Sections.Add();

            //draw the label and text of the first page
            DrawTextandLabel(section, margin);

            ////draw the label and text of the second page
            this.text = "This is the second page";
            DrawTextandLabel(section, margin);

            //draw the label and text of the third page
            this.text = "This is the third page";
            DrawTextandLabel(section, margin);

            //save the PDF file
            bool? result = this.saveFileDialog.ShowDialog();
            if (result.HasValue && result.Value)
            {
                using (Stream stream = this.saveFileDialog.OpenFile())
                {
                    this.pdfDoc.SaveToStream(stream);
                }
            }
        }

        private void DrawTextandLabel(PdfSection section, PdfMargins margin)
        {
            //set the label of the PDF file
            section.PageNumber = new PdfPageNumber();
            section.PageNumber.NumberStyle = PdfNumberStyle.Numeric;
            section.PageNumber.Prefix = "page ";
            section.PageSettings.Size = PdfPageSize.A4;
            section.PageSettings.Margins.All = 0;

            //draw the content 
            PdfPageBase page = section.Pages.Add();
            float x = margin.Left;
            float y = margin.Top + 8;
            float width = page.Canvas.ClientSize.Width - margin.Left - margin.Right;
            PdfFont font1 = new PdfFont(PdfFontFamily.Courier, 16f);
            PdfBrush brush1 = PdfBrushes.Black;
            PdfPen pen1 = new PdfPen(brush1, 0.75f);
            PdfStringFormat format = new PdfStringFormat();
            format.MeasureTrailingSpaces = true;
            page.Canvas.DrawString(this.text, font1, brush1, x, y, format);
        }
    }
}

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

Imports Spire.Pdf
Imports Spire.Pdf.Graphics

Namespace PageLabel
	Partial Public Class MainPage
		Inherits UserControl
		'create a saveFileDialog to save the PDF file
		Private saveFileDialog As SaveFileDialog = Nothing

		'create a pdf document
		Private pdfDoc As New PdfDocument()

		Private text As String = "This is the first page"
		Public Sub New()
			InitializeComponent()

			'initialize the saveFileDialog
			Me.saveFileDialog = New SaveFileDialog()
			Me.saveFileDialog.Filter = "PDF Document (*.pdf)|*.pdf"
		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)
			'create a margin
			Dim margin As New PdfMargins(62f, 50.8f, 62f, 50.8f)

			'add one section to the PDF file
			Dim section As PdfSection = Me.pdfDoc.Sections.Add()

			'draw the label and text of the first page
			DrawTextandLabel(section, margin)

			'//draw the label and text of the second page
			Me.text = "This is the second page"
			DrawTextandLabel(section, margin)

			'draw the label and text of the third page
			Me.text = "This is the third page"
			DrawTextandLabel(section, margin)

			'save the PDF file
			Dim result? As Boolean = Me.saveFileDialog.ShowDialog()
			If result.HasValue AndAlso result.Value Then
				Using stream As Stream = Me.saveFileDialog.OpenFile()
					Me.pdfDoc.SaveToStream(stream)
				End Using
			End If
		End Sub

		Private Sub DrawTextandLabel(ByVal section As PdfSection, ByVal margin As PdfMargins)
			'set the label of the PDF file
			section.PageNumber = New PdfPageNumber()
			section.PageNumber.NumberStyle = PdfNumberStyle.Numeric
			section.PageNumber.Prefix = "page "
			section.PageSettings.Size = PdfPageSize.A4
			section.PageSettings.Margins.All = 0

			'draw the content 
			Dim page As PdfPageBase = section.Pages.Add()
			Dim x As Single = margin.Left
			Dim y As Single = margin.Top + 8
			Dim width As Single = page.Canvas.ClientSize.Width - margin.Left - margin.Right
			Dim font1 As New PdfFont(PdfFontFamily.Courier, 16f)
			Dim brush1 As PdfBrush = PdfBrushes.Black
			Dim pen1 As New PdfPen(brush1, 0.75f)
			Dim format As New PdfStringFormat()
			format.MeasureTrailingSpaces = True
			page.Canvas.DrawString(Me.text, font1, brush1, x, y, format)
		End Sub
	End Class
End Namespace