Friday, February 22, 2013

Merge multiple documents in SharePoint 2010 Programmatically

So here is the scenario:

 
1.  SharePoint document library has multiple documents with the same context let’s say month’s announcements.

2.  Now a single newsletter should go to all users with all announcements in a single announcement monthly letter.

3.  So it’s nothing but merging multiple documents into a single document.

 

Note:
Here “filepath1” is the location of the first document and “filepath2” is for second document. So it could be like http:/// Lib>/documentname.docx

Hope you are clear here as this code only merge 2 documents…but with a loop you can have multiple documents.


________________________________________________________________________________
private void readDocument(string filePath1, string filePath2)

        {
            string targetfile = string.Empty;
            object file1 = filePath1;
            object file2 = filePath2;
            object file3 = targetfile;
            object objMissing = System.Reflection.Missing.Value;
            object objTrue = System.Reflection.Missing.Value;
            object start = 0;
            object end = 0;

          

ApplicationClass WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();


Document finalDocument = WordApp.Documents.Add(ref objMissing, ref objMissing, ref objMissing, ref objMissing);
 

//Range field will ensure they won’t overwrite and second document start where first document ends.


Range rng = finalDocument.Range(ref start, ref objMissing);

rng.InsertFile(filePath1, ref objMissing, ref objMissing, ref objMissing, ref objMissing);

start = (WordApp.ActiveDocument.Content.End)-1; 

Range rng1 = finalDocument.Range(ref start, ref objMissing); 

rng1.InsertFile(filePath2, ref objMissing, ref objMissing, ref objMissing, ref objMissing); 

start = (WordApp.ActiveDocument.Content.End) - 1; 

finalDocument.Save();         

}

 

Cheers!!!

Suneet

No comments: