@derek444 Actually ControlChar.LineFeed (\n
) character is not normally used in MS Word especially in Run
node text. If you need to have multiline text in the run you should use ControlChar.LineBreak (\v
) character - soft line break.
The code like the following:
string text = "test\ntest";
Document doc = new Document();
Run r = new Run(doc);
r.Text = text;
doc.FirstSection.Body.FirstParagraph.AppendChild(r);
doc.Save(@"C:\Temp\out.docx");
Produces the following XML representation in DOCX:
<w:p w:rsidR="00A77B3E">
<w:r>
<w:t>
test
test
</w:t>
</w:r>
</w:p>
As you can see line break is there, but MS Word interprets such line break as whitespace. This is an expected behavior.
If you use \v
instead of \n
in the text
string, a special <w:br />
tag is inserted, which corresponds a soft line break:
<w:p w:rsidR="00A77B3E">
<w:r>
<w:t>test</w:t>
<w:br />
<w:t>test</w:t>
</w:r>
</w:p>
Also, you can use ControlChar.ParagraphBreak (\r
) character, the paragraph break character inserted into Run.Text
will not actually produce paragraph break, but insted a special <w:cr />
break will be inserted:
string text = "test\rtest";
<w:p w:rsidR="00A77B3E">
<w:r>
<w:t>test</w:t>
<w:cr />
<w:t>test</w:t>
</w:r>
</w:p>
If you need that \n
character produces an actual paragraph break, you can use DocumentBuilder to insert the content. For example:
string text = "test\ntest";
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write(text);
doc.Save(@"C:\Temp\out.docx");
produces two paragraphs:
<w:p w:rsidR="00A77B3E">
<w:r>
<w:t>test</w:t>
</w:r>
</w:p>
<w:p w:rsidR="00A77B3E">
<w:r>
<w:t>test</w:t>
</w:r>
</w:p>
The same output will be produced with the following strings:
string text = "test\rtest";
string text = "test\r\ntest";