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.

Split Huge PDF Document by Pages in WPF

2012-08-24 02:43:10 Written by Koohji

PDF Split is always needed by programmers and developers. It is very convenient to split a PDF file to multiple files by using online PDF split tools, you can split PDF in a page range as well as only extract a unique page. However, if you want to split a huge PDF document to hundreds of files, you have to try at least dozens of times, which, undoubtedly, takes too much time. Furthermore, when the network goes slowly, an error is likely to occur, sometimes, the file is reported to be damaged or corrupted. While using Spire.PDF for WPF, you can easily split huge PDF document up to hundreds of pages without any worry of the document safety in your WPF application.

By using Spire.PDF, you can achieve the effect as below:

Split PDF Document

Spire.PDF for WPF, as a WPF PDF component, allows users to create, read, write and manipulate PDF documents without using Adobe Acrobat or any third party component library. As for PDF split task, you can realize it by below methods:

doc.Split(pattern):

When splitting a PDF document to multiple PDF files, each PDF file is made of one page from the original PDF file. Split method works well since it can quickly split your PDF file and there is only one parameter passed to provide a template name of the destination PDF file.

String.Format(pattern, doc.Pages.Count - 1):

"String.Format" method provides great convenience for you to preview an existing file by returning the PDF file name that you want to process. The second parameter String.Format method is used to point out the index item which starts from 0.

The key step of PDF split task only requires four lines of code, before your start your PDF split project, please download Spirel.PDF for WPF first, then you can invoke the key code below to split any PDF you want.

[C#]
        String pattern = "SplitDocument-{0}.pdf";
        doc.Split(pattern);
        String lastPageFileName= String.Format(pattern, doc.Pages.Count - 1);
        doc.Close();
[VB.NET]
	Dim pattern As String = "SplitDocument-{0}.pdf"
	doc.Split(pattern)
	Dim lastPageFileName As String = String.Format(pattern, doc.Pages.Count - 1)
	doc.Close()

Obviously, using this WPF PDF component, PDF can be split absolutely according to your requirements. Enjoy fast speed, high quality and free choices to build your application to split PDF right now.

OLE, short for Object Linking and Embedding, is a powerful technology integrated into Microsoft Word and other Microsoft Office applications. Its primary purpose is to seamlessly integrate objects from external programs directly into your documents. These objects can range from simple images or charts to more complex items like spreadsheets, presentations, multimedia files and more. In this article, we will demonstrate how to insert OLE objects as well as extract OLE objects in Word documents in C# using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Insert OLE Objects in Word in C#

Spire.Doc for .NET offers the Paragraph.AppendOleObject(string pathToFile, DocPicture olePicture), OleObjectType type) method, which allows you to insert various types of documents (including Excel spreadsheets, PDF files, Word documents, PowerPoint presentations, and more) as OLE objects into a Word document.

The detailed steps are as follows:

  • Create an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile() method.
  • Get a specific section using the Document.Sections[index] property.
  • Add a paragraph to the section using the Section.AddParagraph() method.
  • Create an instance of the DocPicture class.
  • Load an image that will be used as the icon of the embedded object using the DocPicture.LoadImage() method, and then set image width and height.
  • Append an Excel spreadsheet as an OLE object to the paragraph using the Paragraph.AppendOleObject(string pathToFile, DocPicture olePicture, OleObjectType type) method.
  • Repeat the above 4-7 steps to add more paragraphs and append more types of documents, like a PDF file, a PowerPoint presentation, and a Word document as OLE objects.
  • Save the result file using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace InsertOleObjects
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the Document class
            Document doc = new Document();
            // Load a Word document
            doc.LoadFromFile("Example.docx");

            // Get the first section
            Section section = doc.Sections[0];

            // Add a paragraph to the section
            Paragraph para1 = section.AddParagraph();
            para1.AppendText("Excel File: ");
            // Load an image that will be used as the icon of the OLE object
            DocPicture picture1 = new DocPicture(doc);
            picture1.LoadImage("Excel-Icon.png");
            picture1.Width = 50;
            picture1.Height = 50;
            // Append an Excel spreadsheet to the paragraph as an OLE object
            para1.AppendOleObject("Budget.xlsx", picture1, OleObjectType.ExcelWorksheet);

            // Add a paragraph to the section
            Paragraph para2 = section.AddParagraph();
            para2.AppendText("PDF File: ");
            // Load an image that will be used as the icon of the OLE object
            DocPicture picture2 = new DocPicture(doc);
            picture2.LoadImage("PDF-Icon.png");
            picture2.Width = 50;
            picture2.Height = 50;
            // Append a PDF file to the paragraph as an OLE object
            para2.AppendOleObject("Report.pdf", picture2, OleObjectType.AdobeAcrobatDocument);

            // Add a paragraph to the section
            Paragraph para3 = section.AddParagraph();
            para3.AppendText("PPT File: ");
            // Load an image that will be used as the icon of the OLE object
            DocPicture picture3 = new DocPicture(doc);
            picture3.LoadImage("PPT-Icon.png");
            picture3.Width = 50;
            picture3.Height = 50;
            // Append a PowerPoint presentation to the paragraph as an OLE object
            para3.AppendOleObject("Plan.pptx", picture3, OleObjectType.PowerPointPresentation);

            // Add a paragraph to the section
            Paragraph para4 = section.AddParagraph();
            para4.AppendText("Word File: ");
            // Load an image that will be used as the icon of the OLE object
            DocPicture picture4 = new DocPicture(doc);
            picture4.LoadImage("Word-Icon.png");
            picture4.Width = 50;
            picture4.Height = 50;
            // Append a Word document to the paragraph as an OLE object
            para4.AppendOleObject("Introduction.docx", picture4, OleObjectType.WordDocument);

            doc.SaveToFile("InsertOLE.docx", FileFormat.Docx2013);
            doc.Close();
        }
    }
}

C#: Insert or Extract OLE Objects in Word

Extract OLE Objects from Word in C#

To extract OLE objects from a Word document, you need to locate the OLE objects within the document first. Once located, identify the file format of each OLE object. Finally, save the data of each OLE object to a file in its original format.

The detailed steps are as follows:

  • Create an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile() method.
  • Iterate through all sections of the document.
  • Iterate through all child objects in the body of each section.
  • Identify the paragraphs within each section.
  • Iterate through the child objects in each paragraph.
  • Locate the OLE object within the paragraph.
  • Determine the file format of the OLE object.
  • Save the data of the OLE object to a file in its native file format.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;

namespace InsertOrExtractOleObjects
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of the Document class
            Document doc = new Document();
            // Load a Word document
            doc.LoadFromFile("InsertOLE.docx");

            int i = 1;
            // Iterate through all sections of the Word document
            foreach (Section sec in doc.Sections)
            {
                // Iterate through all child objects in the body of each section
                foreach (DocumentObject obj in sec.Body.ChildObjects)
                {
                    // Check if the child object is a paragraph
                    if (obj is Paragraph par)
                    {
                        // Iterate through the child objects in the paragraph
                        foreach (DocumentObject o in par.ChildObjects)
                        {
                            // Check if the child object is an OLE object
                            if (o is DocOleObject ole)
                            {
                                string s = ole.ObjectType;
                                string ext = "";

                                // Check if the OLE object is a PDF file
                                if (s.StartsWith("AcroExch.Document"))
                                {
                                    ext = ".pdf";
                                }
                                // Check if the OLE object is an Excel spreadsheet
                                else if (s.StartsWith("Excel.Sheet"))
                                {
                                    ext = ".xlsx";
                                }
                                // Check if the OLE object is a PowerPoint presentation
                                else if (s.StartsWith("PowerPoint.Show"))
                                {
                                    ext = ".pptx";
                                }
                                // Check if the OLE object is a Word document
                                else if (s.StartsWith("Word.Document"))
                                {
                                    ext = ".docx";
                                }
                                else
                                {
                                    continue;
                                }

                                // Write the data of OLE into a file in its native format
                                using (var file = System.IO.File.OpenWrite($"Output/OLE{i}{ext}"))
                                {
                                    file.Write(ole.NativeData, 0, ole.NativeData.Length);
                                }

                                i++;
                            }
                        }
                    }
                }
            }

            doc.Close();
        }
    }
}

C#: Insert or Extract OLE Objects in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Create PDF Digital Signature in WPF

2012-08-16 01:00:08 Written by Koohji

Digital signature is more advanced and more popular to detect forgery and tampering today compared with traditional handwritten signature. Especially in business world, digital signature becomes an effective method to safeguard and authenticate your documents. As long as a digital signature is created and singed, the document has not been tampered and the recipients can view both the document version history and any changes that were made to it. Now, it is time to see how to create a PDF digital signature via a WPF PDF component Spire.PDF for WPF.

Spire.PDF for WPF, as a PDF component, enables you to create PDF digital signature in a simple way which can not only ensure your data information has not been altered since it was sent but also verify the signer's digital identity. The key procedure only requires six lines of code. Please preview the effective screenshot below, and then, view the key code.

Create Digital Signature

Please feel free to Download Spire.PDF for WPF first before the key code below. In this solution, for constructing one instance of a Spire.Pdf.Sercurity.PdfCertificate class named cert, we reference a certificate file and its file protect password as parameters. Then, cert is applied to create an instance of a PdfSignature class we name it signature. Setting signature “page” parameter allows you to sign the digital signature of any PDF page. And DocumentPermissions, one property of signature, can be set: AllowComments, AllowFormFill and ForbidChanges.

Core Code:

[C#]
String pfxPath = @"..\Data\Demo.pfx";
PdfCertificate cert = new PdfCertificate(pfxPath, "e-iceblue");
PdfSignature signature = new PdfSignature(doc, page, cert, "demo");
signature.ContactInfo = "Harry Hu";
signature.Certificated = true;
signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill;
[VB.NET]
Dim pfxPath As String = "..\Data\Demo.pfx"
Dim cert As New PdfCertificate(pfxPath, "e-iceblue")
Dim signature As New PdfSignature(doc, page, cert, "demo")
signature.ContactInfo = "Harry Hu"
signature.Certificated = True
signature.DocumentPermissions = PdfCertificationFlags.AllowFormFill

Encrypt PDF for Security in WPF

2012-08-10 06:04:42 Written by Koohji

For PDF security, people are more likely to encrypt PDF file by setting up to two passwords: owner password and user password. The essential difference between these two passwords is that people can fully control the document by owner password, while only can open or have to subject to some restrictions by user password. This section will introduce a solution to easily encrypt your PDF by the two passwords via Spire.PDF for WPF.

Spire.PDF for WPF is a WPF PDF component, which can encrypt your PDF not only by owner password but also by restricting nine permissions when setting user password. In the solution, these two passwords are set by an object of PDFSecurity class which is contained in the namespace Spire.PDFDocument.Security.

Before you start, please feel free to download Spire.PDF for WPF first and encrypt your PDF file by below key steps after loading it.

Step1: Set PDF password size

In this step, three kinds of key size are applicable by the enum Spire.Pdf.Security.PdfEncryptionKeySize. They are: Key128Bit, Key256Bit and Key40Bit. You can choose any of the three according to your own situation.

[C#]
doc.Security.KeySize = PdfEncryptionKeySize.Key256Bit;
[VB.NET]
doc.Security.KeySize = PdfEncryptionKeySize.Key256Bit

Step 2: Secure PDF file by passwords

Owner password and user password are set to encrypt your PDF file. Please make sure that the password size should not be over the key size you set in last step.

[C#]
doc.Security.OwnerPassword = "e-iceblue";
doc.Security.UserPassword = "pdf";
[VB.NET]
doc.Security.OwnerPassword = "e-iceblue"
doc.Security.UserPassword = "pdf"

Step 3: Restrict certain permissions of user password

Nine access permissions of user password can be specified in the step, you can view them as below picture:

Encrypt PDF Document

  • AccessibilityCopyContent: copy accessibility content.
  • AssembleDocument: assemble document permission. (Only for 128 bits key).
  • CopyContent: copy content.
  • Default: default value means users are authorized all permissions.
  • EditAnnotations: add or modify text annotations, fill in interactive form fields.
  • EditContent: edit content.
  • FillFields: fill form fields. (Only for 128 bits key).
  • FullQualityPrint: print document with full quality.
  • Print: print document.

Here, three permissions are authorized: AccessibilityCopyContent, Print and EditAnnotations. Now, see following code:

[C#]
doc.Security.Permissions = PdfPermissionsFlags.AccessibilityCopyContent | PdfPermissionsFlags.Print | PdfPermissionsFlags.EditAnnotations;
[VB.NET]
doc.Security.Permissions = PdfPermissionsFlags. AccessibilityCopyContent Or PdfPermissionsFlags. Print Or PdfPermissionsFlags.EditAnnotations

After you run the project, appears a dialog box in which you need to input password before opening the PDF document. You can look at the effective screenshot below:

Encrypt PDF Document

This section will introduce an easy solution to convert image to PDF in WPF. In my method, image to PDF conversion is just a piece of cake since various image formats such as jpg, png and bmp, even images of gif, tif and ico can be converted to PDF through two key steps for Spire.PDF users.

Spire.PDF for WPF,a professional WPF PDF component, enables your WPF applications to read, write and manipulate PDF document without Adobe Acrobat or any third party component library. As for image to PDF conversion, apart from clearly converting images of different formats to PDF, Spire.PDF for WPF also allows you to directly load your images to PDF files from stream. Please feel free to Download Spire.PDF and give it a try following our programming guide below. The following is a picture which we will convert to PDF. At the bottom of this  article, a target PDF will be presented.

Image to PDF

Now it's time for the key procedure of image to PDF conversion. To realize the key procedure, we need below two steps.

Step 1: Load an image file from system

An image file is required in this step. The image format can be any format among jpg, png, bmp, gif, tif and ico. Here a jpg image is loaded.

[C#]
//Load a jpg image from system
PdfImage image = PdfImage.FromFile(@"..\sky.jpg");
[VB.NET]
'Load a jpg image from system
Dim image As PdfImage = PdfImage.FromFile("..\sky.jpg") 

Step 2: Set the image location and size to fit PDF page

Spire.PDF for WPF contains a namespace “Spire.Pdf.Graphics” in which image size and location are set through four parameters: Width/Height for image size and fitWidth/fitHeight for image location.

[C#]
  //Set image display location and size in PDF
float widthFitRate = image.PhysicalDimension.Width / page.Canvas.ClientSize.Width;
float heightFitRate = image.PhysicalDimension.Height / page.Canvas.ClientSize.Height;
float fitRate = Math.Max(widthFitRate, heightFitRate);
float fitWidth = image.PhysicalDimension.Width / fitRate;
float fitHeight = image.PhysicalDimension.Height / fitRate;
page.Canvas.DrawImage(image, 30, 30, fitWidth, fitHeight);
[VB.NET]
'Set image display location and size in PDF
Dim widthFitRate As Single = image.PhysicalDimension.Width / page.Canvas.ClientSize.Width
Dim heightFitRate As Single = image.PhysicalDimension.Height / page.Canvas.ClientSize.Height
Dim fitRate As Single = Math.Max(widthFitRate, heightFitRate)
Dim fitWidth As Single = image.PhysicalDimension.Width / fitRate
Dim fitHeight As Single = image.PhysicalDimension.Height / fitRate
page.Canvas.DrawImage(image, 30, 30, fitWidth, fitHeight)

After this coding, run your application, you can find a target PDF as below.

Image to PDF

Convert Webpage to PDF in WPF

2012-08-08 01:06:49 Written by Koohji

HTML to PDF solution can be quite a few when people search on google. However, most solutions are not proper in use since what you view on webpage is not always completely same with what you get on your PDF. Some information such as dynamic image and anchor text in HTML are easily lost. This section will introduce a simple method to clearly convert HTML to PDF without any cut on WPF platform.

Spire.PDF for WPF, as a professional PDF component, allows you to clearly convert HTML to PDF only by three lines of key code on WPF platform. In the solution, you only need to load HTML file with four parameters:

  • URL, the url of the webpage which will be converted to PDF file.
  • Enable JavaScrpit, indicates whether enables the JavaScript of the webpage.
  • Enable hyperlink, indicates whether enables the hyperlink of the webpage.
  • Auto detect page break, indicates whether splits auto the web page in the result PDF file.

Then, save your html as PDF to file by calling the method PdfDocument.LoadFromHTM. Please preview the result screenshot of the whole project first as prove:

Webpage to PDF

Before demonstrating the code, please feel free to download Spire.PDF and install it on system. Now, you can view the full code below:

[C#]
using Spire.Pdf;

namespace WPFhtmltopdf
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        [STAThread]
        private void button1_Click(object sender, RoutedEventArgs e)
        {

            //Create a new pdf document.
            PdfDocument doc = new PdfDocument();
            //load the webpage 
            String url = "http://msdn.microsoft.com/";
            doc.LoadFromHTML(url, false, true, true);
            //Save html webpage as pdf file.
            doc.SaveToFile("sample.pdf");
            doc.Close();
        }
    }
}
[VB.NET]
Imports Spire.Pdf

Namespace WPFhtmltopdf
	''' 
	''' Interaction logic for MainWindow.xaml
	''' 
	Public Partial Class MainWindow
		Inherits Window
		Public Sub New()
			InitializeComponent()
		End Sub
		 _
		Private Sub button1_Click(sender As Object, e As RoutedEventArgs)

			'Create a new pdf document.
			Dim doc As New PdfDocument()
			'load the webpage 
			Dim url As  = "http://msdn.microsoft.com/"
			doc.LoadFromHTML(url, False, True, True)
			'Save html webpage as pdf file.
			doc.SaveToFile("sample.pdf")
			doc.Close()
		End Sub
	End Class
End Namespace

Obviously, using this WPF PDF component, the webpage is easily converted to PDF. Both text and images are clearly shown in PDF file. Besides, Spire.PDF for WPF is a 100% secure PDF component software. No Malware, No Spyware and No Virus.

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.

Convert Text to PDF in WPF

2012-08-01 03:15:20 Written by Koohji

This section is designed to introduce a simple method to clearly convert text to PDF for WPF. During the text to PDF conversion task, font, font color, line space and other text format also can be quickly set according to your own need via a WPF PDF component Spire.PDF for WPF.

Spire.PDF for WPF will display a solution of two key steps to realize text to PDF task as well as customize text in PDF. Compared with some text to PDF converters, Spire.PDF for WPF not only has the function of convert HTML, text and image to PDF, but also owns the ability to read, write and manipulate PDF document without Adobe Acrobat or any third party component library.

Below screenshot gives you a clear view of the text to PDF conversion effect:

Text to PDF

Please download Spire.PDF for WPF on system. Then, perform your text to PDF by below key steps.

Step1: Read all text information to s string

In this step, you need to read all the text from a text file to a string.

[C#]
string text = File.ReadAllText(@"..\texttopdf.txt");
[VB.NET]
Dim text As String = File.ReadAllText("..\texttopdf.txt")

Step2: Draw string to PDF document with custom layout.

This step allows you to set the text font, font color, text format and position in PDF document at your own will by below code:

[C#]
  PdfPageBase page = section.Pages.Add();
            PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 11);
            PdfStringFormat format = new PdfStringFormat();
            format.LineSpacing = 20f;
            float pageWidth = page.Canvas.ClientSize.Width;
            PdfBrush brush = PdfBrushes.DarkBlue;
            float y = 30;
            PdfStringLayouter textLayouter = new PdfStringLayouter();
            PdfStringLayoutResult result
                = textLayouter.Layout(text, font, format, new SizeF(pageWidth, 0));
            foreach (LineInfo line in result.Lines)
            {
                page.Canvas.DrawString(line.Text, font, brush, 0, y, format);
                y = y + result.LineHeight;
            }
[VB.NET]
Dim page As PdfPageBase = section.Pages.Add()
	Dim font As New PdfFont(PdfFontFamily.Helvetica, 11)
	Dim format As New PdfStringFormat()
	format.LineSpacing = 20F
	Dim pageWidth As Single = page.Canvas.ClientSize.Width
	Dim brush As PdfBrush = PdfBrushes.DarkBlue
	Dim y As Single = 30
	Dim textLayouter As New PdfStringLayouter()
	Dim result As PdfStringLayoutResult = textLayouter.Layout(text, font, format, New SizeF(pageWidth, 0))

	For Each line As LineInfo In result.Lines
		page.Canvas.DrawString(line.Text, font, brush, 0, y, format)
		y = y + result.LineHeight
	Next

Now that is all the core codes for draw text in PDF.  Apart from converting text to PDF, Spire.PDF for WPF also can extract PDF text.

page 71