C#Word OpenXml SDK-向运行中添加文本会修剪空格



我正试图使用OpenXml SDK将文本运行添加到Word中现有的段落中,但每次我这样做都会导致"修剪";我添加的文本。

例如

Run newRun = newRun();
newRun.AppendChild(new Text("Hello "));
paragraph.AppendChild(newRun);
Run newRun = newRun();
newRun.AppendChild(new Text(" World"));
paragraph.AppendChild(newRun);
// the resulting paragraph contains "HelloWorld" as the text

我还检查了生成的结果Run的XML,其中清楚地包括";空间";字符:

<w:t xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">Hello  </w:t>

我已经尝试注入'\u0020'unicode值,以及一个"空";运行,只包含一个空间,但似乎什么都不起作用。

有人知道其中的诀窍吗?

您可以使用SpaceProcessingModeValues枚举。

var text   = new Text("Hello ");
text.Space = SpaceProcessingModeValues.Preserve;

通过几种扩展方法,您可以自动处理它,也可以换行:

public static Text Append(this Run run, string text)
{
Text lastText = null;
if (text == null)
{
lastText = new Text();
run.Append(lastText);
return lastText;
}
var lines = text.Split(new[] { Environment.NewLine }, StringSplitOptions.None );
for (int index = 0; index < lines.Length; index++)
{
if (index != 0)
run.AppendBreak();
var line = lines[index];
lastText = new Text(line);
if (line.StartsWith(" ") || line.EndsWith(" "))
lastText.Space = SpaceProcessingModeValues.Preserve;
run.Append(lastText);
}
return lastText;
}
public static void AppendBreak(this Run run)
{
run.Append(new Break());
}

在发布(已经尝试了几个小时(5分钟后,我翻白眼,发现答案是多么典型

答案是添加XMLXML:space="保存">属性,否则会修剪空格。

newRun.InnerXml = $"<w:t xml:space="preserve" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">{text}</w:t>";

最新更新