用分页符替换分节符

时间:2016-05-31 10:47:55

标签: c# openxml openxml-sdk wordprocessingml power-tools-for-xml

我正在尝试使用OpenXml Powertools的DocumentBuilder将一些word文档合并到一个word文档中。 这是用于合并的代码:

var sources = new List<Source>();
                foreach (var doc in documents)
                {
                    var wmlDoc = new WmlDocument(doc.Path);

                    sources.Add(new Source(wmlDoc, doc.PageBreak));
                }

                var newDestinationDocument = DocumentBuilder.BuildDocument(sources);

documents中的每个对象都包含一个文档路径和一个bool,表示我是否要在文档后插入分页符。

这段代码正在运行,但问题是我得到了一个分节符而不是分页符,我知道Source构造函数中的第二个参数表示一个分节符bool,但我需要一个Page Break而不是

这是结果文件在合并后包含的内容: enter image description here

我需要这样的事情:

enter image description here

我无法使用altChunksInterop或任何付费图书馆。

1 个答案:

答案 0 :(得分:1)

你必须添加

<w:br w:type="page" />

表示要与分页符分隔的文档的文档段落的开头或结尾。

在您应用代码之前,请尝试以下操作 -

WordprocessingDocument myDoc = WordprocessingDocument.Open(@"file path", true);
MainDocumentPart mainPart = myDoc.MainDocumentPart;
OpenXmlElement last = myDoc.MainDocumentPart.Document
    .Body
    .Elements()
    .LastOrDefault(e => e is Paragraph || e is AltChunk);
last.InsertAfterSelf(new Paragraph(
    new Run(
        new Break() { Type = BreakValues.Page })));
mainPart.Document.Save();

我选择了文件的最后一段。您可以根据需要选择对文档的第一个执行相同的操作。

上面的代码将添加<w:br w:type="page" />,这会添加手动分页符。

您还可以尝试将<w:pageBreakBefore/>用于指定客户端(MS Word等)的文档的最后一段,该标记后面的段落将在新页面上呈现。