Styles are typically used to change the formatting consistently across a complete document. Specifically when merging templates using the MailMerge class, it makes sense to keep all styles in a separate master template in order to apply those styles to all other templates.
This sample project shows how to apply the paragraph styles of a master template to a loaded document based on style names. The following screenshot shows a document with 3 paragraphs in different TextParts styled with the custom paragraph styles Heading 1 (in the main text and text frame) and Heading 2 (in the header).
When clicking the menu item Apply Master Template, the extension method ApplyMasterTemplate is called by passing a master template document as a parameter:
textControl1.ApplyMasterTemplate("master.tx", StreamType.InternalUnicodeFormat); |
This master template contains two styles with the same names Heading1 and Heading2:
The following extension method stores all paragraphs with the applied style names. Using a temporary ServerTextControl instance, the master template is loaded. All styles with the same name are replaced with the style from the master template. Finally, they are applied to all stored paragraphs.
public static bool ApplyMasterTemplate(this TextControl textControl, | |
string masterTemplate, StreamType streamType) | |
{ | |
// list to keep all style names | |
List<ParStyle> styles = new List<ParStyle>(); | |
using (ServerTextControl serverTextControl = | |
new ServerTextControl()) | |
{ | |
serverTextControl.Create(); | |
// load the master template | |
try { | |
serverTextControl.Load(masterTemplate, streamType); | |
} | |
catch { | |
return false; | |
} | |
// loop through all paragraphs to store the used | |
// style names | |
foreach (IFormattedText textPart in textControl.TextParts) | |
{ | |
foreach (Paragraph par in textPart.Paragraphs) | |
{ | |
ParStyle style = new ParStyle(par, par.FormattingStyle); | |
styles.Add(style); | |
} | |
} | |
// loop through all paragraph styles and | |
// replace the style, if the name already exist | |
foreach (ParagraphStyle style in serverTextControl.ParagraphStyles) | |
{ | |
if (textControl.ParagraphStyles.GetItem(style.Name) != null) | |
{ | |
textControl.ParagraphStyles.Remove(style.Name); | |
// create a new style and add it to TextControl | |
ParagraphStyle newStyle = new ParagraphStyle(style); | |
textControl.ParagraphStyles.Add(newStyle); | |
} | |
} | |
} | |
// apply the stored style names to all paragraphs | |
foreach (ParStyle par in styles) | |
{ | |
par.Paragraph.FormattingStyle = par.StyleName; | |
} | |
return true; | |
} |
After the styles have been replaced, the applied styles are visible in the original document:
Download the sample from GitHub and test it on your own.