Question

We've just discovered that Rich Text Content Controls does not allow line breaks.

We have several thousands of word document that are used as templates. I need a way to programmatically replace each Rich Text content control whit a Plain Text one and allow line breaks.

There seems to be no attribute in the XML that denotes a Rich text content control from a plain text one.

Could I simply add :

<w:text w:multiLine="1"/>

To each content control or should I delete the old one and create a new one ?

UPDATE 1 : according to this post :

There is a child element of the w:stdPr element that indicates the type of content control. The default type of content control is Rich Text, so if this is the type of the content control you will not see this child element.

If the content control type is plain text, there will be a child element.

Was it helpful?

Solution

Adding a new child element of type SdtContentText is indeed the solution.

I'm using the OpenXML Power Tools.

The following code is taken from here :

public static class ContentControlExtensions
{
    public static IEnumerable<OpenXmlElement> ContentControls(
        this OpenXmlPart part)
    {
        return part.RootElement
            .Descendants()
            .Where(e => e is SdtBlock || e is SdtRun);
    }

    public static IEnumerable<OpenXmlElement> ContentControls(
        this WordprocessingDocument doc)
    {
        foreach (var cc in doc.MainDocumentPart.ContentControls())
            yield return cc;
    }
}

And then :

    using (WordprocessingDocument doc =
                 WordprocessingDocument.Open(sourceFile, true))
    {
        foreach (var cc in doc.ContentControls())
        {
            SdtProperties props = cc.Elements<SdtProperties>().FirstOrDefault();
            Tag tag = props.Elements<Tag>().FirstOrDefault();
            SdtContentText text = props.Elements<SdtContentText>().FirstOrDefault();
            if (text == null)
            {
                text = new SdtContentText();
                text.MultiLine = new OnOffValue(true);
                cc.AppendChild<SdtContentText>(text);
            }
            if (tag != null)
                Console.WriteLine(tag.Val);
        }

        doc.MainDocumentPart.Document.Save();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top