Canalblog
Suivre ce blog Administration + Créer mon blog

SpireXLS

3 juillet 2012

With Silverlight-How to Insert TextBox in Word

Sometimes, people may insert a textbox in Word document in order to distinguish some additional information or note from body. People can change size of textbox or adjust location to make it to be presented more appropriately.

Textbox includes textbox and vertical textbox. In vertical textbox, text direction is assigned vertically. The vertical textbox is very useful if we want to add quote or sidebar in Word document.

In this post, I will introduce a method about how to insert textbox in Word with Silverlight. I will create a textbox in a blank document and add contents in it.

Also, the component, Spire.Doc for Silverlight is used for realizing this function more quickly and easily. So, if you want to use the following code, please DOWNLOAD and install it at first, and then add its dll file as reference in your project.

STEPS

Step 1. Design UserControl

Rename MainPage.xaml as InsertTextBox.xaml. Double click it and design UserControl. Add a label and a button in UserControl. Then, change label and button contents. Set format for the contents, including font style, size and color. Finally, set background color for UserControl.

Step 2. Declare SaveFileDialog

Declare a SaveFileDialog to save documents. And set a filter for it. The filter is used for users to choose format for documents. In this example, I set the format in filter as .docx only.

Step 3. Insert TextBox 

Create a new Word document and add a section in this document. Then, add a paragraph in this section. Insert textbox in paragraph by using paragraph.AppendTextBox() method. Two parameters passed to this method, box width and height.

Step 4. Set TextBox Format

Firstly, set textbox format, including fill color, line color, line width and line style.

Secondly, add contents in textbox and set format. Add a paragraph in textbox by using textbox.Body.AddParagraph() method. Then, append text in this paragraph. Finally, set font style and color for contents.

Step 5. Save Document

Judge if the SaveFileDialog which I declare in first step can pop up. If the result is true, save document which textbox has been inserted through this SaveFileDialog.

Full InsertTextbox.xaml.cs

using System.Windows;
using System.Windows.Controls;
using System.IO;
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
 
namespace WordTextBox
{
    public partial class MainPage : UserControl
    {
        private SaveFileDialog saveFiledialog = new SaveFileDialog();
        public MainPage()
        {
            InitializeComponent();
            this.saveFiledialog.Filter = "Word Document (*.docx)|*.docx";
        }
 
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //Create Document
            Document document = new Document();
            Section section = document.AddSection();
 
            //Insert TextBox
            Paragraph paragraph1 = section.AddParagraph();
            Spire.Doc.Fields.TextBox textBox = paragraph1.AppendTextBox(250, 150);
 
            //Set TextBox Format
            textBox.Format.FillColor = Color.LightSeaGreen;
            textBox.Format.LineColor = Color.RosyBrown;
            textBox.Format.LineWidth = 3.5F;
            textBox.Format.LineStyle = TextBoxLineStyle.ThickThin;
 
            //Add Contents in TextBox
            Paragraph paragraph2 = textBox.Body.AddParagraph();
            TextRange txtRange = paragraph2.AppendText("Insert TextBoxt in Word");
            txtRange.CharacterFormat.Font = new Font("Impact", 14F);
            txtRange.CharacterFormat.TextColor = Color.GhostWhite;
 
            //Save Document
            bool? result = this.saveFiledialog.ShowDialog();
            if (result.HasValue && result.Value)
            {
                using (Stream stream = this.saveFiledialog.OpenFile())
                {
                    document.SaveToStream(stream, FileFormat.Docx);
                }
            }
        }
     }

_______________________________________________________________________

Click Here to LEARN MORE about Spire.Doc for Silverlight

Spire.Office also can be used to realize this function

Publicité
Publicité
28 juin 2012

With Silverlight-How to Insert Text Watermark in Word

Because information is spread very quickly online, some people find that their documents are modified, even stolen by others. In order to protect copyright of document, people try to add watermark in document. In this post, I want to introduce the method to add watermark in Word with Silverlight.

Watermark can be text or image. Generally speaking, text often shows document properties, for example important, secret, while image can make document appearance more wonderful. In this example, I will add text watermark and watermark content is the title of document.

In order to realize this function more easily and quickly, I use a component, Spire.Doc for Silverlight in this example. If you want to use the following code, please DOWNLOAD and install it. Then, add its dll file as reference in your project.

STEPS

Step 1. Design UserControl

Rename MainPage.xaml as Watermark.xaml. Double click it to design UserControl. At first, add a label and change label content. Set format for content, including font style, size and color. Then, change UserControl background color. Finally, add a button to run.

Watermark.xaml

    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="232" d:DesignWidth="465" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

   

       

       

   

Step 2. Declare SaveFileDialog

Declare a new SaveFileDialog for saving Word document. Then, set filter for this SaveFileDialog. This filter is used to choose Word format (.doc or .docx). I set the format as .docx only for this filter.

        private SaveFileDialog saveFiledialog = new SaveFileDialog();

        public MainPage()

        {

            InitializeComponent();

            this.saveFiledialog.Filter = "Word Document (*.docx)|*.docx";

        }

Step 3. Load Document

Right click project to add existed item (Word document which I want to add watermark) and set this item’s Build Action as Embedded Resource. After that, double click run button and write code. Declare document and assembly. Use foreach sentence get name string from assembly. If the name is the same as embedded resource name, load it.

            Document document = new Document();
            Assembly assembly = this.GetType().Assembly;
            foreach (String name in assembly.GetManifestResourceNames())
            {
                if (name.EndsWith("Antarctic.docx"))
                {
                    using (Stream docStream=
assembly.GetManifestResourceStream(name))
                    {
                        document = new Document(docStream, FileFormat.Docx);
                    }
                }

            }

Step 4. Add Text Watermark

Declare a TextWatermark and set text, which is content, of TextWatermark as document title. Then, set format for text, including font name, size, color, watermark layout. Finally, assign this watermark as value of document's watermark.

            TextWatermark textWatermark = new TextWatermark();

            textWatermark.Text = "Antarctic";

            textWatermark.FontName = "Impact";

            textWatermark.FontSize=90;

            textWatermark.Color = Color.DarkOrange;

            textWatermark.Layout=WatermarkLayout.Diagonal;

            document.Watermark = textWatermark;

Step 5. Save Document

Judge if the SaveFileDialog which is declared in the first step can pop up. If so, save the document which has been added text watermark by using  SaveFileDialog.

            bool? result = this.saveFiledialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFiledialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

Full Watermark.xaml.cs

using System;

using System.Windows;

using System.Windows.Controls;

using System.Reflection;

using System.IO;

using System.Drawing;

using Spire.Doc;

using Spire.Doc.Documents;

 

namespace WordWatermark

{

    public partial class MainPage : UserControl

    {

        private SaveFileDialog saveFiledialog = new SaveFileDialog();

        public MainPage()

        {

            InitializeComponent();

            this.saveFiledialog.Filter = "Word Document (*.docx)|*.docx";

        }

 

        private void button1_Click(object sender, RoutedEventArgs e)

        {

            Document document = new Document();

            Assembly assembly = this.GetType().Assembly;

            foreach (String name in assembly.GetManifestResourceNames())

            {

                if (name.EndsWith("Antarctic.docx"))

                {

                    using (Stream docStream = assembly.GetManifestResourceStream(name))

                    {

                        document = new Document(docStream, FileFormat.Docx);

                    }

                }

            }

 

            TextWatermark textWatermark = new TextWatermark();

            textWatermark.Text = "Antarctic";

            textWatermark.FontName = "Impact";

            textWatermark.FontSize=90;

            textWatermark.Color = Color.DarkOrange;

            textWatermark.Layout=WatermarkLayout.Diagonal;

            document.Watermark = textWatermark;

 

            bool? result = this.saveFiledialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFiledialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

        }

    }

}

RESULT

 

______________________________________________________________________________

Click Here to LEARN MORE about Spire.Doc for Silverlight

Spire.Office also can be used to realize this function

 

27 juin 2012

With Silverlight-How to Replace Text in Word Document

It is possible that we may make some mistakes when writing something in Word, such as misspelling, catachresis and so on. We can correct mistakes directly, or use “Replace” function.

Replace function in Word is used to replace text or sentence with another one. Because of this function, it is very convenient for users to modify contents to make words or sentences to be used more correctly and appropriately. And it is very useful when we need to replace text which appears many times in document.

In this post, I want to introduce a method to replace text in Word with Silverlight. I prepare a document which is talking about New Zealand. I will change all “New Zealand” in this document as “NZ”.

Note: a component, Spire.Doc for Silverlight is used in this example. So, if you want to use the following code, please DOWNLOAD and install it. And then, add its dll file as reference in your project.

STEPS

Step 1. Design UserControl

Rename MainPage.xaml as Replace.xaml. Double click it to design UserControl. Firstly, add a label in UserControl and change content. Set format for content, including font style and size. Secondly, add a button to run. Change button background color and content font style. Thirdly, set background color for UserControl.

Replace.xaml

<UserControl x:Class="Replace.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="222" d:DesignWidth="487" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

 

    <Grid x:Name="LayoutRoot" Height="219" Width="486">

        <sdk:Label Height="31" HorizontalAlignment="Center" Margin="-4,58,0,116" Name="label1" VerticalAlignment="Center" Width="462" Content="Replace Text in Word with Silverlight" FontFamily="Times New Roman" FontSize="28" Foreground="AliceBlue" FontWeight="Bold" />

        <Button Content="RUN" Height="39" HorizontalAlignment="Center" Margin="239,154,187,26" Name="button1" VerticalAlignment="Center" Width="61" FontFamily="Arial" FontSize="14" FontWeight="Bold" Foreground="YellowGreen" Background="AliceBlue" Click="button1_Click" />

        <Grid.Background>

            <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">

                <GradientStop Color="Black" Offset="0" />

                <GradientStop Color="Cyan" Offset="1" />

                <GradientStop Color="#FF006262" Offset="0" />

            </LinearGradientBrush>

        </Grid.Background>

    </Grid>

</UserControl>

ReplaceBG

Step 2. Declare SaveFileDialog

Declare a SaveFileDialog for saving document. Then, set filter for this SaveFileDialog. Filter is used for people to choose format the document is, for example, .doc or .docx. In this example, I set the format as .docx only.

        private SaveFileDialog saveFiledialog = new SaveFileDialog();

        public MainPage()

        {

            InitializeComponent();

            this.saveFiledialog.Filter = "Word Document (*.docx)|*.docx";

        }

Step 3. Load Document

Right click project to add existed item which is the document which I want to replace text. After adding, click document and change its Build Action as Embedded Resource.

Double click run button to write code. Declare document and assembly. Use foreach sentence to get name string from assembly. If the name string is the same with document name, load this document.

            Document document = new Document();

            Assembly assembly = this.GetType().Assembly;

            foreach (String name in assembly.GetManifestResourceNames())

            {

                if (name.EndsWith("New Zealand.docx"))

                {

                    using (Stream docStream = assembly.GetManifestResourceStream(name))

                    {

                        document = new Document(docStream, FileFormat.Docx);

                    }

                }

            }

Step 4. Replace Text

Use document.Replace method to replace text. There are four parameters passed to this method, original string the document has, new string to replace original string, bool value to judge if casing sensitive, bool value to judge if replacing whole world.

            document.Replace("New Zealand", "NZ", true, true);

Step 5. Save Document

Save document through SaveFileDialog which I declare in the first step if it can pop up.

            bool? result = this.saveFiledialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFiledialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

Full Replace.xaml.cs

using System;

using System.Windows;

using System.Windows.Controls;

using System.Reflection;

using System.IO;

using Spire.Doc;

using Spire.Doc.Documents;

 

namespace Replace

{

    public partial class MainPage : UserControl

    {

        private SaveFileDialog saveFiledialog = new SaveFileDialog();

        public MainPage()

        {

            InitializeComponent();

            this.saveFiledialog.Filter = "Word Document (*.docx)|*.docx";

        }

 

        private void button1_Click(object sender, RoutedEventArgs e)

        {

            Document document = new Document();

            Assembly assembly = this.GetType().Assembly;

            foreach (String name in assembly.GetManifestResourceNames())

            {

                if (name.EndsWith("New Zealand.docx"))

                {

                    using (Stream docStream = assembly.GetManifestResourceStream(name))

                    {

                        document = new Document(docStream, FileFormat.Docx);

                    }

                }

            }

 

            document.Replace("New Zealand", "NZ", true, true);

 

            bool? result = this.saveFiledialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFiledialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

        }

    }

}

RESULT

Original Document

New zealand

Result Document

Nz

____________________________________________________________________

Click Here to LEARN MORE about Spire.Doc for Silverlight

Spire.Office also can be used to realize this function

 

25 juin 2012

With Silverlight-How to Find and Highlight Text in Word Document

Actually, it is a little difficult to find specified words or sentences from lots of contents. Therefore, Microsoft Word offers Find function to users. This function can help users find text quickly and save users time. The text which users want to find will be highlighted in order to confirm location.

In this post, I will introduce a method about how to find and highlight specified text in a Word document with Silverlight.

Note: a component, Spire.Doc for Silverlight is used in this example. If you want to use the following code, please download and install it at first and then add its dll file as reference in your project.

STEPS

Step 1. Design UserControl

Rename MainPage.xaml as Find.xaml and then double click it to design UserControl. Change background color and then add a label in UserControl. Change label contents which are about what I will do next. Set label background color and font style. Finally, add a button to run.

Find.xaml

<UserControlx:Class="FindandHighlight.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="184"d:DesignWidth="439"xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

 

    <Gridx:Name="LayoutRoot"Background="#FFFFB9EF"Height="179"Width="436">

        <sdk:LabelHeight="100"HorizontalAlignment="Center"Margin="0,-2,0,81"Name="label1"VerticalAlignment="Center"Width="436"Content="Find and Highlight Specified Text in Word "FontSize="22"FontFamily="Arial"Foreground="DarkCyan"Background="AliceBlue" />

        <ButtonContent="RUN"Height="37"HorizontalAlignment="Left"Margin="379,142,0,0"Name="button1"VerticalAlignment="Top"Width="58"Click="button1_Click" />

    </Grid>

</UserControl>

Step 2. Declare SaveFileDialog

Declare a SaveFileDialog to save document and set a filter for this SaveFileDialogue. This filter is used to choose Word format, for example, .doc or .docx. In this example, I set filter format as .docx only.

        private SaveFileDialog saveFiledialog = new SaveFileDialog();

        public MainPage()

        {

            InitializeComponent();

            this.saveFiledialog.Filter = "Word Document (*.docx)|*.docx";

        }

 

Step 3. Load Document

Right click project name and add existed item (Word document). After adding, click its name and change its Build Action as Embedded Resource.

Double click Run button to write code. Declare a document at the beginning and then load this document from assembly. Use foreach sentence to get document name. If the document is the same with embedded resource name, load this document.

            Document document = new Document();

            Assembly assembly = this.GetType().Assembly;

            foreach (String name in assembly.GetManifestResourceNames())

            {

                if (name.EndsWith("Blues Introduction.docx"))

                {

                    using (Stream docStream = assembly.GetManifestResourceStream(name))

                    {

                        document = new Document(docStream, FileFormat.Docx);

                    }

                }

            }

 

Step 4. Find Text

Use document.FindAllString() method to find document. Three parameters are passed to this method, text string, a bool value to define if casing sensitive, a bool value to define if highlighting whole word. Then save this string in a TextSelection array. Use foreach sentence to get each word in TextSelection and highlight.

            TextSelection[] textSelections = document.FindAllString("Blues", true, true);

            foreach (TextSelection selection in textSelections)

            {

                selection.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;

            }

 

Step 5. Save Document

Judge if the saveFileDialog which I declare at step 1 can pop up. If yes, save the encrypted document through it.

            bool? result = this.saveFiledialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFiledialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

 

Full WordTable.xaml.cs

usingSystem;

usingSystem.Windows;

usingSystem.Windows.Controls;

usingSystem.Reflection;

usingSystem.IO;

usingSystem.Drawing;

usingSpire.Doc;

usingSpire.Doc.Documents;

 

namespaceFindandHighlight

{

    public partial class MainPage : UserControl

    {

        private SaveFileDialog saveFiledialog = new SaveFileDialog();

        public MainPage()

        {

            InitializeComponent();

            this.saveFiledialog.Filter = "Word Document (*.docx)|*.docx";

        }

 

        private void button1_Click(object sender, RoutedEventArgs e)

        {

            Document document = new Document();

            Assembly assembly = this.GetType().Assembly;

            foreach (String name in assembly.GetManifestResourceNames())

            {

                if (name.EndsWith("Blues Introduction.docx"))

                {

                    using (Stream docStream = assembly.GetManifestResourceStream(name))

                    {

                        document = new Document(docStream, FileFormat.Docx);

                    }

                }

            }

 

            TextSelection[] textSelections = document.FindAllString("Blues", true, true);

            foreach (TextSelection selection in textSelections)

            {

                selection.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;

            }

 

            bool? result = this.saveFiledialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFiledialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }    

        }

    }

}

RESULT

__________________________________________________________________________________

Click Here to LEARN MORE about Spire.Doc for Silverlight

Spire.Office also can be used to realize this function

20 juin 2012

With Silverlight-How to Set Word Page in Word

Before printing one Word document, users need to set page for having a better layout. The process to set page is called page setup in Word. Page setup includes margins, page orientation, size etc. Generally speaking, users pay more attention on margin settings because contents may not printed completely if margins are not well set.

In this post, I will share my method about how to set Word page with Silverlight. I have prepared a Word document. Then, set its margins (top, bottom, right and left), page size and page orientation. The component, Spire.Doc for Silverlight is used in this example, so I have added its dll file in project at the beginning.

STEPS

Step 1. Design UserControl

Double click MainPage.xaml to design UserControl. Firstly, set background color for UserControl. Secondly, add a label. Change its content and then set label background and content text format. Thirdly, add a button to RUN and set format.

MainPage.xaml

<UserControlx:Class="SilverlightPageSetup.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="259"d:DesignWidth="401"xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"Background="WhiteSmoke">

 

    <Gridx:Name="LayoutRoot"Background="#FF1482DE"Height="257"Width="401">

        <sdk:LabelHeight="111"HorizontalAlignment="Center"Margin="-1,59,1,87"Name="label1"VerticalAlignment="Center"Width="401"Content="Set Word Page with Silverlight"FontFamily="Times New Roman"FontSize="30"Background="WhiteSmoke" />

        <ButtonContent="RUN"Height="37"HorizontalAlignment="Left"Margin="342,221,0,0"Name="button1"VerticalAlignment="Top"Width="59"FontFamily="Arial"FontSize="12"FontWeight="Bold"Background="White"Click="button1_Click" />

    </Grid>

</UserControl>

Step 2. Declare SaveFileDialog

Declare a saveFileDialog. Then, set filter for this saveFileDialog, which is the Word format (.doc or .docx) provided with others to choose. In this example, I set the filter format as .docx only.

        private SaveFileDialog saveFileDialog = null;

        public MainPage()

        {

            InitializeComponent();

            this.saveFileDialog = new SaveFileDialog();

            this.saveFileDialog.Filter = "Word Document(*.docx)|*.docx";

        }

Step 3. Load Document

Right click project to add existed item which is the document which I want to add comment. After adding, click this document to change its Build Action as Embedded Resource.

Double Click RUN button to write code. Declare a new document at the beginning. Next, use foreach sentence to get document name from assembly. If the name is the same with name of embedded resource, load the document.

            Document document = new Document();

            Assembly assembly = this.GetType().Assembly;

            foreach (String name in assembly.GetManifestResourceNames())

            {

                if (name.EndsWith("New Zealand.docx"))

                {

                    using (Stream docStream = assembly.GetManifestResourceStream(name))

                    {

                        document = new Document(docStream, FileFormat.Docx);

                    }

                }

            }

Step 4. Page Setup

Get the first section in Word document. Then, assign value for section.PageSetup.PageSize/Orientation/Margins. Page size is set as A4 and Orientation is set as LandScapge.

            Section section = document.Sections[0];

            section.PageSetup.PageSize = PageSize.A4;

            section.PageSetup.Orientation = PageOrientation.Landscape;

            section.PageSetup.Margins.Top = 55f;

            section.PageSetup.Margins.Bottom = 55f;

            section.PageSetup.Margins.Left = 70f;

            section.PageSetup.Margins.Right = 70f;

Step 5. Save Document

Judge if the saveFileDialog which I declare at step 1 can pop up. If yes, save the encrypted document through it.

            bool? result = this.saveFiledialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFiledialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

Full WordTable.xaml.cs

using System;

using System.Windows;

using System.Windows.Controls;

using System.IO;

using System.Reflection;

 

using Spire.Doc;

using Spire.Doc.Documents;

 

namespace SilverlightPageSetup

{

    public partial class MainPage : UserControl

    {

        private SaveFileDialog saveFiledialog = new SaveFileDialog();

        public MainPage()

        {

            InitializeComponent();

            this.saveFiledialog.Filter = "Word Document (*.docx)|*.docx";

        }

 

        private void button1_Click(object sender, RoutedEventArgs e)

        {

            Document document = new Document();

            Assembly assembly = this.GetType().Assembly;

            foreach (String name in assembly.GetManifestResourceNames())

            {

                if (name.EndsWith("New Zealand.docx"))

                {

                    using (Stream docStream = assembly.GetManifestResourceStream(name))

                    {

                        document = new Document(docStream, FileFormat.Docx);

                    }

                }

            }

 

            Section section = document.Sections[0];

 

            section.PageSetup.PageSize = PageSize.A4;

            section.PageSetup.Orientation = PageOrientation.Landscape;

            section.PageSetup.Margins.Top = 55f;

            section.PageSetup.Margins.Bottom = 55f;

            section.PageSetup.Margins.Left = 70f;

            section.PageSetup.Margins.Right = 70f;

 

            bool? result = this.saveFiledialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFiledialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

        }

    }

}

RESULT

______________________________________________________________________________________________

Click Here to LEARN MORE about Spire.Doc for Silverlight

Click Here to DOWNLOAD Spire.Doc for Silverlight

Spire.Office also can be used to realize this function

Publicité
Publicité
19 juin 2012

With Silverlight-How to Add Comment in Word

Comments can be taken as reviews or additional information for an article. On one hand, comments are used to present readers' thoughts about article and give suggestions to readers. On the other hand, comments show some information which is not the main content in article but very important. Microsoft Word offers one function to users to insert comment for some special sentences or text. And in this post, I will introduce the method about how to add comment in Word with Silverlight.

I prepare a Word document which is about Antarctic and I will insert a comment for the first paragraph. This comment presents the original source of contents in this document.

I use a component, Spire.Doc for Silverlight in this example. If you want to use the following code, please make sure that you have installed Silverlight 4 and Spire.Doc for Silverlight. What’s more, Spire.Doc for Silverlight dll file must be added as reference in project.

STEPS

Step 1. Design UserControl

Rename MainPage.xaml as InsertComment.xaml. Double click it to design UserControl. I set its background as an image at the beginning. Then, I add a label to and change the contents as what I will do next and set format for label contents. Finally, add a button to run.

InsertComment.xaml

<UserControlx:Class="WordComment.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="224"d:DesignWidth="419"xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

 

    <Gridx:Name="LayoutRoot"Height="219"Width="419">

        <Grid.Background>

            <ImageBrushImageSource="/WordComment;component/Images/CrystalTable1.jpg" />

        </Grid.Background>

        <sdk:LabelHeight="135"HorizontalAlignment="Center"Margin="12,12,6,72"Name="label1"VerticalAlignment="Center"Width="402"Content="Method to Insert Comments in Word"FontSize="24"FontFamily="Times New Roman"FontWeight="Bold" />

        <ButtonContent="RUN"Height="36"HorizontalAlignment="Left"Margin="180,154,0,0"Name="button1"VerticalAlignment="Top"Width="58"FontWeight="Bold"FontFamily="Comic Sans MS"FontSize="15"Click="button1_Click">

            <Button.Background>

                <ImageBrushImageSource="/WordComment;component/Images/silverlight.jpg" />

            </Button.Background>

        </Button>

    </Grid>

</UserControl>

Step 2. Declare SaveFileDialog

Declare a saveFileDialog for saving document. Also, set filter for this saveFileDialog, which is used to choose format. And I set the format as .docx.

        private SaveFileDialog saveFileDialog = null;

        public MainPage()

        {

            InitializeComponent();

            this.saveFileDialog = new SaveFileDialog();

            this.saveFileDialog.Filter = "Word Document(*.docx)|*.docx";

        }

Step 3. Load Document

Right click project to add existed item which is the document which I want to add comment. After adding, click this document to change its Build Action as Embedded Resource.

Double Click RUN button to write code. Declare a new document at the beginning. Next, use foreach sentence to get document name from assembly. If the name is the same with name of embedded resource, load the document.

            Document document = new Document();

            Assembly assembly = this.GetType().Assembly;

            foreach (String name in assembly.GetManifestResourceNames())

            {

                if (name.EndsWith("Antarctic.docx"))

                {

                    using (Stream docStream = assembly.GetManifestResourceStream(name))

                    {

                        document = new Document(docStream, FileFormat.Docx);

                    }

                }

            }

Step 4. Add Comment

Get section in document and get paragraph which I want to add comment in this section. Then, declare a string which is the comment contents, and use paragraph.AppendComment() method to add comment. The parameter passed to this method is string. Then, set comment author and initial.

            Section section = document.Sections[0];

            Paragraph paragraph = section.Paragraphs[1];

 

            string str = "All the contents in this document is from Wikipedia. If you want to learn more information about Antarctic, please visit http://en.wikipedia.org/wiki/Antarctic.";

            Comment comment = paragraph.AppendComment(str);

            comment.Format.Author = "Wikipedia";

            comment.Format.Initial = "C";

Step 5. Save Document

Judge if the saveFileDialog which I declare at step 1 can pop up. If yes, save the encrypted document through it.

            bool? result = this.saveFileDialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFileDialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

Full WordTable.xaml.cs

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 WordComment

{

    public partial class MainPage : UserControl

    {

        private SaveFileDialog saveFileDialog = null;

        public MainPage()

        {

            InitializeComponent();

            this.saveFileDialog = new SaveFileDialog();

            this.saveFileDialog.Filter = "Word Document(*.docx)|*.docx";

        }

 

        private void button1_Click(object sender, RoutedEventArgs e)

        {

            Document document = new Document();

            Assembly assembly = this.GetType().Assembly;

            foreach (String name in assembly.GetManifestResourceNames())

            {

                if (name.EndsWith("Antarctic.docx"))

                {

                    using (Stream docStream = assembly.GetManifestResourceStream(name))

                    {

                        document = new Document(docStream, FileFormat.Docx);

                    }

                }

            }

 

            Section section = document.Sections[0];

            Paragraph paragraph = section.Paragraphs[1];

 

            string str = "All the contents in this document is from Wikipedia. If you want to learn more information about Antarctic, please visit http://en.wikipedia.org/wiki/Antarctic.";

            Comment comment = paragraph.AppendComment(str);

            comment.Format.Author = "Wikipedia";

            comment.Format.Initial = "C";

 

            bool? result = this.saveFileDialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFileDialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

        }

    }

}

RESULT

______________________________________________________________________________________________

Click Here to LEARN MORE about Spire.Doc for Silverlight

Click Here to DOWNLOAD Spire.Doc for Silverlight

Spire.Office also can be used to realize this function

15 juin 2012

With Silverlight-How to Create Table in Word

Microsoft Word provides users with a function to insert table. Because table, users can present data information in Word more conveniently. Also, comparing with showing data with text, table can make reader learn data more clearly. In this post, I will share a method about how to create a table with data in Word with Silverlight.

Spire.Doc for Silverlight, a component specialized in operating Word document is used in this method. So, at the beginning, I have add its dll file as reference in project.

STEPS

Step 1. Design UserControl

Rename MainPage.xaml as WordTable.xaml. Double click it and then design UserControl. Set background as an image. Then, add a label. Change label content and set format for text, including font style and color. Finally, add a button to run.

WordTable.xaml

<UserControlx:Class="CreateTable.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"xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"d:DesignHeight="254"d:DesignWidth="415">

    <UserControl.Background>

        <ImageBrushStretch="None" />

    UserControl.Background>

    <Gridx:Name="LayoutRoot"Height="254"Width="412">

        <Grid.RowDefinitions>

            <RowDefinitionHeight="0*" />

            <RowDefinitionHeight="466*" />

        Grid.RowDefinitions>

        <Grid.Background>

            <ImageBrushImageSource="/CreateTable;component/Images/Table1.jpg" />

        Grid.Background>

        <sdk:LabelHeight="101"HorizontalAlignment="Center"Margin="-2,59,-2,94"Name="label1"VerticalAlignment="Center"Width="415"Content="Insert Table with Data in Word"FontSize="28"FontFamily="Times New Roman"FontWeight="Bold"Foreground="#FFD5E8D3"Grid.Row="1" />

        <ButtonContent="RUN"Height="39"HorizontalAlignment="Left"Margin="180,166,0,0"Name="button1"VerticalAlignment="Top"Width="63"Background="#FFFA58DC"Grid.Row="1"Click="button1_Click" />

    Grid>

UserControl>

Step 2. Declare saveFileDialog

Declare a saveFiledialog for saving Word document. Then, set filter for this saveFileDialog, which is used for choosing Word format (.doc or .docx). In this example, I just set the format as .docx.

        private SaveFileDialog saveFileDialog = null;

        public MainPage()

        {

            InitializeComponent();

            this.saveFileDialog = new SaveFileDialog();

            this.saveFileDialog.Filter = "Word Documents(*.docx)|*.docx";

        }

Step 3. Save Data

Declare a new Word document and add section in this document. Then, save header and body data in string arrays.

            Document document = new Document();

            Section section = document.AddSection();

 

            String[] header = { "Vendor No", "Vendor Name", "Address", "City", "State", "Zip" };

            String[][] data =

                {

                    new String[]{"3501","Cacor Corporation","161 Southfield Rd","Southfield","OH","60093"},

                    new String[]{"3502","Underwater""50 N 3rd Street","Indianapolis","IN","46208"},

                    new String[]{"3503","J.W.  Luscher Mfg.","65 Addams Street","Berkely","MA","02779"},

                    new String[]{"3504","Scuba Professionals","3105 East Brace","Rancho Dominguez","CA","90221"},

                    new String[]{"3505","Divers'  Supply Shop","5208 University Dr","Macon","GA","20865"},

                    new String[]{"3506","Techniques","52 Dolphin Drive","Redwood City","CA","94065-1086"},

                    new String[]{"3507","Perry Scuba","3443 James Ave","Hapeville","GA","30354"},

                    new String[]{"3508","Beauchat, Inc.","45900 SW 2nd Ave","Ft Lauderdale","FL","33315"},

                    new String[]{"3509","Amor Aqua","42 West 29th Street","New York","NY","10011"},

                    new String[]{"3510","Aqua Research Corp.","P.O. Box 998","Cornish","NH","03745"},

                    new String[]{"3511","B&K Undersea Photo","116 W 7th Street","New York","NY","10011"},

                    new String[]{"3512","Diving International Unlimited","1148 David Drive","San Diego","DA","92102"},

                    new String[]{"3513","Nautical Compressors","65 NW 167 Street","Miami","FL","33015"},

                    new String[]{"3514","Glen Specialties, Inc.","17663 Campbell Lane","Huntington Beach","CA","92647"},

                };

Step 3. Create Table

Add table in this section and then use table.ResetCells() method to confirm data row and column number.

            Table table = section.AddTable();

            table.ResetCells(data.Length + 1, header.Length);

Step 4. Set Header and Data Format

Set the first row as header row and then set its row height and background color. Use for loop to get header data information and set font style, color and alignment. Then, use for loop to get body data rows and set format and in this for loop, use another for loop to set data information format. Finally, set border style for whole table.

            TableRow row = table.Rows[0];

            row.IsHeader = true;

            row.Height = 20;

            row.HeightType = TableRowHeightType.Exactly;

            row.RowFormat.BackColor = Color.LimeGreen;

            for (int i = 0; i < header.Length; i++)

            {

                row.Cells[i].CellFormat.VerticalAlignment = Spire.Doc.Documents.VerticalAlignment.Middle;

                Paragraph p = row.Cells[i].AddParagraph();

                p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;

                TextRange txtRange = p.AppendText(header[i]);

                txtRange.CharacterFormat.Bold = true;

                txtRange.CharacterFormat.TextColor = Color.WhiteSmoke;

            }

            for (int r = 0; r < data.Length; r++)

            {

                TableRow dataRow = table.Rows[r + 1];

                dataRow.Height = 20;

                dataRow.HeightType = TableRowHeightType.Exactly;

                dataRow.RowFormat.BackColor = Color.AliceBlue;

                for (int c = 0; c < data[r].Length; c++)

                {

                    dataRow.Cells[c].CellFormat.VerticalAlignment = Spire.Doc.Documents.VerticalAlignment.Middle;

                    dataRow.Cells[c].AddParagraph().AppendText(data[r][c]);

                }

            }

Step 5. Save Document

Judge if the saveFileDialog which I declare at step 1 can pop up. If yes, save the encrypted document through it.

            bool? result = this.saveFileDialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFileDialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

Full WordTable.xaml.cs

using System;

using System.Windows;

using System.Windows.Controls;

using System.Drawing;

using System.IO;

using Spire.Doc;

using Spire.Doc.Documents;

using Spire.Doc.Fields;

 

namespace CreateTable

{

    public partial class MainPage : UserControl

    {

        private SaveFileDialog saveFileDialog = null;

        public MainPage()

        {

            InitializeComponent();

            this.saveFileDialog = new SaveFileDialog();

            this.saveFileDialog.Filter = "Word Documents(*.docx)|*.docx";

        }

 

        private void button1_Click(object sender, RoutedEventArgs e)

        {

            Document document = new Document();

            Section section = document.AddSection();

 

            String[] header = { "Vendor No", "Vendor Name", "Address", "City", "State", "Zip" };

            String[][] data =

                {

                    new String[]{"3501","Cacor Corporation","161 Southfield Rd","Southfield","OH","60093"},

                    new String[]{"3502","Underwater""50 N 3rd Street","Indianapolis","IN","46208"},

                    new String[]{"3503","J.W.  Luscher Mfg.","65 Addams Street","Berkely","MA","02779"},

                    new String[]{"3504","Scuba Professionals","3105 East Brace","Rancho Dominguez","CA","90221"},

                    new String[]{"3505","Divers'  Supply Shop","5208 University Dr","Macon","GA","20865"},

                    new String[]{"3506","Techniques","52 Dolphin Drive","Redwood City","CA","94065-1086"},

                    new String[]{"3507","Perry Scuba","3443 James Ave","Hapeville","GA","30354"},

                    new String[]{"3508","Beauchat, Inc.","45900 SW 2nd Ave","Ft Lauderdale","FL","33315"},

                    new String[]{"3509","Amor Aqua","42 West 29th Street","New York","NY","10011"},

                    new String[]{"3510","Aqua Research Corp.","P.O. Box 998","Cornish","NH","03745"},

                    new String[]{"3511","B&K Undersea Photo","116 W 7th Street","New York","NY","10011"},

                    new String[]{"3512","Diving International Unlimited","1148 David Drive","San Diego","DA","92102"},

                    new String[]{"3513","Nautical Compressors","65 NW 167 Street","Miami","FL","33015"},

                    new String[]{"3514","Glen Specialties, Inc.","17663 Campbell Lane","Huntington Beach","CA","92647"},

                };

 

            Table table = section.AddTable();

            table.ResetCells(data.Length + 1, header.Length);

 

            TableRow row = table.Rows[0];

            row.IsHeader = true;

            row.Height = 20;

            row.HeightType = TableRowHeightType.Exactly;

            row.RowFormat.BackColor = Color.LimeGreen;

            for (int i = 0; i < header.Length; i++)

            {

                row.Cells[i].CellFormat.VerticalAlignment = Spire.Doc.Documents.VerticalAlignment.Middle;

                Paragraph p = row.Cells[i].AddParagraph();

                p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;

                TextRange txtRange = p.AppendText(header[i]);

                txtRange.CharacterFormat.Bold = true;

                txtRange.CharacterFormat.TextColor = Color.WhiteSmoke;

            }

 

            for (int r = 0; r < data.Length; r++)

            {

                TableRow dataRow = table.Rows[r + 1];

                dataRow.Height = 20;

                dataRow.HeightType = TableRowHeightType.Exactly;

                dataRow.RowFormat.BackColor = Color.AliceBlue;

                for (int c = 0; c < data[r].Length; c++)

                {

                    dataRow.Cells[c].CellFormat.VerticalAlignment = Spire.Doc.Documents.VerticalAlignment.Middle;

                    dataRow.Cells[c].AddParagraph().AppendText(data[r][c]);

                }

            }

 

            table.TableFormat.Borders.BorderType = BorderStyle.Thick;

 

            bool? result = this.saveFileDialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFileDialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

        }

    }

}

RESULT

_______________________________________________________________________________

Click Here to LEARN MORE about Spire.Doc for Silverlight

Click Here to DOWNLOAD Spire.Doc for Silverlight

Spire.Office also can be used to realize this function

12 juin 2012

With Silverlight-How to Encrypt Word

Because of the sharp development of internet, information can be spread very quickly. However, some people find that their documents which are submitted online are stolen or modified by others. Therefore, it is very important to protect electronic documents.

Actually, there are several methods to protect a document. Some people encrypt document directly by setting a password. If so, others cannot view document contents unless they have the correct password. Some others just set permissions for document. For example, readers can view and print document but cannot edit.

In this post, I will introduce a method about how to encrypt Word document with Silverlight. I will set a password for one existed document. If you want to view it, you must enter the password.

Note: component, Spire.Doc for Silverlight is used in this example. So I have added its dll file as reference in project.

STEPS

Step 1. Design UserControl

Rename MainPage.xaml as Encryption.xaml. Then, double click it to design UserControl. I change background color at first. Next, add a label to show what I will do. Set label background color and set text format. Finally, add a button to run.

Encryption.xaml

<UserControlx:Class="EncryptWord.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="239"d:DesignWidth="448"xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

    <UserControl.Background>

        <LinearGradientBrushEndPoint="1,0.5"StartPoint="0,0.5">

            <GradientStopColor="Black"Offset="0" />

            <GradientStopColor="#FFD413D4"Offset="1" />

        </LinearGradientBrush>

    </UserControl.Background>

    <Gridx:Name="LayoutRoot"Background="#FFA810B7">

        <sdk:LabelHeight="87"HorizontalAlignment="Center"Margin="57,58,53,91"Name="label1"VerticalAlignment="Center"Width="331"Content="Encrypt Word with Password"FontSize="26"FontFamily="Times New Roman"Background="White" />

        <ButtonContent="RUN"Height="39"HorizontalAlignment="Left"Margin="365,173,0,0"Name="button1"VerticalAlignment="Top"Width="57"Click="button1_Click" />

    </Grid>

</UserControl>

Step 2. Declare saveFileDialog

Declare a saveFiledialog for saving Word document. Then, set filter for this saveFileDialog, which is used for choosing Word format (.doc or .docx). In this example, I just set the format as .docx.

        private SaveFileDialog saveFiledialog = new SaveFileDialog();

        public MainPage()

        {

            InitializeComponent();

            this.saveFiledialog.Filter = "Word Document (*.docx)|*.docx";

        }

Step 3. Load Document

Right click project name to add existed item which is the Word document I want to encrypt. After adding, find the document and click it. Change its Build Action as Embedded Resource.

Double click run button to write code. Declare a document at the beginning. Then, get embedded resource from assembly and load it.

            Document document = new Document();

            Assembly assembly = this.GetType().Assembly;

            foreach (String name in assembly.GetManifestResourceNames())

            {

                if (name.EndsWith("Student Transcript.docx"))

                {

                    using (Stream docStream = assembly.GetManifestResourceStream(name))

                    {

                        document = new Document(docStream, FileFormat.Docx);

                    }

                }

Step 4. Encrypt and Save Document

Use document.Encrypt() method to encrypt this document. The parameter passed to this method is password string.

Then, judge if the saveFileDialog which I declare at step 1 can pop up. If yes, save the encrypted document through it.

            document.Encrypt("123456789");

 

            bool? result = this.saveFiledialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFiledialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

        }

Full Encryption.xaml.cs

using System;

using System.Windows;

using System.Windows.Controls;

using System.Reflection;

using System.IO;

using Spire.Doc;

 

namespace EncryptWord

{

    public partial class MainPage : UserControl

    {

        private SaveFileDialog saveFiledialog = new SaveFileDialog();

        public MainPage()

        {

            InitializeComponent();

            this.saveFiledialog.Filter = "Word Document (*.docx)|*.docx";

        }

 

        private void button1_Click(object sender, RoutedEventArgs e)

        {

            Document document = new Document();

            Assembly assembly = this.GetType().Assembly;

            foreach (String name in assembly.GetManifestResourceNames())

            {

                if (name.EndsWith("Student Transcript.docx"))

                {

                    using (Stream docStream = assembly.GetManifestResourceStream(name))

                    {

                        document = new Document(docStream, FileFormat.Docx);

                    }

                }

            }

 

            document.Encrypt("123456789");

 

            bool? result = this.saveFiledialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFiledialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

        }

    }

RESULT

______________________________________________________________________

Click Here to LEARN MORE about Spire.Doc for Silverlight

Click Here to DOWNLOAD Spire.Doc for Silverlight

Spire.Office also can be used to realize this function

11 juin 2012

With Silverlight-How to Add Header in Word

Header, similar to footer, is used to show some additional information about document. Its contents can be same with footer, for example, document title, page number etc. However, if one document includes both header and footer, the contents will be different. In this post, I will show the method to add header in Word with Silverlight.

At the beginning, I have prepared a Word document. I will add a header for it to present document title and set format for this header. Also, the component, Spire.Doc for Silverlight is used in this example to realize this function more quickly and easily.

STEPS:

Step 1. Design User Control

Rename MainPage.xaml as WordHeader.xaml and double click it to design UserControl. Set background as an image and then add a label to show what I will do. Also, set format for label contents. Finally, add a button to run.

WordHeader.xaml

<UserControlx:Class="DrawHeader.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="349"d:DesignWidth="474"xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

 

    <Gridx:Name="LayoutRoot"Height="350"Width="469">

        <Grid.Background>

            <ImageBrushImageSource="/DrawHeader;component/Images/Technology%20City.jpg" />

        </Grid.Background>

        <sdk:LabelHeight="73"HorizontalAlignment="Center"Margin="20,84,21,193"Name="label1"VerticalAlignment="Center"Width="428"Content="Draw Header in Word"FontSize="36"FontFamily="Arial Black"Foreground="#FF00E100"></sdk:Label>

        <ButtonContent="RUN"Height="36"HorizontalAlignment="Left"Margin="385,263,0,0"Name="button1"VerticalAlignment="Top"Width="58"FontWeight="Bold"Background="#FFF8FCFF"Click="button1_Click" />

    </Grid>

</UserControl>

Step 2. Declare saveFileDialog

Declare a saveFileDialog for saving Word document. Also, set saveFileDialog filter to set which kind of format to choose. In this example, I set it as .docx.

        private SaveFileDialog saveFiledialog = new SaveFileDialog();

        public MainPage()

        {

            InitializeComponent();

            this.saveFiledialog.Filter = "Word Document (*.docx)|*.docx";

        }

Step 3. Load Document

Firstly, right click project name to add existed item (Word document I prepared). After adding, click this document and change its Build Action as Embedded Resource.

Secondly, double click run button to write code. Declare a new document at the beginning. Then, judge if the document name in assembly is the same as embedded resource name. If so, get this document.

            Document document = new Document();

            Assembly assembly = this.GetType().Assembly;

            foreach (String name in assembly.GetManifestResourceNames())

            {

                if (name.EndsWith("welcome.docx"))

                {

                    using (Stream docStream = assembly.GetManifestResourceStream(name))

                    {

                        document = new Document(docStream, FileFormat.Docx);

                    }

                }

            }

 

Step 3. Add Header

Get section in this loaded document and then add header in this section. Next, add a header paragraph to add text which presents header contents.

            Section section = document.Sections[0];

            HeaderFooter header = section.HeadersFooters.Header;

 

            Paragraph headerParagraph = header.AddParagraph();

            TextRange text = headerParagraph.AppendText("Welcome to Our Town");

In order to make the header more wonderful, set format for header text, including font style, color and alignment.

            text.CharacterFormat.FontName = "Arial Narrow";

            text.CharacterFormat.FontSize = 12;

            text.CharacterFormat.Italic= true;

            text.CharacterFormat.TextColor = Color.DarkSlateGray;

            headerParagraph.Format.HorizontalAlignment

                = Spire.Doc.Documents.HorizontalAlignment.Right;

Also, add a border to separate header and document body and set border format.

            headerParagraph.Format.Borders.Bottom.BorderType

                = Spire.Doc.Documents.BorderStyle.ThickThinMediumGap;

            headerParagraph.Format.Borders.Bottom.Space = 0.05f;

            headerParagraph.Format.Borders.Bottom.Color = Color.AliceBlue;

Step 4. Save File

Judge if the saveFileDialog which I declare in the first step can pop up. If yes, save the Word document with header through it.

            bool? result = this.saveFiledialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFiledialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

Full Footer.xaml.cs

using System;

using System.Windows;

using System.Windows.Controls;

using System.Reflection;

using System.IO;

using System.Drawing;

 

using Spire.Doc;

using Spire.Doc.Documents;

using Spire.Doc.Fields;

 

namespace DrawHeader

{

    public partial class MainPage : UserControl

    {

        private SaveFileDialog saveFiledialog = new SaveFileDialog();

        public MainPage()

        {

            InitializeComponent();

            this.saveFiledialog.Filter = "Word Document (*.docx)|*.docx";

        }

 

        private void button1_Click(object sender, RoutedEventArgs e)

        {

            Document document = new Document();

            Assembly assembly = this.GetType().Assembly;

            foreach (String name in assembly.GetManifestResourceNames())

            {

                if (name.EndsWith("welcome.docx"))

                {

                    using (Stream docStream = assembly.GetManifestResourceStream(name))

                    {

                        document = new Document(docStream, FileFormat.Docx);

                    }

                }

            }

 

            Section section = document.Sections[0];

            HeaderFooter header = section.HeadersFooters.Header;

 

            Paragraph headerParagraph = header.AddParagraph();

            TextRange text = headerParagraph.AppendText("Welcome to Our Town");

 

            text.CharacterFormat.FontName = "Arial Narrow";

            text.CharacterFormat.FontSize = 12;

            text.CharacterFormat.Italic= true;

            text.CharacterFormat.TextColor = Color.DarkSlateGray;

            headerParagraph.Format.HorizontalAlignment

                = Spire.Doc.Documents.HorizontalAlignment.Right;

 

            headerParagraph.Format.Borders.Bottom.BorderType

                = Spire.Doc.Documents.BorderStyle.ThickThinMediumGap;

            headerParagraph.Format.Borders.Bottom.Space = 0.05f;

            headerParagraph.Format.Borders.Bottom.Color = Color.AliceBlue;

 

            bool? result = this.saveFiledialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFiledialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

        }

    }

}

RESULT

_____________________________________________________________

Click Here to LEARN MORE about Spire.Doc for Silverlight

Click Here to DOWNLOAD Spire.Doc for Silverlight

Spire.Office also can be used to realize this function

7 juin 2012

With Silverlight-How to Add Footer for Word Document

Footer, often added on the bottom of one Word page, shows additional information about document. The information can be document title, company name, author name, page number etc. Besides text, footer can be image as well, such as company logo, stamp and so on.

In this post, I will share my method about how to add footer in Word document with Silverlight. I will create a new Word document and then add footer for it. The footer is text and will be formatted.

STEPS:

Step 1. Design User Control

Rename MainPage.xaml as Footer.xaml. Double click Footer.xaml to design UserControl. At the beginning, judge size. Add a label and change its contents as “Draw Footer in Word”. Then, set text font style and color. Next, add a button to run. Finally, set UserControl background as image.

Footer.xaml

<UserControlx:Class="WordFooter.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="265"d:DesignWidth="428"xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

 

    <Gridx:Name="LayoutRoot"Height="265"Width="428">

        <ButtonContent="RUN"Height="36"HorizontalAlignment="Left"Margin="189,188,0,0"Name="button1"VerticalAlignment="Top"Width="72"FontWeight="Bold"Background="#FF1CF347"Click="button1_Click">

            <Button.BorderBrush>

                <LinearGradientBrush>

                    <GradientStopColor="#FFA3AEB9"Offset="0" />

                    <GradientStopColor="#FF8399A9"Offset="0.375" />

                    <GradientStopColor="#FF718597"Offset="0.375" />

                    <GradientStopColor="#FF087BD0"Offset="1" />

                </LinearGradientBrush>

            </Button.BorderBrush>

        </Button>

        <sdk:LabelHeight="130"HorizontalAlignment="Center"Margin="24,33,28,102"Name="label1"VerticalAlignment="Center"Width="375"Content="Draw Footer in Word"FontSize="30"FontFamily="Arial Black">

            <sdk:Label.Foreground>

                <LinearGradientBrushEndPoint="1,0.5"StartPoint="0,0.5">

                    <GradientStopColor="Black"Offset="0" />

                    <GradientStopColor="#FFE6FFFF"Offset="0.008" />

                </LinearGradientBrush>

            </sdk:Label.Foreground>

        </sdk:Label>

        <Grid.Background>

            <ImageBrushImageSource="/WordFooter;component/Images/BG.jpg" />

        </Grid.Background>

    </Grid>

</UserControl>

Step 2. Declare saveFileDialog

Declare a saveFileDialog for save Word document. Then, set filter for this saveFileDialog. In this example, I set filter format as .docx.

        private SaveFileDialog saveFiledialog = new SaveFileDialog();

        public MainPage()

        {

            InitializeComponent();

            this.saveFiledialog.Filter = "Word Document (*.docx)|*.docx";

        }

Step 3. Add Footer

Declare a new word document. Then, add a section in this document. Next, add footer in this section.

            Document document = new Document();

            Section section = document.AddSection();

            HeaderFooter footer = section.HeadersFooters.Footer;

Create a footer paragraph, append text for this paragraph. The text is footer content. Then, set format for footer content, including font style, color and alignment.

            Paragraph footerParagraph = footer.AddParagraph();

            TextRange text = footerParagraph.AppendText("Word Footer");

 

            text.CharacterFormat.FontName = "Calibri";

            text.CharacterFormat.FontSize = 14;

            text.CharacterFormat.TextColor = Color.DarkOrange;

            text.CharacterFormat.Bold = true;

            text.CharacterFormat.Italic = true;

            footerParagraph.Format.HorizontalAlignment

                = Spire.Doc.Documents.HorizontalAlignment.Right;

In order to separate footer from document contents, add top border for footer. Then, set border style and color.

            footerParagraph.Format.Borders.Top.BorderType

                = Spire.Doc.Documents.BorderStyle.ThinThinSmallGap;

            footerParagraph.Format.Borders.Top.Space = 0.15f;

            footerParagraph.Format.Borders.Color = Color.CadetBlue;

Step 4. Save File

Judge if the saveFileDialog which is declared in step 1 can pop up. If so, save document which image is inserted in through it.

            bool? result = this.saveFiledialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFiledialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

Full Footer.xaml.cs

usingSystem.Windows;

usingSystem.Windows.Controls;

usingSystem.IO;

usingSystem.Drawing;

 

usingSpire.Doc;

usingSpire.Doc.Documents;

usingSpire.Doc.Fields;

 

 

namespaceWordFooter

{

    public partial class MainPage : UserControl

    {

        private SaveFileDialog saveFiledialog = new SaveFileDialog();

        public MainPage()

        {

            InitializeComponent();

            this.saveFiledialog.Filter = "Word Document (*.docx)|*.docx";

        }

 

        private void button1_Click(object sender, RoutedEventArgs e)

        {

            Document document = new Document();

            Section section = document.AddSection();

            HeaderFooter footer = section.HeadersFooters.Footer;

 

            Paragraph footerParagraph = footer.AddParagraph();

            TextRange text = footerParagraph.AppendText("Word Footer");

 

            text.CharacterFormat.FontName = "Calibri";

            text.CharacterFormat.FontSize = 14;

            text.CharacterFormat.TextColor = Color.DarkOrange;

            text.CharacterFormat.Bold = true;

            text.CharacterFormat.Italic = true;

            footerParagraph.Format.HorizontalAlignment

                = Spire.Doc.Documents.HorizontalAlignment.Right;

 

            footerParagraph.Format.Borders.Top.BorderType

                = Spire.Doc.Documents.BorderStyle.ThinThinSmallGap;

            footerParagraph.Format.Borders.Top.Space = 0.15f;

            footerParagraph.Format.Borders.Color = Color.CadetBlue;

 

            bool? result = this.saveFiledialog.ShowDialog();

            if (result.HasValue && result.Value)

            {

                using (Stream stream = this.saveFiledialog.OpenFile())

                {

                    document.SaveToStream(stream, FileFormat.Docx);

                }

            }

        }

    }

}

RESULT

________________________________________________________

Click Here to LEARN MORE about Spire.Doc for Silverlight

Click Here to DOWNLOAD Spire.Doc for Silverlight

Spire.Office also can be used to realize this function

Publicité
Publicité
1 2 3 4 5 6 > >>
SpireXLS
Publicité
Publicité