Merge Two Or More Documents Programmatically In C#

Merging two or more documents is a basic need these days. If you have installed any PDF reader or MS Office on your machine you can open documents (PDF, DOCX or PPTX) and merge them. But this is a time and resources consuming procedure. There could be a business requirement that there must no such tool installed on the server. In that case, you need a simple yet helpful application to combine and merge two or more documents (of the same format) into a single one. 
 
Now, we have the following limitations and keeping that in mind, we have to look for a solution:
  • No software installation on server or local machine
  • Resources (e.g. Memory, CPU) availability is limited 
  • Source files could be password protected
Let's walk through the implementation.
  1. string sourceFile1 = "source file";  
  2. string sourceFile2 = "source file";  
  3. string password = "SomePasswordString";  
  4. Stream openFile1 = new FileStream(sourceFile1, FileMode.Open);  
  5. Stream openFile2 = new FileStream(sourceFile2, FileMode.Open);  
  6. List<JoinItem> documentStreams = new List<JoinItem>();  
  7. JoinItem item1 = new JoinItem(openFile1, FileFormat.Docx, password);  
  8. documentStreams.Add(item1);  
  9. JoinItem item2 = new JoinItem(openFile2, FileFormat.Docx, password);  
  10. documentStreams.Add(item2);  
  11. DocumentResult result = new DocumentHandler().Join(documentStreams);  
  12. Stream documentStream = result.Stream;  
  13. var fileStream = File.Create("output path" + "OutPut." + FileFormat.Docx);  
  14. documentStream.CopyTo(fileStream);  
  15. documentStream.Close();  
You just have to integrate GroupDocs.Merger DLL. JoinItem and DocumentResult classes are defined in this DLL. NuGet package could be installed here. Aside from Word and PDF, this API supports Presentation and Spreadsheet formats as well.