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.
//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.
//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
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.