Search code examples
c#.netvisual-studioms-wordoffice-interop

Losing Formating when Pasting from one Word Document to another


I have a program where for each ticked box it opens a certain word doc, copies the text and pastes it to the end of a new document.

The problem is the pasted text is missing it's formatting.

Because the copied text remains on the Clipboard I can tell it has the formating when copied, but it doesn't have it when pasted.

Here is the code that copies and pastes it:

foreach (ListViewItem item in checkedItems)
{
    //open documents here
    path = item.SubItems[1].Text;
    objWord.Documents.Open(path);

    //copy document text here
    objWord.ActiveWindow.Selection.WholeStory();
    objWord.ActiveWindow.Selection.Copy();

    //close document here
    objWord.ActiveDocument.Close();

    //paste to end of new document here
    newDoc.Activate();
    copiedText = Clipboard.GetText();
    newDoc.Content.InsertAfter(copiedText);
}

I tried changing:

copiedText = Clipboard.GetText();

to

copiedText = Clipboard.GetText(TextDataFormat.Rtf);

and

copiedText = Clipboard.GetText(TextDataFormat.Rtf).toString();

Neither of which has the desired effect. I went into words options and made sure all pasting options were set to keep source formating.


Solution

  • The problem is that any variable you declare - copiedText in this case - can't "carry" Word's formatting commands. The only way you could use "plain text" would be if it were valid WordOpenXML, then you'd need the InsertXML method to put it into the document. For anything else that carries formatting Word requires a converter. Word automatically triggers a converter when you use the Paste method, Open method to open a file, or InsertFile method to insert a file into the document object.

    Normally, I'd use the FormattedText property to carry formatted content from one document to another. But there are special circumstances where that doesn't carry the required content (such as headers, footers, margins). Then you do need to Copy/Paste.

    I think Word's Paste method should work. Try something like:

    newDoc.Content.Paste
    

    Or, since you've used Activate:

    Selection.Paste