Click here to Skip to main content
Click here to Skip to main content

Creating Word documents in .Net using Docentric Toolkit

, 14 Apr 2014
Rate this:
Please Sign up or sign in to vote.
Introduction As any other developer who has been involved in writing business applications, I have used different frameworks (and tricks) to generate word reports. It’s usually a roller coaster ride as most of the components and frameworks try to use various inbuilt features from Word (usually

Editorial Note

This article appears in the Third Party Product Reviews section. Articles in this section are for the members only and must not be used by tool vendors to promote or advertise products in any way, shape or form. Please report any spam or advertising.

Introduction

As any other developer who has been involved in writing business applications, I have used different frameworks (and tricks) to generate word reports. It’s usually a roller coaster ride as most of the components and frameworks try to use various inbuilt features from Word (usually Mail Merge) to accomplish that.

This article is focused on generating or creating the mail merge word documents using Docentric Toolkit.

In their own words,

Docentric Toolkit is a Word document generation, mail-merge and reporting toolkit for .NET designed to drastically reduce the time and effort required to create and maintain documents and reports in Word.

And based on their website, the high level design of the product is as shown below:

Let’s try it first hands

Generate Document using .Net Object

As I said before, I have used various components before to implement the word report generation. To be honest it has never been a satisfactory experience.

For the purpose of demonstration in this article, I would be using the xml data source as the input for report generation using the Docentric Took Kit. And as I wanted a real world example of data and not something which I would define, I decided to use the Book Catalog Xml data source based on this MSDN link.

Let’s do some ground work before we dig deep into the Docentric demonstration. Based on the xml data structure, I wanted to create a .NET class that would hold and represent the XML data. Big deal, you can always use the XSD.exe to generate XML schema or common language runtime classes from XDR, XML, and XSD files, or from classes in a runtime assembly. But what I was not aware of was a new feature in Visual Studio 2012 (and of course Visual Studio 2013) and when using .Net 4.5 project. Now, you can use simple use Edit -> Paste Special -> Paste XML as Classes. Quite handy as a feature and lets you as a developer focus on more important thing which you want to accomplish and does the most obvious things itself.


So now we have a class library named Catalog.dll which wraps up the data structure for our input Book Catalog xml.

The installation of Docentric Toolkit not only gives you access to the assemblies which you can use in your code to generate word reports but also provides an Add-In for Microsoft Word which can be used to generate the template documents for your reports. In my opinion, the Add-In is one of the unique features of Docentric Toolkit which differentiates it from other similar mail merge solutions available in market.

Data Source Explorer

The starting point while designing a template for your report is the Data Source Explorer. The various data sources supported by the toolkit are:

  • .Net Objects
  • Xml Data Source
  • DTS Object

DTS is their own type system and was introduced in order to make the template design user experience even better for non-technical users. However, the first two types are quite generic as well and can be used by someone who is not writing real code in his day-to-day work. For this example, I will be using .NET Object kind of a data source which is probably used the most.

The next step is to select a Schema for the report you are going to generate and I am going to use the class catalogBook from the assembly Catalog.dll which we created earlier using the xml data source.

Schema Info and Member Tree

Once the Schema has been selected, Docentric Toolkit automatically provides you with a graphical representation of all available members defined by the schema.

Basic Design and Elements Explorer

For the first demonstration, I want to generate a report with the information of a singe book record and that’s the reason I have specified in the template itself what kind of behavior I want from the template. You can change this by selecting the value of .Net Type Usage to be either Single Object or Collection.

Next step is to graphically design your word template and add the field tagging elements for each property that we want to write on the generated document. The Field element is the most basic tagging element used as a placeholder for values on a report template. It is a bind able element which means that when it is placed on a template, it can also be bound to data. The Field element will simply be replaced with the value it is bound to when the report engine will process it.

Every field selected and specified is represented in the Elements Explorer (see image below). The Field elements also provide you with additional features such as formatting a string to a number, date time etc.
The Formatted objects are shown with a different representation with an adjacent circle (see next to price),

Review1

Get more with less code

I am a big supporter of writing less lines of code and achieving more with fewer lines of code. The motive behind this argument is simple. The bigger your code base becomes, the bigger gets your technical debt and effort to maintain it throughout its life cycle.

Let’s start by creating a simple Console Application to demonstrate the report generation. All you need to begin is add reference to the following three Docentric Libraries in your project.

The following code is the most basic repeatable piece of code which you can use to achieve most of the functionality when generating reports using Docentric Toolkit.

private static void GenerateReport(string templateDocument, object input)
        {
            string reportDocumentFileName = String.Format("GenerateReport_{0}.docx", Guid.NewGuid());

            using (Stream reportDocumentStream = File.Create(reportDocumentFileName))
            {
                using (Stream reportTemplateStream = File.OpenRead(templateDocument))
                {
                    DocumentGenerator dg = new DocumentGenerator(input);

                    DocumentGenerationResult result = dg.GenerateDocument(reportTemplateStream, reportDocumentStream);

                    if (result.HasErrors)
                    {
                        foreach (Docentric.Word.Error error in result.Errors) Console.Out.WriteLine(error.Message);
                    }
                }
            }
        }

XmlSerializer reader = new XmlSerializer(typeof(catalog));
System.IO.StreamReader file = new System.IO.StreamReader(dataXml);
catalog catalogOverview = new catalog();
catalogOverview = (catalog)reader.Deserialize(file);

//Generate simple report fields
GenerateReport(templateDocumentSimple, catalogOverview.book[0]);

With just handful lines of code and most of the configuration in the Word itself we can easily generate a report connecting to a .Net Schema and data coming in the form of an Xml file.

Generate Document directly using Xml Schema

We quickly saw the Data Source possibility in the Docentric Toolkit and the support directly for Xml objects. What does it exactly mean?

In simple terms, further less code. You can simply specify an XSD or even an a sample XML file to import the schema for a data source to Docentric Toolkit Add-In. It will generate a schema based on the data available as it would have done with the .Net Object.

Once you selected the xml file which we used to generate the .Net class, we see a very similar schema of objects as it was represented by .Net Object. This means, you can actually get rid of the additional step of generating the .Net library for your xml data source.

However, in this example we will generate a table with a collection of records from the xml file. The collection will use the List feature which basically wraps around the field elements to create a repeatable control in the template. The List element is much different to the Field element. It doesn’t act as a placeholder, but rather as a “repeater”. The List element’s behavior is very simple. All it does is “repeating” its wrapped content for each data item in the collection it is bound to, where the wrapped content acts as a content template for each collection item. A template content is not limited to be a table row, it can be anything. Those familiar with the “Repeater” control in Asp.Net or WPF/Silverlight’s “Items Control” will notice that similar concepts have also been employed for the List element.

Revie2

The data context gets changed to the current collection item for the List element’s child elements. For example, if the List element is bound to the collection, then its nested Field elements Data Context will be of type Customer. This is reasonable, since the Field element is part of the List element’s template content, which gets repeated for each item in the collection. Most data bindable elements nested inside a List element will mostly have their Binding Source set to the Current Data Context value.


With even fewer lines of code which we wrote earlier and just changing a few arguments to the same function we can generate the results as shown below. And not only generation, we can control certain other behaviors such as sorting etc. within the template itself. If you notice in the figure above, the table is sorted based on the Title of a book and it is completely configured in the template without any special treatment in the code.

//Generate report with table structured data
XElement data = XElement.Load(dataXml);
GenerateReport(templateDocumentTable, data);

Conclusion

One of the most common requirement in any serious business application is a generation of reports based on the data used.

Docentric Toolkit is no doubt a nice mail merge framework to stream line the document and report generation process in any application. As I indicated earlier in the article as well, the best feature in my opinion is the simplicity of the toolkit and the burden it removes from the developer for the repetitive work he has to do. With the template feature, the business users themselves can define the document, fields, lists, groups etc. and of course we developer can enhance the work done by them to make sure the correct data is enriched into the reports.

Having said that, I would personally like to see more from this toolkit to even go to an extent where you don’t need any code written for report generation. And your template can just accept the data source from various formats like Xml, OData or JSON feed.

Download Demo Project

The post Creating Word documents in .Net using Docentric Toolkit appeared first on Manas Bhardwaj's Stream.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Manas Bhardwaj
Architect
Netherlands Netherlands
Read my personal blog at www.manasbhardwaj.net.
Follow on   Twitter

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 14 Apr 2014
Article Copyright 2014 by Manas Bhardwaj
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid