Word Header in Silverlight

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

The sample demonstrates how to add Word header in Silverlight via Spire.Doc.

 

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

using System;
using System.Windows;

namespace AddHeader_Doc
{
    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 AddHeader_Doc
	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="AddHeader_Doc.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="219" d:DesignWidth="397" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

    <Grid x:Name="LayoutRoot" Background="#FFD7E1FF" Width="397" Height="219" Loaded="LayoutRoot_Loaded">
        <sdk:Label Height="24" HorizontalAlignment="Left" Margin="12,64,0,130" Name="label1" VerticalAlignment="Center" Width="373" Content="This sample demonstrates how to add header in a doc file" FontSize="11" FontWeight="Bold" />
        <Button Content="Run" Height="23" HorizontalAlignment="Left" Margin="260,161,0,0" Name="buttonRun" VerticalAlignment="Top" Width="75" Click="buttonRun_Click" />
    </Grid>
</UserControl>    

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

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace AddHeader_Doc
{
    public partial class MainPage : UserControl
    {
        private SaveFileDialog saveFiledialog = new SaveFileDialog();
        private Document document = null;
        public MainPage()
        {
            InitializeComponent();
            this.saveFiledialog.Filter = "Word Document (*.doc)|*.doc";
            this.document = new Document();
        }

        private void buttonRun_Click(object sender, RoutedEventArgs e)
        {
           //add a header in document
            Section section = this.document.Sections[0];
            HeaderFooter header = section.HeadersFooters.Header;

            //draw the text of header
            Paragraph headerParagraph = section.Paragraphs[0];
            TextRange text = headerParagraph.AppendText("Demo of Spire.doc");

            //set the style of the text
            text.CharacterFormat.FontName = "Arial";
            text.CharacterFormat.FontSize = 10;
            text.CharacterFormat.Italic = true;
            headerParagraph.Format.HorizontalAlignment
                = Spire.Doc.Documents.HorizontalAlignment.Right;

            //draw the bottom line of header
            headerParagraph.Format.Borders.Bottom.BorderType
                = Spire.Doc.Documents.BorderStyle.Single;
            headerParagraph.Format.Borders.Bottom.Space = 0.05f;

            //save the document using the saveDiledialog
            bool? result = this.saveFiledialog.ShowDialog();
            if (result.HasValue && result.Value)
            {
                using (Stream stream = this.saveFiledialog.OpenFile())
                {
                    this.document.SaveToStream(stream, FileFormat.Doc);
                }
            }
        }

        private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {
            //load the sample2.doc file through stream
            Assembly assembly = this.GetType().Assembly;
            foreach (String name in assembly.GetManifestResourceNames())
            {
                if (name.EndsWith("sample2.doc"))
                {
                    using (Stream docStream = assembly.GetManifestResourceStream(name))
                    {
                        this.document = new Document(docStream, FileFormat.Doc);
                    }
                }
            }
        }
    }
}

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

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields

Namespace AddHeader_Doc
	Partial Public Class MainPage
		Inherits UserControl
		Private saveFiledialog As New SaveFileDialog()
		Private document As Document = Nothing
		Public Sub New()
			InitializeComponent()
			Me.saveFiledialog.Filter = "Word Document (*.doc)|*.doc"
			Me.document = New Document()
		End Sub

		Private Sub buttonRun_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
		   'add a header in document
			Dim section As Section = Me.document.Sections(0)
			Dim header As HeaderFooter = section.HeadersFooters.Header

			'draw the text of header
			Dim headerParagraph As Paragraph = section.Paragraphs(0)
			Dim text As TextRange = headerParagraph.AppendText("Demo of Spire.doc")

			'set the style of the text
			text.CharacterFormat.FontName = "Arial"
			text.CharacterFormat.FontSize = 10
			text.CharacterFormat.Italic = True
			headerParagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right

			'draw the bottom line of header
			headerParagraph.Format.Borders.Bottom.BorderType = Spire.Doc.Documents.BorderStyle.Single
			headerParagraph.Format.Borders.Bottom.Space = 0.05f

			'save the document using the saveDiledialog
			Dim result? As Boolean = Me.saveFiledialog.ShowDialog()
			If result.HasValue AndAlso result.Value Then
				Using stream As Stream = Me.saveFiledialog.OpenFile()
					Me.document.SaveToStream(stream, FileFormat.Doc)
				End Using
			End If
		End Sub

		Private Sub LayoutRoot_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
			'load the sample2.doc file through stream
			Dim [assembly] As System.Reflection.Assembly = Me.GetType().Assembly
			For Each name As String In [assembly].GetManifestResourceNames()
                If name.EndsWith("sample2.doc") Then
                    Using docStream As Stream = [assembly].GetManifestResourceStream(name)
                        Me.document = New Document(docStream, FileFormat.Doc)
                    End Using
                End If
			Next name
		End Sub
	End Class
End Namespace