Apply style on Content Control in a Word Document using OpenXML

957 views Asked by At

I'm trying to generate Word documents using OpenXML SDK and Word Document Generator. I need to apply my custom style on ContentControls (Repeating Section).

For Recursive Placeholders, I use

foreach (var item in list)
{
    var datacontext = new OpenXmlElementDataContext()
    {
        Element = openXmlElementDataContext.Element,
        DataContext = item.Value
    };
    var clonedElement = CloneElementAndSetContentInPlaceholders(datacontext);
    SetContentOfContentControl(clonedElement, item.Value);
}
openXmlElementDataContext.Element.Remove();

I need to apply my style on this element. How to I can do ?

I try to see generated code with "Open XML SDK 2.5 Productivity Tool for Microsoft Office" to inspire me:

var moduleDatacontext = new OpenXmlElementDataContext()
{
    Element = openXmlElementDataContext.Element,
    DataContext = module.Valeur
};
var moduleClonedElement = CloneElementAndSetContentInPlaceholders(moduleDatacontext);

var sdtProperties1 = new SdtProperties();
var styleId1 = new StyleId() { Val = "FormationTitre2" };

ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
RunFonts runFonts1 = new RunFonts() { ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };

paragraphMarkRunProperties1.Append(runFonts1);

sdtProperties1.Append(styleId1);
sdtProperties1.Append(paragraphMarkRunProperties1);

Run run1 = new Run() { RsidRunProperties = "00C463E5" };

RunProperties runProperties1 = new RunProperties();
RunFonts runFonts2 = new RunFonts() { ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };

runProperties1.Append(runFonts2);

run1.Append(runProperties1);

moduleClonedElement.Append(sdtProperties1);
moduleClonedElement.Append(run1);

When I open the generated document, I have this error :

We're sorry. We can't open "...docx" because we found a problem with its contents.

I validate the document and I can see 15 errors: http://imagizer.imageshack.us/a/img633/1176/7QX5So.png

Full Size

1

There are 1 answers

0
Andres Talavera On BEST ANSWER

I've found the solution. I search first paragraph and apply my custom style on it.

// clone element
var clonedElement = CloneElementAndSetContentInPlaceholders(datacontext);

// search the first created paragraph on my clonedElement
Paragraph p = clonedElement.Descendants<Paragraph>().FirstOrDefault();
if (p != null)
    p.PrependChild<ParagraphProperties>(new ParagraphProperties());
// get the paragraph properties
ParagraphProperties pPr = p.Elements<ParagraphProperties>().First();
// apply style
pPr.ParagraphStyleId = new ParagraphStyleId { Val = "FormationTitre2" };
// set content of content control
SetContentOfContentControl(clonedElement, item.Value);