使用OpenXML SDK AddAlternativeFormatImportPart后Word文档方向丢失

时间:2014-08-19 20:33:18

标签: c# ms-word orientation openxml

我正在尝试将多个Word文档合并到一个Word文档中。我正在使用Microsoft的OpenXML SDK 2.5中的AltChunk功能。最终报告需要以横向为导向,因此我们将每个组件文档放入横向模式。我正在使用以下代码合并文档。

for (int i = 0; i < otherDocs.Length; i++)
{
    using (var headerDoc = WordprocessingDocument.Open(headerPath, true))
    {
        var mainPart = headerDoc.MainDocumentPart;

        string altChunkId = "AltChunkId" + i;
        var chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);

        using (var fileStream = File.Open(otherDocs[i], FileMode.Open))
        {
            chunk.FeedData(fileStream);
        }

        var altChunk = new AltChunk();
        altChunk.Id = altChunkId;
        mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());
        mainPart.Document.Save();

        DocumentWriter.SetPrintOrientation(headerDoc, PageOrientationValues.Landscape);

        headerDoc.Close();
    }
}

当我运行此代码时,如果组件文档至少有一个分节符,则最终输出文档会混合使用横向和纵向。

DocumentWriter.SetPrintOrientation()方法是根据MSDN的说明实现的。它似乎对文档的实际方向没有影响。我还检查了基础XML文件,以及所有&#34; orient&#34;属性设置为横向。

我可以使用一些配置选项或API调用来确保最终文档在所有部分都具有横向方向吗?

1 个答案:

答案 0 :(得分:2)

OpenXML Word文档是XML文档的压缩集合,用于定义其内容,格式和元数据。使用AddAlternativeFormatImportPart将Word文档合并在一起时,将合并到原始文档(AltChunks)中的Word文档复制到zip存档中,并将引用这些文档的XML元素添加到XML文档定义中。然后,下次任何人在Microsoft Word(或任何其他OpenXML兼容的文档编辑器)中打开生成的文档时,该应用程序将处理AltChunks中的合并。在这种情况下,Microsoft Word 2010(我们使用的版本)具有bug causing Word to ignore some formatting information defined in Word document sections。其中一条信息是方向性,使得AltChunk方法在保留方向信息方面无效。

相反,我们使用了OpenXml Power Tools project中的DocumentBuilder。这导致更简单的代码解决了我们的问题,分为两行:

var sourceList = documentPaths.Select(doc => new Source(new WmlDocument(doc), true)).ToList();
DocumentBuilder.BuildDocument(sourceList, outputPath);