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

Posted by cjb on Stack Overflow See other posts from Stack Overflow or by cjb
Published on 2009-03-27T10:54:52Z Indexed on 2010/04/01 6:43 UTC
Read the original article Hit count: 638

Filed under:
|
|
|

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.

Can anyone help before I buy a grenade and a one way ticket to Redmond...

© Stack Overflow or respective owner

Related posts about word2007

Related posts about insert