Monday 28 January 2013

Open XML 2.0 and Word Processing

I am sure those who have tried his hands on Open XML SDK, must have used Word Content Control Toolkit available at codeplex.

The exe is prepared by Microsoft itself and pretty old but can be used to create word document quickly through code. It makes template creation for Mail Merge like solution very easy.

Use the tool to map your content controls with custom xml and use the below code to replace your content with xml data.

Below code has ContentXML variable that has required data.

using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(_templateDocument, 0, _templateDocument.Length);
                using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(ms, true))
                {

                    MainDocumentPart main = wordDocument.MainDocumentPart;
                    Document document = main.Document;
                    main.DeleteParts<CustomXmlPart>(main.CustomXmlParts);

                    //add and write new XML part
                    CustomXmlPart customXmlPart =   main.AddCustomXmlPart(CustomXmlPartType.CustomXml);
                    using (StreamWriter ts = new StreamWriter(customXmlPart.GetStream()))
                    {
                        ts.Write(ContentXML);
                    }

                    document.Save();
                }
              

References
 http://blogs.msdn.com/b/acoat/archive/2007/03/01/linking-word-2007-content-controls-to-custom-xml.aspx
http://msdn.microsoft.com/en-us/library/office/bb510135%28v=office.12%29.aspx