Search code examples
xmlvb.netms-wordopenxml-sdk

Adding a .docx Word document to a word processing document using Open XML SDK


I just started using Open XML and am unsure how to insert a file (.docx/.doc) into a word processing document.

I've tried something like the following but get a unknown document error when launching the document with Word 2016.

Using wordprocessingDocument As WordprocessingDocument = WordprocessingDocument.Open(memoryStream, True)
    Using addProcessDoc As WordprocessingDocument = WordprocessingDocument.Open(itemView.Items(i).SubItems(3).Text.ToString, True)
        Dim tempPart = addProcessDoc.MainDocumentPart
        wordprocessingDocument.AddPart(tempPart) 'ERROR: Specified argument was out of the range of valid values.
    End Using
End Using

Solution

  • Inserting an entire document can be achieved using an AltChunk (as described by @VarunRathore here, which allow to embed content such as HTML or OpenXML into another document:

    Imports System.Linq
    Imports System.IO
    Imports DocumentFormat.OpenXml.Packaging
    Imports DocumentFormat.OpenXml.Wordprocessing
    
    Class Program
    
        Private Shared Sub Main(args As String())
    
            Dim targetFileName As String = "c:\Users\Public\Documents\Target.docx"
            Dim sourceFileName As String = "c:\Users\Public\Documents\Source.docx"
            Dim templateFile As String = "c:\Users\Public\Documents\Template.docx"
    
            ' create target file from template
            File.Delete(targetFileName)
            File.Copy(templateFile, targetFileName)
    
            ' open target document
            Using myDoc As WordprocessingDocument = 
                WordprocessingDocument.Open(targetFileName, True)
    
                Dim altChunkId As String = "AltChunkId1"
                Dim mainPart As MainDocumentPart = myDoc.MainDocumentPart
                Dim chunk As AlternativeFormatImportPart = 
                    mainPart.AddAlternativeFormatImportPart(
                        AlternativeFormatImportPartType.WordprocessingML, 
                        altChunkId)
    
                ' feed the source document into the alt chunk
                Using fileStream As FileStream = File.Open(sourceFileName, FileMode.Open)
                    chunk.FeedData(fileStream)
                End Using
    
                ' insert alt chunk after last paragraph of body
                Dim altChunk As New AltChunk()
                altChunk.Id = altChunkId
                mainPart.Document.Body.InsertAfter(
                    altChunk, 
                    mainPart.Document.Body.Elements(Of Paragraph)().Last())
    
                ' save the document
                mainPart.Document.Save()
            End Using
    
        End Sub
    
    End Class