Aspose.Word

A .NET Word Document Reporting Component

Steve C Orr

October 30, 2009

7 Min Read
ITPro Today logo in a gray background | ITPro Today

asp:review

 

Aspose.Word

A .NET Word Document Reporting Component

 

By Steve C.Orr

 

So youwant to create downloadable, dynamic Microsoft Word documents for the users ofyour Web site. You could use COM automation to have Word itself generate thedocuments for you. This isn't a bad choice for a Windows Forms application;however, there are many reasons why it's a bad idea for Web applications,including licensing issues, poor performance, and virtually no scalability.

 

Forbasic documents you could output plain HTML to your Web page and simply changethe Response.ContentType to"application/ms-word", causing the document to open inside Word on the user'smachine. However, this approach falls short when you want or need more advancedcontrol over the document creation process, such as filling in templates, orusing mail merge, lists, headers, and drawing objects.

 

Aspose.Wordprovides a good solution to all these problems.

 

Outperform

Writtenyears ago in unmanaged code, Word was designed to be run as a single-userdesktop application. Its threading model does not gracefully support use as aserver component. On the other hand, Aspose.Word is written entirely in C# andhas no dependencies (other than the .NET Framework, of course). Word is notrequired on your server, because Aspose.Word itself acts as the documentcreation engine. This delivers all kinds of scalability and frees you frompotentially daunting Microsoft licensing requirements. To view the generateddocuments, your users will either need Word installed on their computers or theWord file viewer, which can be downloaded free from Microsoft.

 

Thespeed of this product is generally snappy, although sometimes for no obviousreason documents appear to be generated noticeably faster than other times.According to Aspose, informal testing has demonstrated that a standard desktopPC can generate roughly 180,000 moderately complex five-page documents perhour. Now that's performance!

 

FlexibleSolutions

One wayto go about using the custom class library exposed by Aspose.Word is to ignoreit. Instead, open Word and build an example of what you want your finaldocument to look like. You can set up static text, colors, tables, fonts,images, etc. in advance. Wherever you want dynamic data to be inserted, insert amerge field. (To do this, select Fieldfrom the Insert dropdown menu in Word. Then chooseMergeField from the list of field names and give the field a unique name soyou can reference it from your code.) This standard Word file will act as yourtemplate, or as the Aspose documentation names it, a "designer." Then at runtime you can use the Aspose.Word object model to merge the data with yourdesigner to result in a snazzy looking document full of juicy data. If youprefer, you can skip the designer and generate every aspect of the document atrun time. Or you can mix and match the techniques in virtually any wayimaginable. Almost every available feature can be specified at design time orrun time.

 

Figure 1shows a simple VB.NET example that fills in a couple of fields in an existingWord template and outputs it to the browser. After instantiating theAspose.Word object and pointing it to your template file, you then pass it anarray of field names and an array of their associated values. The final statementsaves the document to the output stream and opens it in the user's browser. Youcan optionally choose to open it in an independent instance of Word outside theWeb browser, although my tests of this functionality caused the same standarddownload prompt to appear twice in a row before opening the document - notquite acceptable for a production system. You can also choose to output in textformat, or if you've purchased the companion product, Aspose.PDF, you canchoose to output to PDF just as easily by specifying SaveFormat.FormatAsposePdf.

 

'Instantiate and configure the Aspose.Word object.

Dim word AsWord = New Word

Dim doc AsDocument = _

  word.Open(MapPath(".") +"MyTest.doc")

 

'Fill the fields in the document with user data.

doc.MailMerge.Execute(_

   New String() {"FirstName","LastName"}, _

   New Object() {"Steve", "Orr"})

 

'Send the document in Word format to the user's browser.

doc.Save("MyTest.doc",_

  SaveFormat.FormatDocument, _

  SaveType.OpenInBrowser, _

   Me.Response)

Figure1: This code"fills in the blanks" of an existing Word document and allows it to bedownloaded into the user's browser.

 

If youwant a repeatable table of data, instead of (or in addition to) merely fillingin a few disparate fields, you can output an entire formatted DataSet,DataTable, DataReader, or DataView with one line of code:

 

MyDoc.MailMerge.ExecuteWithRegions(MyDataTable)

 

You canalso designate repeatable merge mail regions that will be repeated for eachrecord in a datasource. For example, a table row can be marked as a repeatableregion to cause the table to grow dynamically to accommodate all the data. Ifyou don't use mail merge regions you can cause the whole document to berepeated for each record, which might be handy for quick and simple mass mailings.

 

IntuitiveObject Model

Theobject model of Aspose.Word is similar to the object model of Word itself, soyou should feel right at home if you've done any Office automation with Word.Although you won't find every Word object, you'll find many of the most usefuland familiar ones, such as Document, Section, Range, Bookmark, and FormField.

 

Once theAspose.Word object library has been referenced from a new ASP.NET applicationin Visual Studio.NET, it only takes several lines of code to output a simpledocument from scratch. Import the Aspose.Word namespace and input the VB.NETcode shown in Figure 2.

 

Dim word AsWord = New Word

Dim doc AsDocument = word.Open(MapPath(".") + "blank.doc")

Dim builder AsDocumentBuilder = New DocumentBuilder(doc)

 

'Specify font formatting before adding text.

builder.Font.Size= 18

builder.Font.Bold= True

builder.Font.Name= "Garamond"

builder.Underline= Underline.Thick

builder.Font.Color= System.Drawing.Color.Green

builder.Write("Hello")

 

'Specify different formatting for next section.

builder.Font.Bold= True

builder.Underline= Underline.Dotted

builder.Font.Color= System.Drawing.Color.DarkBlue

builder.Writeln("World!")

 

'Send the document in Word format to the client browser.

doc.Save("MyTest.doc",_

  SaveFormat.FormatDocument, _

  SaveType.OpenInWord, _

   Me.Response)

Figure2: The objectmodel of Aspose.Word is very similar to the object model of Word, so you shouldfeel right at home if you've done any Office automation with Word.

 

Thefirst two statements simply instantiate the Aspose.Word object, and creates aDocumentBuilder object, which will be used to craft the document from theground up. The code then goes on to specify font settings, before outputtingthe first text. Then different font settings are set for the next section oftext. Finally, the document is output to the client machine, which then opensin Word.

 

TheDocumentBuilder is a new object not found in the Word object model. Thisintuitive object can be used to create paragraphs, lists, tables, and more. Youcan use it to insert images or move to specific sections of a document.

 

Free Stuff

Afteryou download the free evaluation version of Aspose.Word and run the simpleinstallation, one of the first things you're likely to notice is the sample code.No matter what kind of document you need to generate, you're likely to findsimilar code in their samples that can be modified for your own needs. Thissample code is available in VB.NET and C#.

 

The APIdocumentation is sufficient, with the most important functionality beingcovered the most thoroughly. Every object, method, and property is referencedin the help file, with example code included in C# and VB.NET. It would be niceif the help documentation was integrated with Visual Studio.NET's help system,but the link is easy enough to find on your Startmenu. The local documentation is supplemented by online documentation,including a free forum full of common questions and answers. Aspose watchestheir forums closely for ideas to put in future versions of the product. This,combined with free upgrades, makes it a tempting value.

 

Thereare several editions of Aspose.Word available: Basic, Standard, Professional,Corporate, and Enterprise. Prices start at around $230 for one Basic license.Only the higher-end versions support such advanced functionality as headers andfooters and image support. You could shell out thousands for some fancy reportwriter suite, but for many projects I suspect this product is a much bettersolution.

 

Rating:

WebSite: http://www.aspose.com/Products/Aspose.Word/

Price: Starting around $230 USD

 

 

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like