Новая строка в Rich Text Контент управления Word открыть XML - PullRequest
0 голосов
/ 19 октября 2019

У меня есть документ Word с Rich text Content Control.

. Я хочу добавить текст с новой строкой.

using (WordprocessingDocument theDoc = WordprocessingDocument.Open(docName, true))
 {
   MainDocumentPart mainPart = theDoc.MainDocumentPart;
   foreach (SdtElement sdt in mainPart.Document.Descendants<SdtElement>())
     {
        SdtAlias alias = sdt.Descendants<SdtAlias>().FirstOrDefault();
        if (alias != null)
          {
            string sdtTitle = alias.Val.Value;
            var t = sdt.Descendants<Text>().FirstOrDefault();
             if (sdtTitle == "Body")
               {
                 t.Text = "Welcome to Yazd With its winding lanes, forest of badgirs,\r\n mud-brick houses and delightful places to stay, Yazd is a 'don't miss' destination. On a flat plain ringed by mountains, \r\nthe city is wedged between the northern Dasht-e Kavir and southern Dasht-e Lut and is every inch a city of the desert." }
         }
     }
}

Я использую текст с \r\n, но недобавить новую строку.

1 Ответ

0 голосов
/ 22 октября 2019

Некоторые символы, такие как символы табуляции, новые строки и т. Д., Определяются специальным элементом XML.
Для вашего случая вам необходим элемент <w:br/>, поэтому попробуйте что-то вроде следующего:

using (WordprocessingDocument theDoc = WordprocessingDocument.Open(docName, true))
{
    MainDocumentPart mainPart = theDoc.MainDocumentPart;
    foreach (SdtElement sdt in mainPart.Document.Descendants<SdtElement>())
    {
        SdtAlias alias = sdt.Descendants<SdtAlias>().FirstOrDefault();
        if (alias != null && alias.Val.Value == "Body")
        {
            var run = sdt.Descendants<Run>().FirstOrDefault();
            run.RemoveAllChildren<Text>();

            var text = "Welcome to Yazd With its winding lanes, forest of badgirs,\r\n mud-brick houses and delightful places to stay, Yazd is a 'don't miss' destination. On a flat plain ringed by mountains, \r\nthe city is wedged between the northern Dasht-e Kavir and southern Dasht-e Lut and is every inch a city of the desert.";
            var lines = text.Split(new string[] { "\r\n" }, StringSplitOptions.None);

            foreach (var line in lines)
            {
                run.AppendChild(new Text(line));
                run.AppendChild(new Break());
            }

            run.Elements<Break>().Last().Remove();
        }
    }
}

Надеюсь, это поможет.

...