Program Guide for WPF

Program Guide for WPF (24)

With the help of Spire.Doc for WPF, developers can create and edit word documents easily and flexibly for their WPF applications. Sometimes developers need to protect their word documents for being read and edit by others. They may need to add password for the word files to protect them confidential. Then others have to enter the password to open the view the encrypted word documents. Spire.Doc for WPF offers a method of Document.Encrypt(); to enable developers to set the password for word documents and Document.RemoveEncryption(); to remove the encryption for word documents.

This article will demonstrate how to encrypt and word documents with password and decrypt the word documents in C# for WPF applications.

Note: Before Start, please download the latest version of Spire.Doc and add Spire.Doc.Wpf.dll in the bin folder as the reference of Visual Studio.

Here comes to the code snippets:

Step 1: Create a new word document and load the document from file.

Document document = new Document();
document.LoadFromFile("Sample.docx");

Step 2: Encrypt the document with password.

document.Encrypt("eiceblue");

Step 3: Save the encrypted document to file.

document.SaveToFile("Encryption.docx", FileFormat.Docx);

Step 4: Create a second new word document and load the encrypted document from file with the password.

Document document2 = new Document();
document2.LoadFromFile("Encryption.docx",FileFormat.Docx,"eiceblue");

Step 5: Decrypted the word document.

document2.RemoveEncryption();

Step 6: Save the decrypted document to file.

document2.SaveToFile("Decrytion.docx", FileFormat.Docx);

Please check the effective screenshots of the encrypted word document and the decrypted word documents as below:

Encrypted document with password:

Encrypt and decrypt word document for WPF applications

Decrypted word document:

Encrypt and decrypt word document for WPF applications

Full codes:

using Spire.Doc;
using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Document document = new Document();
            document.LoadFromFile("Sample.docx");

            document.Encrypt("eiceblue");

            document.SaveToFile("Encryption.docx", FileFormat.Docx);

            Document document2 = new Document();
            document2.LoadFromFile("Encryption.docx", FileFormat.Docx, "eiceblue");
            document2.RemoveEncryption();

            document2.SaveToFile("Decrytion.docx", FileFormat.Docx);

        }
    }
}

Spire.Doc for WPF Program Guide Content

2016-01-12 01:40:48 Written by Koohji

Spire.Doc, specially designed for developers/programmers to manipulate word proceeding tasks, from Word version 97-2003 to 2010 and 2013 in .NET, Silverlight and WPF Platform, always welcomes any kind of evaluation or test from either organizations or individuals with no charges.

This professional word component enables users to perform a large range of tasks on Word, as document operation (create, open, edit and save), mail merge, security, format (font, paragraph and page settings), objects (text, image, hyperlink, comment, table, bookmark, header/footer, footnote/endnote etc.). The conversion feature stands out of the peers, which enables developers to realize conversion between most popular formats with high fidelity, including Word to PDF, HTML, RTF, XML, Image formats, TEXT and RTF, XML and HTML files also can be converted to Word back. The following sections have been well-organized to show you how these functions work in detail.

Mail Merge

Others

Convert Word to Image in WPF

2014-10-31 06:13:46 Written by Koohji

In some circumstances, we may need to convert or save Word documents as pictures. For one reason, a picture is difficult to edit; for another, compared with Word, pictures are much easier to be published for browsing. This article is aimed to explore how we can convert .doc/.docx to popular image formats such as Jpg, Png, Gif and Bmp in WPF using Spire.Doc.

Spire.Doc for WPF, as a professional Word component, provides a plenty of useful methods to manipulate Word documents in your WPF applications. Using Spire.Doc, developers are able to export Word documents as images with high quality. Here comes the method:

Step 1: Create a new project by choosing WPF Application in Visual Studio, add a button in MainWindow, double click the button to write code.

public partial class MainWindow : Window
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

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

Step 2: Initialize a new instance of Spire.Doc.Document class and load the sample Word file.

       Document doc = new Document("sample.docx", FileFormat.Docx2010);

Step 3: To convert Word to image in WPF, we need firstly save Word as BitmapSource by calling the method Document.SaveAsImage(ImageType type), then convert BitmapSource to Bitmap, then save the Bitmap as image with a specified format using Image.Save(). Here, I saved Bitmap as .Png.

       BitmapSource[] bss = doc.SaveToImages(ImageType.Bitmap);
            for (int i = 0; i < bss.Length; i++)
            {
                SourceToBitmap(bss[i]).Save(string.Format("img-{0}.png", i));
            }
        }

        private Bitmap SourceToBitmap(BitmapSource source)
        {        

            Bitmap bmp;
            using (MemoryStream ms = new MemoryStream())
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(source));
                encoder.Save(ms);
                bmp = new Bitmap(ms);
            }
            return bmp;
        }

Output of the first page:

Convert Word to Image in WPF

Entire Code:

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

namespace Word2Image
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Document doc = new Document("sample.docx", FileFormat.Docx2010);
            BitmapSource[] bss = doc.SaveToImages(ImageType.Bitmap);
            for (int i = 0; i < bss.Length; i++)
            {
                SourceToBitmap(bss[i]).Save(string.Format("img-{0}.png", i));
            }
        }

        private Bitmap SourceToBitmap(BitmapSource source)
        {        

            Bitmap bmp;
            using (MemoryStream ms = new MemoryStream())
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(source));
                encoder.Save(ms);
                bmp = new Bitmap(ms);
            }
            return bmp;
        }
    }
}

Convert RTF to HTML in WPF

2012-10-15 07:24:19 Written by Koohji

This section will show you a detail solution to easily convert RTF to HTML in your WPF application via a .NET Word component. Only two lines of core code in total will be used to realize your RTF to HTML task in this solution.

Spire.Doc for WPF, as a professional MS Word component on WPF, enables you to accomplish RTF to HTML task through following two methods: Document.LoadFromFile(string fileName, FileFormat fileFormat) called to load your RTF file from system and Document. SaveToFile(string ilename, FileFormat fileFormat) is used to save the RTF file as HTML.

Now, you can download Spire.Doc for WPF and then, view the effect of RTF to HTML task as below picture:

RTF to HTML

Sample Code:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;

namespace wpfrtftohtml
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //Load RTF file
            Document document = new Document();
            document.LoadFromFile(@"..\wpfrtftohtml.rtf", FileFormat.Rtf);
            //Convert rtf to html
            document.SaveToFile("rtftohtml.html", FileFormat.Html);
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace wpfrtftohtml
    
    Public Class MainWindow
        Inherits Window
        Public Sub New()
            MyBase.New
            InitializeComponent
        End Sub
        
        Private Sub button1_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
            'Load RTF file
            Dim document As Document = New Document
            document.LoadFromFile("..\wpfrtftohtml.rtf", FileFormat.Rtf)
            'Convert rtf to html
            document.SaveToFile("rtftohtml.html", FileFormat.Html)
        End Sub
    End Class
End Namespace

Insert Image in Word Document in WPF

2012-08-30 03:30:44 Written by Koohji

Word Image can make one document more interesting and impressive. Sometimes, image can be used explain contents. For example, if one document focuses on describing appearance one kind of birds, readers can learn more clearly with a bird picture.

Spire.Doc for WPF, a professional component to manipulate Word documents with WPF, enables users to insert image in Word with WPF. And this guide will show a method about how to insert image Word in WPF quickly.

Users can invoke paragraph.AppendPicture(image) method to insert image in Word directly. If you want to set image height/width to make picture display appropriately in document, you can use Height and Width property provided by DocPicture class which Spire.Doc for .NET offers. Below, there is the result after inserting image in Word.

Insert Word Image

Download and install Spire.Doc for WPF. Then, add a button in MainWindow. Double click this button and use the following code to insert image in Word.

Code Sample:

[C#]
          //Create Document
            Document document = new Document();
            Section section = document.AddSection();
            Paragraph Imageparagraph = section.AddParagraph();

            //Insert Image
            Image image = Image.FromFile(@"E:\work\Documents\Image\street.jpg");
            DocPicture picture =Imageparagraph.AppendPicture(image);

            //Set Image
            picture.Height = 360;
            picture.Width = 525;
[VB.NET]
        'Create Document
        Dim document As New Document()
        Dim section As Section = document.AddSection()
        Dim Imageparagraph As Paragraph = section.AddParagraph()

        'Insert Image
        Dim image As Image = image.FromFile("E:\work\Documents\Image\street.jpg")
        Dim picture As DocPicture = Imageparagraph.AppendPicture(image)

        'Set Image
        picture.Height = 360
        picture.Width = 525

Spire.Doc is a Microsoft Word component, which enables users to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document in WPF, .NET and Silverlight.

Clearly Convert RTF to PDF in WPF

2012-08-30 01:41:23 Written by Koohji

Whatever solution you use to convert RTF to PDF before, the solution that will be introduced is the easiest method to clearly realize your RTF to PDF conversion task. The whole process can be accomplished through three lines of key code in your WPF application via a Word component Spire.Doc for WPF.

Spire.Doc for WPF, different from RTF to PDF converters, is a WPF Word component, which can generate, read, write and modify word documents in your WPF applications. Apart from converting RTF to PDF, Spire.Doc for WPF can convert word to many other commonly used formats such as PDF, HTML, Text, XML, Image and so on. Please first preview the effective screenshot of the target PDF file:

RTF to PDF

Now, please download Spire.Doc for WPF and convert your RTF to PDF by the code below:

[C#]
using Spire.Doc;
namespace WPFRTFtoPDF
{
      public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Document doc = new Document();
            doc.LoadFromFile(@"..\WPFRTFtoPDF.rtf", FileFormat.Rtf);
            doc.SaveToFile("test.pdf", FileFormat.PDF);
        }
    }
}
[VB.NET]
Imports Spire.Doc
Namespace WPFRTFtoPDF
	
	Public Partial Class MainWindow
		Inherits Window
		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub button1_Click(sender As Object, e As RoutedEventArgs)
			Dim doc As New Document()
			doc.LoadFromFile("..\WPFRTFtoPDF.rtf", FileFormat.Rtf)
			doc.SaveToFile("test.pdf", FileFormat.PDF)
		End Sub
	End Class
End Namespace

For comparison, I put the original RTF file below:

RTF to PDF

Spire.Doc is a standalone word component, which enables users to perform a wide range of word document processing tasks in WPF, .NET and Silverlight without installing MS Word on system.

Find and Highlight Text in Word in WPF

2012-08-29 07:45:27 Written by Koohji

Word Find function can enable users to search for specific text or phrase quickly. Generally speaking, the found text will be highlighted automatically in order to distinguish from other contents. Also, users can format found text, such as set it as italic, bold etc.

Spire.Doc for WPF, a professional WPF component on manipulating Word, enables users to find and highlight text in Word with WPF. With this Word WPF component, developers can invoke doc.FindAllString(text string, bool caseSensitive, bool wholeWord) method directly to find text in Word. And for highlighting found text, developers need Firstly, use TextSelection, the class Spire.Doc for WPF provides, to save found string. Then, use foreach sentence to get each selection in this TextSelection. Finally, set HighlightColor, one properties of TextRange.CharacterFormat, for text in selection.

Below, the screenshot shows a Word document whose specified text has be found and highlighted.

Find and Highlight Word Text

Download and install Spire.Doc for WPF and then use the codes below to Find and Highlight Text in Word

Code Sample:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {

            //Load Document
            Document doc = new Document();
            doc.LoadFromFile(@"E:\work\Documents\A GOOD MAN IS HARD TO FIND.docx");

            //Find Text
            TextSelection[] textSelections = doc.FindAllString("Bailey", true, true);

            //Highlight Text
            foreach (TextSelection selection in textSelections)
            {
                selection.GetAsOneRange().CharacterFormat.HighlightColor = Color.Green;
            }

            //Save Document
            doc.SaveToFile("FindText.docx", FileFormat.Docx2010);
            System.Diagnostics.Process.Start("FindText.docx");
        }


    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Drawing
Imports System.Windows

Namespace WpfApplication1
	Public Partial Class MainWindow
		Inherits Window
		Public Sub New()
			InitializeComponent()
		End Sub
		Private Sub button1_Click(sender As Object, e As RoutedEventArgs)

			'Load Document
			Dim doc As New Document()
			doc.LoadFromFile("E:\work\Documents\A GOOD MAN IS HARD TO FIND.docx")

			'Find Text
			Dim textSelections As TextSelection() = doc.FindAllString("Bailey", True, True)

			'Highlight Text
			For Each selection As TextSelection In textSelections
				selection.GetAsOneRange().CharacterFormat.HighlightColor = Color.Green
			Next

			'Save Document
			doc.SaveToFile("FindText.docx", FileFormat.Docx2010)
			System.Diagnostics.Process.Start("FindText.docx")
		End Sub


	End Class
End Namespace

Spire.Doc is a Microsoft Word component, which enables users to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document in WPF, .NET and Silverlight.

Insert Page Break in Word in WPF

2012-08-07 06:39:51 Written by Koohji

Word Page Break is used to start with contents in a new page, which can be inserted anywhere in Word document. Generally speaking, page break can be generated automatically when one page is filled with contents, or users can specify where Microsoft Word positions automatic page break. Also, users can insert manual page breaks in document to keep some paragraphs together in a single page.

Spire.Doc for WPF, a professional WPF component on manipulating Word document, enables users to insert page break in Word with WPF. Users can invoke paragraph.Append(BreakType.PageBreak) method directly to insert page break in Word.

Spire.Doc presents an easy way to insert a page break. Just follow the simple steps below to insert a page break.

The following screenshot presents document before inserting page break.

Download and install Spire.Doc for WPF. Add button in MainWindow and double click this button to use the following code to insert page break with WPF in Word.

[C#]
using System.Windows;
using Spire.Doc;
using Spire.Doc.Documents;

namespace Doc_x_PageBreak
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //Load Document
            Document doc = new Document();
            doc.LoadFromFile(@"E:\work\documents\Blues Introduction.docx");

            //Get Paragraph Position
            Section section = doc.Sections[0];
            Paragraph paragraph = section.Paragraphs[1];

            //Insert Page Break
            paragraph.AppendBreak(BreakType.PageBreak);

            //Save and Launch
            doc.SaveToFile("PageBreak.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("PageBreak.docx");
        }
    }
}
[VB.NET]
Imports System.Windows
Imports Spire.Doc
Imports Spire.Doc.Documents

Class MainWindow

    Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
        'Load Document
        Dim doc As New Document()
        doc.LoadFromFile("E:\work\documents\Blues Introduction.docx")

        'Get Paragraph Position
        Dim section As Section = doc.Sections(0)
        Dim paragraph As Paragraph = section.Paragraphs(1)

        'Insert Page Break
        paragraph.AppendBreak(BreakType.PageBreak)

        'Save and Launch
        doc.SaveToFile("PageBreak.docx", FileFormat.Docx)
        System.Diagnostics.Process.Start("PageBreak.docx")

    End Sub
End Class

Effective Screenshot:

Spire.Doc is a Microsoft Word component, which enables users to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document in WPF, .NET and Silverlight.

Insert Text Watermark to Word in WPF

2012-07-31 03:24:02 Written by Koohji

Word watermark can be text or image, which appears behind document contents and will not influence integrity of document body. It often adds interest or identifies document status, for example, marking document as private or important. This is the guide you are looking for about how to insert text watermark in Word with WPF.

Spire.Doc for WPF, a professional WPF component on manipulating Word document, enables users to insert text watermark in Word document and set format for this watermark. Comparing with “Insert Watermark” Command in Microsoft Word, Spire.Doc for WPF provides a Spire.Doc.TextWatermark class. Firstly initialize a new instance of Textwatermark with TextWatermark TXTWatermark = new TextWatermark() and then set text watermark as document watermark type by code:document.Watermark = TXTWatermark.

Besides, TextWatermark class includes several parameters for watermark formatting setting, including text, font style, layout etc. The following screenshot is the document without watermark. After the code below, you will find a result screenshot with text watermark being adding at the bottom of the page.

Word Text Watermark

Download Spire.Doc for WPF and install it on your system. After adding button in MainWindow, double click this button to use the following code to insert text watermark in Word with WPF.

[C#]
using System.Windows;
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;

namespace Doc_x_Watermark
{
   public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\work\Documents\New Zealand.docx");

            //Insert Text Watermark and Set Format
            TextWatermark TXTWatermark = new TextWatermark();
            TXTWatermark.Text = "NZ Brief Introduction ";
            TXTWatermark.FontSize = 45;
            TXTWatermark.FontName = "Broadway BT";
            TXTWatermark.Layout = WatermarkLayout.Diagonal;
            TXTWatermark.Color = Color.Purple;
            document.Watermark = TXTWatermark;

            //Save and Launch
            document.SaveToFile("TXTWatermark.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("TXTWatermark.docx");
        }
    }
}
[VB.NET]
Imports System.Windows
Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents

Class MainWindow

    Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
        'Load Document
        Dim document As New Document()
        document.LoadFromFile("E:\work\Documents\New Zealand.docx")

        'Insert Text Watermark and Set Format
        Dim TXTWatermark As New TextWatermark()
        TXTWatermark.Text = "NZ Brief Introduction"
        TXTWatermark.FontSize = 45
        TXTWatermark.FontName = "Broadway BT"
        TXTWatermark.Layout = WatermarkLayout.Diagonal
        TXTWatermark.Color = Color.Purple
        document.Watermark = TXTWatermark

        'Save and Launch
        document.SaveToFile("TXTWatermark.docx", FileFormat.Docx)
        System.Diagnostics.Process.Start("TXTWatermark.docx")

    End Sub
End Class

After running, you can get the result as following:

Word Text Watermark

Spire.Doc is a Microsoft Word component which enables users to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document in WPF.NET and Silverlight.

Convert Word to HTML in WPF

2012-07-25 08:05:32 Written by Koohji

During software development, developers may need to convert Word to HTML. Different from many available ways on Internet, in this example, the solution for converting Word to HTML enables WPF developers load a predefined Doc, Docx, or RTF document, fill it with data, convert the document to HTML.

Spire.Doc for WPF is a professional component specializing in manipulating Word document for WPF. To convert a Word to HTML simply in WPF, developers need to invoke document.LoadFromFile(), which is used to load document and document.SaveToFile(), which is used to convert document.

The following screenshot shows parts of contents of original Word document. The target HTML is at the bottom after this coding. It is shown in Firefox, same as the original document.

Word to HTML

Download and install Spire.Doc for WPF on your system. Then, add a button in MainWindow and double click it to use the following code to convert Word to HTML in WPF

[C#]
using Spire.Doc;
using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\work\Documents\Humor Them.docx");

            //Convert to HTML
            document.SaveToFile("ToHTML.html", FileFormat.Html);

            //Launch Document
            System.Diagnostics.Process.Start("ToHTML.html");

        }



    }
}
[VB.NET]
Imports Spire.Doc
Imports System.Windows

Namespace WpfApplication1
	Public Partial Class MainWindow
		Inherits Window
		Public Sub New()
			InitializeComponent()
		End Sub
		Private Sub button1_Click(sender As Object, e As RoutedEventArgs)
			'Load Document
			Dim document As New Document()
			document.LoadFromFile("E:\work\Documents\Humor Them.docx")

			'Convert to HTML
			document.SaveToFile("ToHTML.html", FileFormat.Html)

			'Launch Document
			System.Diagnostics.Process.Start("ToHTML.html")

		End Sub



	End Class
End Namespace

After running, you can get the result as following:

Word to HTML

Spire.Doc is an Microsoft Word component which enables users to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document in WPF.NET and Silverlight.

Page 2 of 2
page 2