Programatically insert a Word document into an existing document (Word 2007)

Chris B picture Chris B · Mar 27, 2009 · Viewed 17.5k times · Source

I have a Word 2007 document that I want to insert an exsiting Word document into - while preserving the header/footer, graphics, borders etc of both documents.

I'm doing this using the Word API in C#.

It sounds pretty simple, I mean surely you just use the "InsertFile" method... except that in Word 2007 the "insert file" functionality now is actually "insert text from file" and it does just that - leaving out the page border, graphics and footer etc.

OK then, I'll use copy and paste instead, like so...

_Document sourceDocument = wordApplication.Documents.Open(insert the 8 million by ref parameters Word requries)
sourceDocument.Activate(); // This is the document I am copying from 
wordApplication.Selection.WholeStory();
wordApplication.Selection.Copy();
targetDocument.Activate(); // This is the document I am pasting into
wordApplication.Selection.InsertBreak(wdSectionBreakNextPage);
Selection.PasteAndFormat(wdFormatOriginalFormatting);
wordApplication.Selection.InsertBreak(wdSectionBreakNextPage);

which does what you would expect, takes the source document, selects everything, copies it then pastes it into the target document. Because I've added a section break before doing the paste it also preserves the borders, header/footer of both documents.

However - now this is where I have the problem. The paste only includes the borders, header etc if I paste at the end of the target document. If I paste it in the middle - despite there being a preceding section break, then only the text gets pasted and the header and borders etc are lost.

Answer

Matrim picture Matrim · Mar 27, 2009

Would the bookmark functionality work. The InsertFile contains parameters to take from this which may get around the problem. You may have considered this already though

http://msdn.microsoft.com/en-us/library/microsoft.office.tools.word.bookmark.insertfile.aspx