Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Microsoft Open XML SDL 2.0 append document to template document asp.net c#

My asp.net c# web-application is creating word documents by filling an existing template word document with data. Now I need to add a further existing documents to that document as next page.

For example: My template has two pages. The document I need to append has one page. As result I want to get one word document with 3 pages.

How do I append documents to an existing word document in asp.net/c# with the Microsoft Open XML SDK 2.0?

like image 884
raven_977 Avatar asked Jan 09 '14 10:01

raven_977


1 Answers

Use this code to merge two documents

using System.Linq;
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace altChunk
{
    class Program
    {
        static void Main(string[] args)
        {          
            string fileName1 = @"c:\Users\Public\Documents\Destination.docx";
            string fileName2 = @"c:\Users\Public\Documents\Source.docx";
            string testFile = @"c:\Users\Public\Documents\Test.docx";
            File.Delete(fileName1);
            File.Copy(testFile, fileName1);
            using (WordprocessingDocument myDoc =
                WordprocessingDocument.Open(fileName1, true))
            {
                string altChunkId = "AltChunkId1";
                MainDocumentPart mainPart = myDoc.MainDocumentPart;
                AlternativeFormatImportPart chunk = 
                    mainPart.AddAlternativeFormatImportPart(
                    AlternativeFormatImportPartType.WordprocessingML, altChunkId);
                using (FileStream fileStream = File.Open(fileName2, FileMode.Open))
                    chunk.FeedData(fileStream);
                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;
                mainPart.Document
                    .Body
                    .InsertAfter(altChunk, mainPart.Document.Body
                    .Elements<Paragraph>().Last());
                mainPart.Document.Save();
            }           
        }
    }
}

This works flawlessly and the same code is also available here.

There is another approach that uses Open XML PowerTools

like image 82
Varun Rathore Avatar answered Nov 14 '22 22:11

Varun Rathore