Search code examples
c#.netopenxmldocxopenxml-sdk

How to insert line break into Word (docx) document using OpenXMLPowerTools?


I'm writing a library which generates Word documents based on a template. Some text needs to be replaced with another text. Everything seems to be working, there is a TextReplacer class which may perform replacements.

The things become worse when I need to replace a single-line part of text with multiline text. Line breaks such as \n or \r\n are just pasted as text. I understand that this is expected as multiple lines of text must become separate tags (<w.p>..</w.p>, I suppose) in document.xml.

I think that simple solution is to replace all \n or \r\n in document with break tags before saving. I can do this with string.Replace(), but I don't think it is the best way to go. I want to use some built-in OpenXMLPowerTools library features, if it is possible. Or maybe other (free) OpenXML libraries.


Solution

  • I ended up with this:

    public static void ReplaceNewLinesWithBreaks(XDocument xDoc)
    {
        var textWithBreaks = xDoc.Descendants(W.t).Where(t => t.Value.Contains("\\r\\n"));
        foreach (var textWithBreak in textWithBreaks)
        {
            var text = textWithBreak.Value;
            var split = text.Replace("\\r\\n", "\\n").Split(new[] {"\\n"}, StringSplitOptions.None);
    
            textWithBreak.Value = string.Empty;
            foreach (var s in split)
            {
                textWithBreak.Add(new XElement(W.t, s));
                textWithBreak.Add(new XElement(W.br));
            }
            textWithBreak.Descendants(W.br).Last().Remove();
        }
    }
    

    Which may be also rewritten as helper method.

    But, it would be great if someone from OpenXmlPowerTools team will write an overload to TextReplacer which would accept IEnumerables for replacement.