2
votes

I am attempting to merge several Word documents together into a single Word document. I am using the AltChunk capability from Microsoft's OpenXML SDK 2.5. The final report needs to be in landscape orientation, thus we have put each component document into landscape mode. I am merging the documents using the following code.

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();
    }
}

When I run this code, the final output document has a mix of landscape and portrait orientation if the component documents each have at least one section break.

The DocumentWriter.SetPrintOrientation() method is implemented according to instructions from MSDN. It seems to have no effect on the actual orientation of the document. I have also examined the underlying XML files, and all "orient" attributes are set to landscape.

Is there some configuration option or API call I can use to ensure the final document will have landscape orientation across all sections?

1

1 Answers

2
votes

An OpenXML Word document is a zipped collections of XML documents that define its content, formatting, and metadata. When merging Word documents together using AddAlternativeFormatImportPart, the Word documents being merged into the original document (AltChunks) are copied into the zip archive, and XML elements referencing the documents are added into the XML document definition. Then, the next time anyone opens the resulting document in Microsoft Word (or any other OpenXML compatible document editor), the application handles merging in the AltChunks. In this case, Microsoft Word 2010 (the version we are using) has a bug causing Word to ignore some formatting information defined in Word document sections. One of these pieces of information is orientation, making the AltChunk approach ineffective at preserving orientation information.

Instead, we used DocumentBuilder from the OpenXml Power Tools project. This resulted in much simpler code that solved our problem in two lines:

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