Sunday, 9 September 2012

Integrating Word into a web application

After the success of integrating excel into my website, I wanted to try my hand at expanding the word integration options.

We already had quite extensive abilities to generate documents in html, pdf and rtf format (using an old version of the iTextSharp library).

I wanted to have functionality where more experienced users could download a template file, customise it in any way they like (for example adding their own text, logos etc) and then upload it back to our server and use it as a template.

Again a project on codeplex came to the rescue, Word Doc Generator.

This uses document placeholders, and you can write your own class that inherits from the DocumentGenerator class to output the data you want.

So a template file like this can be used to generate a custom booklet like this.

You can test this on the website, by creating your own logon, selecting some exercises, generating a booklet and then using the word templates tab.

I had to make some modifications to the code to enable it to handle images as part of the document placeholders.

I gave a presentation to the Newcastle Coders group in September and was asked by several people to post how I modified the code for images so I will post the details here.

This is based on the version released on the 24th January. It is a bit of hack, but it might be useful for you (or at least give you a starting point).

In the WordDocumentGenerator.Library project, I had to modify the DocumentGenerator and OpenXmlHelper classes. I include links to the changed files.

First Hack

Add a reference DocumentFormat.OpenXml.Drawing to OpenXmlHelper as well as a reference to the document being handled (this is needed to add images).

Second Hack

Modify the method SetContentOfContentControl, to handle jpg images (this could be any image type).

Third Hack

Add two helper methods to add the image.

Final Hack

Modify the SetContentInPlaceHolders method in the DocumentGenerator class so it passes in a link to the main document.

Amend as necessary and compile into the WordDocumentGenerator.library dll.

When you are making your own documentgenerator class libary, pass in the filename of the image as your content.

Email me if I have missed something and I will amend my blog post.

1 comment:

  1. Just wanted to thank you for posting this. Was very useful for extending my implementation of the Word Document Generator