Telerik blogs
4 Ways to Export from WPF and WinForms to Word and PDF Files_870x220

Looking to add functionality in your .NET apps to export data to Word and PDF? Learn four ways to do this with just a little code.

Building feature rich applications can often leave users asking to take visual elements off the screen to be used elsewhere. Being able to export from an application to Word or PDF opens up new possibilities, such as sharing, reporting or even satisfying Sarbanes–Oxley (SOX) audit requirements.

Getting data out of your application and into standard formats like Microsoft Word and Adobe PDF can be a daunting task. Especially when performance optimizations for large datasets, document customization & appearance, and supported platforms are taken into consideration.

However, with the right tools, adding this feature to your .NET application can be as simple as a few lines of code. Let's take a look at 4 ways we can include rich document functionality in our .NET apps with very little code and time investment.

For the examples we'll be using the Telerik Document Processing Library (DPL), which is distributed at no additional cost with the Progress Telerik UI libraries for WPF, Silverlight and WinForms. For the web developers out there, the DPL is also included with ASP.NET Web Forms and MVC. In addition, no MS Office licenses or dependencies are required to use the DPL.

If you’re using Telerik UI, you already have these capabilities in your toolbox and we’ll learn how to leverage them. If you’re not using Telerik UI yet, but would like to increase your developer productivity, learn more about it here.

1. Create New Word Document in .NET

Having the ability to create a new Word document from code provides a great deal of flexibility. With a just few dependencies we have access to Word document creation APIs that include text, image, and link generation. For this example, we'll use RadFlowDocument and RadFlowDocumentEditor to create a new Word document from a .NET console application.

We'll start with a few dependencies like System.IO to handle a file stream, and the necessary Telerik DPL assemblies.

using System.IO;
using Telerik.Windows.Documents.Flow.FormatProviders.Docx;
using Telerik.Windows.Documents.Flow.Model;
using Telerik.Windows.Documents.Flow.Model.Editing;

Next, we create a new RadFlowDocument and RadFlowDocumentEditor. The RadFlowDocumentEditor will allow us to insert new text, image and other elements to the document.


static void Main(string[] args)
 
{
 
    RadFlowDocument document = new RadFlowDocument();
 
    RadFlowDocumentEditor editor = new RadFlowDocumentEditor(document);

Using the editor, we'll write some text to the document using the InsertText method. We also have additional methods available such as:

  • InsertFloatingImage
  • InsertParagraph
  • InsertTable
  • InsertHyperlink
  • and more
insert-methods

static void Main(string[] args)
 
 
{
 
 
    RadFlowDocument document = new RadFlowDocument();
 
 
    RadFlowDocumentEditor editor = new RadFlowDocumentEditor(document);
 
 
    editor.InsertText("Hello Word!");

Once the document is complete, we just need to write it to the FileStream. For the RadFlowDocument we'll use the DocxFormatProvider to export to the DOCX format. Similarly, we could use a PdfFormatProvider to create a PDF document.


using System.IO;
 
 
using Telerik.Windows.Documents.Flow.FormatProviders.Docx;
 
 
using Telerik.Windows.Documents.Flow.Model;
 
 
using Telerik.Windows.Documents.Flow.Model.Editing;
 
 
  
 
 
namespace DocProcessing
 
 
{
 
 
    class Program
 
 
    {
 
 
        static void Main(string[] args)
 
 
        {
 
 
            RadFlowDocument document = new RadFlowDocument();
 
 
            RadFlowDocumentEditor editor = new RadFlowDocumentEditor(document);
 
 
            editor.InsertText("Hello Word!");
 
 
  
 
 
            using (Stream output = new FileStream("output.docx", FileMode.OpenOrCreate))
 
 
            {
 
 
                DocxFormatProvider provider = new DocxFormatProvider();
 
 
                provider.Export(document, output);
 
 
            }
 
 
  
 
 
        }
 
 
    }
 
 
}

HelloWorld

In this example, files created using the Telerik DPL are saved directly to disk. However, any file created using the DPL can also be downloaded via the browser from UI for ASP.NET AJAX and UI for ASP.NET MVC applications.

2. Mail Merge from .NET

Creating a mail merge is an effective way of building a template and populating it with data for processing documents in batches. With the mail merge process, you can create a series of personalized documents based on your data source.

The mail merge process is one that is often manually performed inside of Microsoft Word. With the Telerik DPL this process can be completely automated and customized based on the needs of your application. The mail merge APIs can be used virtually anywhere in .NET. To see it in action we'll use an example of how a mail merge is executed in a WPF/WinForms application.

We'll create a new document containing our template message. To create a template field in the document we'll use the InsertField method and set the field code to MERGEFIELD with the variable name we wish to use, in this case FirstName. The variable name simply matches the property on an object that we'll supply to the MailMerge method.


private RadFlowDocument CreateDocument()
 
 
{
 
 
    RadFlowDocument document = new RadFlowDocument();
 
 
    RadFlowDocumentEditor editor = new RadFlowDocumentEditor(document);
 
 
  
 
 
    editor.InsertText("Dear ");
 
 
    editor.InsertField("MERGEFIELD FirstName", "");
 
 
    editor.InsertText(" ");
 
 
    editor.InsertField("MERGEFIELD LastName", "");
 
 
    editor.InsertLine(",");
 
 
    editor.InsertLine("This is a sample Mail Merge");
 
 
    return document;
 
 
}

With the document created, the next step will be to perform the mail merge. The MailMerge method takes any IEnumerable as a parameter, in this case we'll use a predefined list of Person via GetRecipents. In this case Person has a FirstName and LastName property matching the MERGEFIELD variables.


protected void button_Click(object sender, EventArgs e)
 
 
{
 
 
    RadFlowDocument document = this.CreateDocument();
 
 
    RadFlowDocument mailMergeDocument = document.MailMerge(GetRecipients());
 
 
    //save the document
 
 
}

The document can be saved by setting up a MemoryStream and calling Export from a DocxFromatProvider. Once the memory stream is ready, we'll write it to a file.


protected void button_Click(object sender, EventArgs e)
 
 
{
 
 
    RadFlowDocument document = this.CreateDocument();
 
 
    RadFlowDocument mailMergeDocument = document.MailMerge(GetRecipients());
 
 
    byte[] renderedBytes = null;
 
 
     
 
 
     using (Stream output = new FileStream("output.docx", FileMode.OpenOrCreate))
 
 
     {
 
 
         DocxFormatProvider provider = new DocxFormatProvider();
 
 
         provider.Export(mailMergeDocument, output);
 
 
     }}

The result is a multi-page .DOCX file for each recipient provided to the mail merge. This type of document can easily be printed and sent to clients as physical mail. See demos.telerik.com/wpf and the UI for WinForms demos for a more comprehensive example that includes additional file types and document features.

mailMerge

3. Convert Word to PDF in .NET

One of the Telerik DPL strengths is its ability to import and export various file types like: DOCX, PDF (export only), HTML and RTF. Because of this ability, it can also be used to do file conversions between these types as well. Using the IFormatProvider we can utilize the various format providers within the Telerik DPL interchangeably. Let's take a look at a basic example of a console app that can import a DOCX file and export it to PDF.

We'll begin by creating a default provider using an IFormatProvider and setting it to an instance of DocxFormatProvider. A RadFlowDocument is used as our document in the conversion from DOCX to PDF.


IFormatProvider<RadFlowDocument> fileFormatProvider = new DocxFormatProvider();
 
 
RadFlowDocument documentToConvert = new RadFlowDocument();

The DOCX document is opened from disk using the DocxFormatProvider and streamed into memory.

using (FileStream input = new FileStream("input.docx", FileMode.Open))
 
{
 
documentToConvert = fileFormatProvider.Import(input);
 
}

With the document in memory as a RadFlowDocument we can change our provider from a DocxFormatProviderPdfFormatProvider. Now the document can be written back to disk as a PDF.

fileFormatProvider = new PdfFormatProvider();
 
 
 
    using (Stream output = new FileStream("output.pdf", FileMode.OpenOrCreate))
 
    {
 
        fileFormatProvider.Export(documentToConvert, output);
 
    }

Convert Doc PDF

As you can see in the complete example, in just a few short lines of code we're able to convert from DOCX to PDF.

static void Main(string[] args)
 
{
 
    IFormatProvider<RadFlowDocument> fileFormatProvider = new DocxFormatProvider();
 
    RadFlowDocument documentToConvert = new RadFlowDocument();
 
 
 
    // Read DOCX
 
    using (FileStream input = new FileStream("input.docx", FileMode.Open))
 
    {
 
        documentToConvert = fileFormatProvider.Import(input);
 
    }
 
 
 
    // Write PDF
 
    fileFormatProvider = new PdfFormatProvider(); // change format provider to PDF
 
 
 
    using (Stream output = new FileStream("output.pdf", FileMode.OpenOrCreate))
 
    {
 
        fileFormatProvider.Export(documentToConvert, output);
 
    }
 
}

This method of importing and exporting documents can be used to convert between file formats. One caveat however is that there is no import functionality for PDF documents due to file format limitations. To deal with this limitation the IFormatProvider is equipped with a CanImport property that can be checked before the Import operation is performed.

See the UI for WPF and UI for WinForms WordsProcessing demos that includes additional file types and scenarios.

4. Edit Microsoft Word Docs in WPF and WinForms

Customers can sometimes ask for time-consuming project requirements, like the ability to edit Word Documents in the application without the need to leave the app and use external editors. On the surface this sounds like a feature that will take quite a bit of effort to accomplish; however, it's as simple as adding a rich text component to your application which comes with the Telerik UI for WPF and Telerik UI for WinForms suites.

rtb combined

Using UI for WPF and UI for WinForms, the ability to import and export right from the rich text editor control can be accomplished with few lines of code.

DocxFormatProvider provider = new DocxFormatProvider();
 
 
 
using (FileStream fileStream = new FileStream(@"input.docx", FileMode.Open))
 
{
 
    this.radRichTextBox1.Document = provider.Import(fileStream);
 
})

Exporting the content is just as simple. Simply pick the format provider for the desired format – PDF, DOCX, XAML, HTML, RTF, TXT and utilize its Export() method.

DocxFormatProvider provider = new DocxFormatProvider();
 
SaveFileDialog saveDialog = new SaveFileDialog() { DefaultExt = ".docx", Filter = "Documents|*.docx" };
 
DialogResult dialogResult = saveDialog.ShowDialog();
 
if (dialogResult == System.Windows.Forms.DialogResult.OK)
 
{
 
     using (Stream output = saveDialog.OpenFile())
 
     {
 
         provider.Export(radRichTextEditor1.Document, output);
 
     }
 
}

See the Telerik UI for WPF and Telerik UI for WinForms demos for more comprehensive examples that include additional editor features.

Conclusion

Whether you need to create documents from scratch or edit in the desktop app, the Telerik UI libraries make short work of any document export task for .NET developers. With the Telerik Document Processing Library new files can be created from scratch as DOCX, PDF, RTF, or TXT. Advanced features such as mail merge can reduce manual tasks with app driven automation. With the addition of Telerik UI libraries powered by UI for WPF and WinForms, documents can be edited on screen and custom export features empower users to export content with the click of a button.

Get access to the vast benefits of Telerik Document Processing and document exporting by downloading either the full Progress DevCraft bundle or any technology-specific library you need: Telerik UI for WPF or Telerik UI for WinForms.

Other Useful Resources


Stefan Stefanov
About the Author

Stefan Stefanov

Stefan Stefanov (MCPD) is a Senior Manager, Product Management and Product Marketing at Progress. He has been working with Telerik products since 2010, when he joined the company. Off work he enjoys traveling, hanging out with friends and reading various technology blogs. You can find Stefan on Twitter and LinkedIn.

Related Posts

Comments

Comments are disabled in preview mode.