Document Generation with OOXML Part 3

In a previous post I explained how the Document Generator library can be used with Word templates and how to use the styles defined in those templates. Besides using the styles in the template it should also be possible to insert specific content in the document. For example placing the title in the header of a document or the author of the document. Before Word 2007 and OOXML you could use fields or create a WordML file with your own tags in it to insert content programmaticly. With OOXML you can use Content Controls for this.
The Document Generator uses content controls to insert a information at specified places in the documents. The content control types that are supported are:

  1. Text
  2. Rich Text
  3. Picture

The content control must be defined in the OOXML document or template that is used with the library. This can be done from the Developer Tab in Word 2007 or higher.

//Create text document from a template
var document = TextDocument.Create("MyDocument.docx", "MyTemplate.dotx", true);

//Insert the author of document, where Author is the name of the content
//control and Shakespeare is the text that will be inserted.
document.ReplaceCustomTag("Author", "W. Shakespeare");

//Insert an image of the author, where AuthorImage is the name of the content
//control and Shakespeare.png is the image.
document.ReplaceCustomTag("AuthorImage", "Shakespeare.png");

The method name is the same for images and text. The library will determine the type of content control to find depending on the type that is given. When a string is given the library will look for a Picture content control and when a string is provided it will look for a Text control.
When it cannot find a match on both name and type it will ignore the replacement.
When a content control is defined more then once in the document it will insert the content for all the controls.

In this post I showed you how you can insert content such as text and images at specific places in documents by using Content Controls.
In the next part I will show how you can create list and tables.

Leave a Reply

Your email address will not be published. Required fields are marked *

* Copy This Password *

* Type Or Paste Password Here *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>