简体   繁体   中英

How to paste image from clipboard to Word

I have copied an image from a word document to the clipboard programmatically.

I want to paste that image into another word file using C# and Microsoft.Office.Interop.Word for word reference.

Here is the code :

foreach (Words.InlineShape shape in document.InlineShapes)
{
    if (shape != null)
    {
        if (shape.Type == Words.WdInlineShapeType.wdInlineShapePicture)
        {
             shape.Select();
             app.Selection.CopyAsPicture();
             Words.Document doc = app.Documents.Add();

             System.Drawing.Image img = null;
             if (Clipboard.ContainsImage())
             {
                  img = Clipboard.GetImage();
                  IDataObject idata = Clipboard.GetDataObject();
             }
         }
    }
}

Rather than work with the clipboard directly, you can simply paste it back using Word's own paste function. For example:

doc.Content.Paste();

But first ask yourself whether you really need to use the clipboard at all. Using the clipboard means that you'll leave a large picture on the clipboard (wasting memory) unless you clean it up, and it also means that you lose the original content of the clipboard, which might upset your users. Consider using the FormattedText of the Range instead:

targetRange.FormattedText = sourceRange.FormattedText

The FormattedText property copies all the text and formatting and that includes any embedded fields, tables, pictures, etc. (You need to start with the range that includes the anchor point for the original picture). You can get that range for an InlineShape via the Range property. (For a floating Shape you'd use the Anchor property).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM