I am dealing with Word VSTO add-in. I wrote a code that inserts one document to another. I have two different approaches.
1) Copy
/Paste
var app = new Word.Application();
var MyDoc = app.Documents.Add(@"C:\install\CSharp\Plank.dotm");
MyDoc.ActiveWindow.Selection.WholeStory();
MyDoc.ActiveWindow.Selection.CopyFormat();
Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;
doc.Activate();
doc.ActiveWindow.Selection.PasteFormat();
2) InsertFile()
var app = new Word.Application();
var MyDoc = app.Documents.Add(@"C:\install\CSharp\Plank.dotm");
Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;
doc.Activate();
//Taking margins
float TopMargin = MyDoc.PageSetup.TopMargin;
float RightMargin = MyDoc.PageSetup.RightMargin;
float LeftMargin = MyDoc.PageSetup.LeftMargin;
Globals.ThisAddIn.Application.Selection.InsertFile(@"C:\\install\CSharp\Plank.dotm", Link: false, Attachment: false);
At the first approach the line PasteFormat()
is not working, telling me that text properties were not copied. (If I use just Copy()
and Paste()
it works.) Even if I paste manually I get what I want.
The second approach works, but it doesn't take text formatting. So I get the text in some other format and size which differs from the original.
QUESTION is: How can I preserve original font formats? I tried to insert a file in Word manually. And I can't get the original text formatting there either. Maybe it is a wrong approach?
I figured it out with the Copy()
/ Paste()
solution. I need to copy like this:
MyDoc.ActiveWindow.Selection.Copy();
doc.ActiveWindow.Selection.PasteAndFormat(Word.WdRecoveryType.wdFormatOriginalFormatting);
Then it preserves the styles. But sometimes, if the document has tables, it copies them to the next page, which is strange. The InsertFile()
method is not working for me.