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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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:UsersPublicDocumentsDestination.docx"; string fileName2 = @"c:UsersPublicDocumentsSource.docx"; string testFile = @"c:UsersPublicDocumentsTest.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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0