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

标签 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 文件,所有“orient”属性都设置为横向。

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

最佳答案

OpenXML Word 文档是定义其内容、格式和元数据的 XML 文档的压缩集合。使用 AddAlternativeFormatImportPart 将 Word 文档合并在一起时,要合并到原始文档 (AltChunks) 中的 Word 文档将被复制到 zip 存档中,引用文档的 XML 元素将添加到 XML 文档定义中。然后,下次有人在 Microsoft Word(或任何其他 OpenXML 兼容文档编辑器)中打开生成的文档时,应用程序将处理 AltChunk 中的合并。在本例中,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);

关于c# - 使用 OpenXML SDK AddAlternativeFormatImportPart 后 Word 文档方向丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25392481/

相关文章:

c# - 设置应用程序 Hook - C#/ASP.NET

c# - 获取上传图像的尺寸?

ms-word - 将 doc 文件插入当前打开的文档中的光标位置(使用 insertFileFromBase64 )

android - 来自画廊/相机 Intent 的图片方向

ios - 旋转图像后更改设备方向时,UIImageView 变得非常拉伸(stretch)

c# - 在 C# 中调用 ruby​​ 脚本

java - 如何将 PDF 转换为 JSON/EXCEL/WORD 文件?

html - 在 html 中为 Chrome、Explorer 和 word 创建分页符

Android:根据屏幕尺寸限制 Activity 方向

c# - 使用 C# 使用 REST API