Search code examples
c#.netopenxmlopenxml-sdkwordprocessingml

How to insert a docx document into another docx at certain position without altchunk


Is there a way to insert a whole docx document into another one without using altchunks? The problem is that after insertion I have to merge the resulted doc with another one using DocumentBuilder from OpenXml Powertools and it does not support documents that contains altchunks.


Solution

  • Ok, so I managed to come up with a solution. In order to insert a document at a certain position I split the original document into two sources for the DocumentBuilder, then I created a source from the document to be inserted. In the end I built a new document with these 3 sources and it seems to be working just fine.

    I am looking for the paragraph to split the original document by a placeholder, for example "@@insert@@".

    Bellow is the code if anyone needs it.

    var paragraph = DestinationDocument.MainDocumentPart.Document.Descendants<OpenXmlParagraph>().FirstOrDefault(item => item.InnerText.Contains(placeHolder));
    
                    if (paragraph != null)
                    {
                        var idOfParagraph =
                        DestinationDocument.MainDocumentPart.Document.Descendants<OpenXmlParagraph>()
                            .ToList()
                            .IndexOf(paragraph);
    
                        //save and close current destination document
                        SaveChanges(destinationFilePath, false);
    
                        var sources = new List<Source>();
    
                        var originalDocument = new WmlDocument(destinationFilePath);
    
                        sources.Add(new Source(originalDocument, 0, idOfParagraph, true)); // add first part of initial document
    
                        var documentToBeInserted = new WmlDocument(docFilePath);
                        sources.Add(new Source(documentToBeInserted, true)); // add document to be inserted
    
                        sources.Add(new Source(originalDocument, idOfParagraph + 1, true)); // add rest of initial document
    
    
                        var newDestinationDocument = DocumentBuilder.BuildDocument(sources); // build new document
                        newDestinationDocument.SaveAs(destinationFilePath); // save
    
                        // re-open destination document
                        DestinationDocument = WordprocessingDocument.Open(Path.GetFullPath(destinationFilePath), true);
                    }