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.

Document Generation with OOXML Part 2

When creating a document from Word templates are used when creating documents. These can be default templates or templates created by users. It is their for essential that these templates can be used when generating OOXML documents. With the Document Generator library templates can be loaded when a new document is created.

//Load a template from file. document is the name of the new document.
//template is the name and full path of the template file
//true indicates that the document can override documents with the same name.
var document = TextDocument.Create(document, template, true);

//Load a template from a stream
using (var stream = new FileStream(templateFile, FileMode.Open, FileAccess.Read))
{
    using (var reader = new StreamReader(stream))
    {
        //stream is the stream of the template.
        var document = TextDocument.Create(stream);
    }
}

Once the template is loaded the styles defined in the template can be used. As long as the styles are the default for the header and the paragraphs only the level needs to be defined.

//This adds a new paragraph with the paragraph text and heading text.
//The styles used are Heading2 and Normal2. When the styles cannot be found then
//Heading1 and normal will be used as styles.
var paragraph = document.AddParagraph("Paragraph Text", "Heading Text", 2);

Templates can also define custom styles. When the name of the style in the template is known the style can be used with the Document Generator library.
The style can be applied to paragraphs and headers

//Creates a paragraph and assigns it the MyParagraphStyle.
var paragraph = document.AddParagraph("This is the paragraph", "MyParagraphStyle");

//Creates a paragraph and assigns it the MyParagraphStyle.
//and gives it a header with the style MyHeaderStyle
var paragraph = document.AddParagraph("This is the paragraph", "Header for Paragraph", "MyParagraphStyle", "MyHeaderStyle");

In this post I showed you how you can use a template when creating documents and how to use custom styles in the template.
In the next part I will show how you can replace content in documents using Content Controls.

Document Generation with OOXML Part 1

For a while I have been working on a private project called Document Generator. Document Generator is a .Net library for creating text documents in OOXML and in ODF. With the library you can create an outline for a document with paragraphs, image, etc and generate an OOXML or ODF document. I recently thought it was mature enough to make it a final release. You can find the project at Codeplex .

To explain the library I decided to write a serie of articles and this is the first part. It will explain how to get started with the library.

Pre-requisites

The library is using OOXML SDK 2.5 for creating OOXML documents and this requires .Net Framework 4.0.

Installation

Document generator does not require any installation. Download the zip file with the latest version and extract the contents to a directory of choice. The zip file contains:

  • DocumentGenerator.dll
  • DocumentFormat.OpenXml.dll (This is the dll for the OOXML SDK 2.5)
  • ICSharpCode.SharpZipLib.dll (This dll is required for creating ODF files)

Setup the project

  1. Create a new console project in Visual Studio
  2. Add a reference to the dll’s for the document generation:
    • DocumentGenerator.dll
    • DocumentFormat.OpenXml.dll
    • ICSharpCode.SharpZipLib.dll

 Generate Documents

  1. The first step in generating a document is to create a Textdocument object. This is the container of the document to generate and is the same for OOXML and ODF documents. For OOXML documents it is also possible to start from a template (.dotx) or an existing document (.docx).
  2. //Create a new text document
    var document = TextDocument.Create();

    //Create a new text document with a file name (including the file location)
    //The Boolean indicates whether the file can be overridden if a file
    //with the same name is found.
    var document = TextDocument.Create("MyFilename", true);

    //Create a new text document based on a template
    var document = TextDocument.Create("MyFilename","myTemplate", true);

    //Open an existing ooxml document.
    var document = TextDocument.Open("MyFile");
  3. When the text document is created headers and paragraphs can be added.
  4. //Add a paragraph to the document. Level is an integer used for the style.
    //of the paragraph, e.g. level "0" set style "Normal"
    //and level "1" style "Normal1"
    document.AddParagraph("The paragraph text", level);

    //Add a paragraph and a header. Level is an integer is used for the style.
    //E.g. level "1" applies "Header1" level "2" applies "Header2"
    document.AddParagraph("The header","The paragraph text", level);

    //Add only a header. Leaving the text for the paragraph empty
    //will add only a header.
    document.AddParagraph("The header",string.Empty, level);
  5. Finally the document can be save in OOXML or ODF format.
  6. //First set a filename (including the file location), if not already set
    document.Filename = "MyFile";

    //Save the document in OOXML format.
    document.Save(DocumentType.OOXMLTextDocument);

    //Save the document in ODF format.
    document.Save(DocumentType.ODFTextDocument);

In this post I showed you how you can create a document, add contents to the document and save this document in either OOXML or ODF format.
I also showed how you can use a dotx template or an existing ooxml document to create new documents.

In the next post I will go through some more advanced features such as creating tables and lists and replace content in OOXML documents.
If you cannot wait for these posts you can have a look a the DocumentGeneratorTest project in Codeplex to see the use of these features.

Caching bitmaps in the HttpContext.Current.Cache

I was working on a website that is generating images on the fly. Generating these images takes some time and therefore they needed to be cached.
So I wrote this small piece of code, just for this:


public static void Cache(Bitmap bmp, String key)
{
  HttpContext.Current.Cache.Insert(key, bmp, null,
    System.Web.Caching.Cache.NoAbsoluteExpiration,
    System.Web.Caching.Cache.NoSlidingExpiration,
    System.Web.Caching.CacheItemPriority.Normal, null);
}
 
public static Bitmap Fetch(String key)
{
  return HttpContext.Current.Cache.Get(key) as BitmapCache;
}

That was easy and straight forward, however this was one of these cases where things are not what they seem to be. Generating the image went without any issue and showed on the webpage. However, getting the image from the cache did not return an image but an error message in stead. The error message was ArgumentException: Parameter is not valid.

When trying to view the properties of the bitmap in debug mode, all of the properties showed the same error in stead of their actual value. After scratching my head a few times I found why, the bitmap was disposed. The above code puts a reference to the bitmap in the cache, so when the bitmap gets disposed it is not longer accessible from the cache. I first thought of creating a copy of the bitmap and put that in the cache, but then I found a much nicer solution on the web: Store the bitmap as a byte array.

Now the code for caching the bitmap looks like


public static void Cache(Bitmap bmp, String key)
{
  //Store the image as a byte array. The bitmap its self maybe disposed
  //and this will retrieve a disposed image from the chache.
  using (var ms = new MemoryStream())

  bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
  HttpContext.Current.Cache.Insert(key, new BitmapCache(ms.ToArray()), null,
      System.Web.Caching.Cache.NoAbsoluteExpiration,
      System.Web.Caching.Cache.NoSlidingExpiration,
      System.Web.Caching.CacheItemPriority.Normal, null);
  }

public static Bitmap Fetch(String key)
{
  byte[] bitmapAsArray= HttpContext.Current.Cache.Get(key) as BitmapCache;
  Bitmap bmp = null;
  try
  {
    using (var ms = new MemoryStream((byte[])bc.bitmapAsArray))
    {
      bmp = Bitmap.FromStream(ms) as Bitmap;
    }
  catch(Exception)
  {
    return null;
  }
  return bmp;
}

and this works everytime. There is a slight overhead in transforming the byte[] to a bitmap, but this is much less then generating the bitmap everytime. When you want to output the image direct you could even stream the byte[] directly and thus avoiding the overhead of transforming it to the bitmap.

Enum.HasFlag() versus Bitwise comparison

Call me a bit slow, but I recently discovered that Microsoft has implemented an HasFlag method on the Enum class since .Net 4. The method is meant as replacement for the bitwise comparison between values of an enumeration that has the FlagAttribute. For more information about the the FlagAttribute and bitwise comparison you can have a look at this blog.

For a project I am working on I am using the bitwise comparison extensively, so using the HasFlag method would make the code much more readable. Before using it I wanted to get some more information about how the HasFlag method works and I found this article. It shows the inner workings of the method, but also mentions that there is a performance cost to pay. However it does not mention what the cost is.

I therefor did my own test to see what the performance overhead would be and if it was worth to change. Continue reading