Tuesday 14 April 2009

Copying data (on the fly) from one Document to another in one Add-in.

If you are interested in copy a word document file, binary style, you will find plenty of problems copying a document on the fly. To sort that out the only way we have, it is to do it is by copying the file locally OR by using this method, what basically is the clipboard.

As soon as we managed to keep the data in the clipboard we can tranform this document into binary and do whatever we want with it....

Mind that this has been developed for an Office Add-in, so it should be incorporated into the event:

private void Connect_DocumentBeforeSave(Microsoft.Office.Interop.Word.Document Doc, ref bool SaveAsUI, ref bool Cancel)

in the Connect.cs class

//## The before save event is disable to avoid recursive savings...
((Microsoft.Office.Interop.Word.Application)applicationObject).DocumentBeforeSave -= new Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentBeforeSaveEventHandler(Connect_DocumentBeforeSave);

//## Temp file where we will keep the new document.
object newDocPath = (object)System.IO.Path.GetTempFileName();

//## Initialize a bogus parameter for arguments we don't care about
object oMissing = System.Reflection.Missing.Value;

//## We find the doc and we get a clean copy...we dont need to do this but it is quite useful.
this.Document = ((Microsoft.Office.Interop.Word.Application)applicationObject).Documents.Application.ActiveDocument;

//## Select entire contents, and copy to clipboard
Document.ActiveWindow.Selection.WholeStory();
Document.ActiveWindow.Selection.Copy();

//## Create new document and paste from clipboard
Microsoft.Office.Interop.Word.Document newDoc = ((Microsoft.Office.Interop.Word.Application)applicationObject).Documents.Add(ref oMissing, ref oMissing,ref oMissing, ref oMissing);

//## We paste all the stuff...
newDoc.ActiveWindow.Selection.Paste();

//## Saving new document....
((Microsoft.Office.Interop.Word.Application)applicationObject).ActiveDocument.SaveAs(ref newDocPath,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

//## Closing the file to avoid problems.
newDoc.Close(ref oMissing, ref oMissing, ref oMissing);

No comments: