Does DocX allow me to insert multiple templates into one document?

Feb 23, 2011 at 10:17 PM

Hi Cathal and docX users, First of all just want to thank you for all the time and stress you've removed from my programming tasks with this library! Its truely amazing!

The question I ask, I'm trying to create a document with a template inserted multiple times, changing custom fields everytime it's inserted. When I do this and save the templates into individual files, more or less identical to your example invoice template, its works fine. However, If I create a master document instance then keep opening my template instance, changing the fields and finally inserting into my master document, my code runs fine and the file is saved. Unfortunately when I try opening my word document I get a error saying:

'Cannot be opened because there are problems with the contents. The file is corrupt and cannot be opened'

I can then click 'OK' and attempt to recover the document which shows all the data I expect, but unsure how to rectify the error I'm getting when opening the document.

Below is the sudo code and Method i've written for inserting the template multiple times into my master file:

1. create master document.

2. open template document.

3. loop through datatable rows calling the 'CreateInvoiceFromTemplate' Method.

private void CreateInvoiceFromTemplate(DocX document, DocX template, DataTable accounts, DataRow personalDetails)

            template.AddCustomProperty(new CustomProperty("ClientName", string.Format("{0} {1} {2}",personalDetails["Title"],personalDetails["Forname"],personalDetails["Surname"])));
            if(personalDetails["Address1"] != DBNull.Value) template.AddCustomProperty(new CustomProperty("Address1", personalDetails["Address1"].ToString()));
            if(personalDetails["Address2"] != DBNull.Value) template.AddCustomProperty(new CustomProperty("Address2", personalDetails["Address2"].ToString()));
            if(personalDetails["Address3"] != DBNull.Value) template.AddCustomProperty(new CustomProperty("Address3", personalDetails["Address3"].ToString()));
            if(personalDetails["Address4"] != DBNull.Value) template.AddCustomProperty(new CustomProperty("Address4", personalDetails["Address4"].ToString()));
            if(personalDetails["Postcode"] != DBNull.Value) template.AddCustomProperty(new CustomProperty("PostCode", personalDetails["Postcode"].ToString()));


4. Save document


Any help or hints would be greatly appreciated.

Thanks, Andrew