none
Errors when pasting in Word. RRS feed

  • Question

  • I'm working on a script that converts XML to Word, and I'm having an issue with pasting. Two annoying things about this issue are that:

    1. The issue is intermittent.
    2. When it does occur, it's not always at the same point in the document.

    If it was always at the same spot in the doc, then I'd figure there was an issue with the XML source, but that's not the case. I'm not sure where to start trouble-shooting this.

    Very briefly, the way this script works is:

    1. I load the XML into an XML object.
    2. I iterate through the XML object, processing different types of data as appropriate to my desired output.
    3. Most times, it's a matter of just processing the text, and using the typeParagraph() method.
    4. For images, I convert the Base64 encoding from the XML into an image stream, copy that image stream to the clipboard, paste the image to the Word doc, then clear the clipboard.
    5. For HTML-encoded tables, I copy the table to the clipboard as HTML, then paste it as HTML, then clear the clipboard.

    Here's one error I've received:

    [ERROR]
         Command Line: &("W:\Scripts\RWExport\PowerShell\Version 1.7\RWExport-To-HTML-test.ps1") -Source 'C:\Users\<Redacted>\Desktop\<Redacted>\Test Export\Shadowrun v2.rwoutput' -Destination 'C:\Users\<Redacted>\Desktop\<Redacted>\Test Export Out\test.doc' -Sort 1 -SimpleImageScale 0 -SmartImageScale 0 -CSSFileName 'RWExport_091b_1.6.css' -Format 'Word' -Details -Indent -SeparateSnippets -WordDelay 15

             Reason: OperationStopped - Command failed

           Location: Line 1924, Character 19
        Script Line: $selection.PasteSpecial() ,,,,10 # Paste as wdPasteHTML

              Topic: Söldner
            Section: Statistics
       Snippet Type: Multi_Line
    [/ERROR]

    Here's the relevant code block:

                Switch ($Format) {
                   "Word" {
                      Set-Clipboard $tagtext -AsHtml
                      $selection = $wordfile.selection
                      $selection.PasteSpecial() ,,,,10 # Paste as wdPasteHTML
                      [Windows.Forms.Clipboard]::Clear()
                   } # "Word"
                   "HTML" {
                      If (-not $KeepStyles) {$Text = StripStyles $Text $Log}
                      if ($SeparateSnippets) {$Text = $Text + "<hr>"}
                      [System.IO.File]::AppendAllText($outputfile,$Text)
                   } # "HTML"
                } # Switch ($Format)

    The relevant switch option, in this case, is "Word".

    An example of the error I'm getting with Images is:

    [ERROR]
         Command Line: &("W:\Scripts\RWExport\PowerShell\Version 1.7\RWExport-To-HTML-test.ps1") -Source 'C:\Users\<Redacted>\Desktop\<Redacted>\Test Export\Shadowrun v2.rwoutput' -Destination 'C:\Users\<Redacted>\Desktop\<Redacted>\Test Export Out\test.doc' -Sort 1 -SimpleImageScale 0 -SmartImageScale 0 -CSSFileName 'RWExport_091b_1.6.css' -Format 'Word' -Details -Indent -SeparateSnippets -WordDelay 15

             Reason: OperationStopped - This method or property is not available because the Clipboard is empty or not valid.

           Location: Line 2026, Character 16
        Script Line: $selection.Paste()
    [/ERROR]

    Here's the relevant code block:

             Switch ($Format) {
                "Word" {
                   $selection = $wordfile.selection
                   $ImageStream=[System.IO.MemoryStream][System.Convert]::FromBase64String($CoverArt)
                   $ImageBmp=[System.Drawing.Bitmap][System.Drawing.Image]::FromStream($ImageStream)
                   [Windows.Forms.Clipboard]::SetImage($ImageBmp)
                   $selection.Paste()
                   $Selection.InsertBreak(7) # Page
                   [Windows.Forms.Clipboard]::Clear()
                } # "Word"
                "HTML" {
                   $CoverArtScale = 'width="100%"'
                   $CoverArt = '<img ' + $CoverArtSCale + ' src="data:image/png;base64,' + $CoverArt + '">'
               } # "HTML"
            } # Switch ($Format)

    I don't know if I'm mismanaging the clipboard or if something else is wrong, and Googling hasn't helped me find answers. Any help/suggestions/ideas are appreciated.

    Thank you.

    • Moved by jrv Saturday, December 2, 2017 8:43 AM Best forum
    Friday, November 17, 2017 11:53 AM

All replies

  • You should contact the author of the module you are using.  The errors are translated and most useful information has been lost.


    \_(ツ)_/

    Friday, November 17, 2017 4:09 PM
  • I am the author. I put in my own error trapping for general troubleshooting. I'll try to get the full error message.
    Friday, November 17, 2017 9:15 PM
  • The full error is critical for the details.

    \_(ツ)_/

    Friday, November 17, 2017 10:00 PM

  • This is one for pasting the HTML tables. Still trying to get one for the images, but like I said, it's intermittent and inconsistent.

             Reason: OperationStopped - Command failed

           Location: Line 1924, Character 19
        Script Line: $selection.PasteSpecial() ,,,,10 # Paste as wdPasteHTML

              Topic: Schwere Waffen
            Section: Overview
       Snippet Type: Multi_Line
    [/ERROR]

    [DBG]: PS W:\Scripts\RWExport\PowerShell\Version 1.7>> $ErrorObject
    Command failed
    At W:\Scripts\RWExport\PowerShell\Version 1.7\RWExport-To-HTML-test.ps1:1924 char:19
    +                   $selection.PasteSpecial() ,,,,10 # Paste as wdPaste ...
    +                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : OperationStopped: (:) [], COMException
        + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
    Friday, November 17, 2017 10:02 PM
  • This line:

    $selection.PasteSpecial() ,,,,10 # Paste as wdPaste

    Will not execute correctly ever.   It just generates an array with the result of the method and "10" as the sync and 1 as the only member

    $selection.PasteSpecial([type]::Missing,[type]::Missing,[type]::Missing,[type]::Missing,10)

    TO skip arguments you must use "[type]::Missing"


    \_(ツ)_/

    Friday, November 17, 2017 10:08 PM
  • I accept the syntax correction (and thank you), but merely as a curiosity (not as an argument), I will point out that it was executing correctly sometimes (the way I had it before the correction).

    Again, not arguing, so I will correct that line.

    Finally  got an image pasting error.

    Reason: OperationStopped - This method or property is not available because the Clipboard is empty or not valid.

           Location: Line 1028, Character 20
        Script Line: $selection.Paste()

              Topic: Agropelzer
            Section: Overview
       Snippet Type: Picture
    [/ERROR]


    Default, full error message:
    This method or property is not available because the Clipboard is empty or not valid.


    Hit Line breakpoint on 'W:\Scripts\RWExport\PowerShell\Version 1.7\RWExport-To-HTML-test.ps1:2010'
    [DBG]: PS W:\Scripts\RWExport\PowerShell\Version 1.7>> $ErrorObject
    This method or property is not available because the Clipboard is empty or not valid.
    At W:\Scripts\RWExport\PowerShell\Version 1.7\RWExport-To-HTML-test.ps1:1028 char:20
    +                    $selection.Paste()
    +                    ~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : OperationStopped: (:) [], COMException
        + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
    Friday, November 17, 2017 10:14 PM
  • And here's that block of code:

    "Word" {
                       $selection = $wordfile.selection
                       $selection.Style = $WordStyles.styles.normal
                       $selection.typeText($ImageName)
                       # $selection.InsertBreak(6) # Line break.
                       if (($annotation -ne $null) -and ($annotation -ne "")) {$annotation = $annotation.trim()}
                       if (($annotation -ne $null) -and ($annotation -ne "") -and ($annotation -ne "&nbsp;")) {
                          $annotation = "Annotation: $annotation"
                          $selection.InsertBreak(6) # Line break.
                          $selection.typeText($annotation)
                       } # if (($Text -ne $null) -and ($text -ne "") -and ($text -ne "&nbsp;"))
                       $selection.InsertBreak(6) # Line break.
                       $ImageStream=[System.IO.MemoryStream][System.Convert]::FromBase64String($PassedSnippet.ext_object.asset.contents)
                       $ImageBmp=[System.Drawing.Bitmap][System.Drawing.Image]::FromStream($ImageStream)
                       [Windows.Forms.Clipboard]::SetImage($ImageBmp)
                       $selection.Paste()
                       [Windows.Forms.Clipboard]::Clear()
                       # if ($WordDelay -ge 1) {Start-Sleep -s $WordDelay}
                    } #"Word" 

    Friday, November 17, 2017 10:17 PM
  • Also, still getting the error on tables.

    Location: Line 1924, Character 19
        Script Line: $selection.PasteSpecial([type]::Missing,[type]::Missing,[type]::Missing,[type]::Missing,10)

              Topic: Pistolen
            Section: Overview
       Snippet Type: Multi_Line
    [/ERROR]


    Default, full error message:
    This method or property is not available because the Clipboard is empty or not valid.


    Hit Line breakpoint on 'W:\Scripts\RWExport\PowerShell\Version 1.7\RWExport-To-HTML-test.ps1:2010'
    [DBG]: PS W:\Scripts\RWExport\PowerShell\Version 1.7>> $ErrorObject
    This method or property is not available because the Clipboard is empty or not valid.
    At W:\Scripts\RWExport\PowerShell\Version 1.7\RWExport-To-HTML-test.ps1:1924 char:19
    + ...             $selection.PasteSpecial([type]::Missing,[type]::Missing,[ ...
    +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : OperationStopped: (:) [], COMException
        + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
    Friday, November 17, 2017 10:28 PM
  • No.  That is a completely different error.

    Just take out the few lines of code that does the image and run it at a prompt.  Look up the syntax of the method and be sure it is correct.


    \_(ツ)_/

    Friday, November 17, 2017 10:34 PM
  • If the syntax was incorrect, wouldn't it fail every time instead of being both intermittent and inconsistent?

    Friday, November 17, 2017 10:37 PM
  • Why are you using PasteSpecial?  That is mostly for pasting Icons with optional settings.  TO just paste an image use "Paste".  The issue with paste is that it cannot tell which object to pull from the clipboard.

    Images are best inserted from a file and not from the clipboard.


    \_(ツ)_/

    Friday, November 17, 2017 10:41 PM
  • I think this is what you are trying to do:

    $selection.PasteAndFormat([Microsoft.Office.Interop.Word.WdPasteDataType]::wdPasteHTML)
    $selection.PasteAndFormat([Microsoft.Office.Interop.Word.WdPasteDataType]::wdPasteBitmap)


    \_(ツ)_/

    Friday, November 17, 2017 10:46 PM
  • Nope. That works worse.

    Reason: OperationStopped - The specified data type is unavailable.

           Location: Line 2035, Character 16
        Script Line: $selection.PasteAndFormat([Microsoft.Office.Interop.Word.WdPasteDataType]::wdPasteBitmap)
    [/ERROR]


    Default, full error message:
    The specified data type is unavailable.


    Hit Line breakpoint on 'W:\Scripts\RWExport\PowerShell\Version 1.7\RWExport-To-HTML-test.ps1:2010'
    [DBG]: PS W:\Scripts\RWExport\PowerShell\Version 1.7>> $ErrorObject
    The specified data type is unavailable.
    At W:\Scripts\RWExport\PowerShell\Version 1.7\RWExport-To-HTML-test.ps1:2035 char:16
    + ...             $selection.PasteAndFormat([Microsoft.Office.Interop.Word. ...
    +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : OperationStopped: (:) [], COMException
        + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
    Saturday, November 18, 2017 2:43 AM
  • what you re trying to paste from the clipboard is not what you think it is.  This is not an issue with the paste but is an issue with the copy.

    Before you paste do this:

    [System.Windows.Forms.Clipboard]::Clear()

    Be sure you release the image after copying.  It will still be locked in memory after calling SetImage and will not successfully copy to the clipboard.

    Do this outside of you script in the simplest short amount of code until you understand how this has to work.


    \_(ツ)_/

    Saturday, November 18, 2017 3:12 AM
  • This comment doesn't make any sense.

    "what you're trying to paste from the clipboard is not what you think it is."

    Then what is it? And why does it work most of the time?

    You want me to clear the clipboard BEFORE I paste? Then there will be nothing to paste.

    On top of that, you started out by telling me that a line of code I was using will NEVER work, when it was clearly working most of the time.

    I have no confidence that you actually know how to resolve this issue.

    Saturday, November 18, 2017 8:09 PM
  • Clear the clipboard  before you COPY, not paste.

    The clipboard can maintain multiple objects in different formats.  If you cannot specify the paste format you have no idea what you will get.  Without a format the paste will paste into the current context which in Word is "text".  Clearing the clipboard before each SetImage or SetText will guarantee that only the required format is available.  That should force word to paste correctly.  Using PasteFromat will force the correct format assuming you actually have a System.Drawing.Image object on the clipboard.

    Post a simple image base64 string (small hopefully) for an image that fails and I will give you and example or tell you what is failing.


    \_(ツ)_/

    Saturday, November 18, 2017 8:18 PM
  • Here is a quick example of how to safely paste an image from the clipboard.

    $wrd = New-Object -ComObject Word.Application
    $doc = $wrd.Documents.Add()
    $wrd.Visible = $true
    
    # paste a jpg as an "Image".
    [System.Windows.Forms.Clipboard]::Clear()
    $img = [System.Drawing.Image]::FromFile('d:\scripts\mytext.jpg')
    [System.Windows.Forms.Clipboard]::SetImage($img)
    $wrd.Selection.PasteAndFormat([Microsoft.Office.Interop.Word.WdPasteDataType]::wdPasteShape)
    $img.Dispose()
    
    # paste an image as a bitmap
    $bmp = [System.Drawing.Bitmap]::FromFile('d:\scripts\mytext.jpg')
    [System.Windows.Forms.Clipboard]::Clear()
    [System.Windows.Forms.Clipboard]::SetImage($bmp)
    $wrd.Selection.PasteAndFormat([Microsoft.Office.Interop.Word.WdPasteDataType]::wdPasteBitmap)
    $bmp.Dispose()


    \_(ツ)_/


    • Edited by jrv Saturday, November 18, 2017 8:56 PM
    Saturday, November 18, 2017 8:36 PM
  • Note that when loading from a base64 string an image is always a bitmap.


    \_(ツ)_/

    Saturday, November 18, 2017 8:56 PM
  • Your code examples still did not fix the issue.

    I noticed that when the error occurs, the item is actually in the clipboard, and I can paste it into word. So I inserted a 1-second delay between copying to the clipboard and pasting into Word. That SEEMS to be working ... for now. I hope I'm not speaking too soon again.

    Saturday, December 2, 2017 2:45 AM
  • I would recommend not usi g the clipboard for this.  It is totally unnecessary.  Al note that there is a lot of malware that disrupts the clipboard and AV scanners can cause it to fail.


    \_(ツ)_/

    Saturday, December 2, 2017 2:50 AM
  • You tell me not to use the clipboard without offering any alternative.

    $ImageStream=[System.IO.MemoryStream][System.Convert]::FromBase64String($PassedSnippet.ext_object.asset.contents)
    $ImageBmp=[System.Drawing.Bitmap][System.Drawing.Image]::FromStream($ImageStream)
    
    [Windows.Forms.Clipboard]::SetImage($ImageBmp) $selection.Paste()

    I'm reading from an XML file, so the images are always going to be a base64 string. Those first two lines read in the stream then convert it to a bitmap.

    The following two lines copy the image to the clipboard then paste into word. For those following two lines, what's my alternative? If you don't know, just say so, and stop giving me half-answers.

    Saturday, December 2, 2017 7:10 AM
  • Yes and the clipboard will always be unreliable.  I see this on all versions of Windows even when copying and pasting from the GUI.

    Save the image to a file and insert the image file into Word.


    \_(ツ)_/

    Saturday, December 2, 2017 7:19 AM
  • You can also set a raw image into a document like this:

    $p.Range.InlineShapes.AddPicture($filename,$false)

    https://msdn.microsoft.com/library/microsoft.office.interop.word.inlineshapes.addpicture(v=office.15).aspx



    \_(ツ)_/

    Saturday, December 2, 2017 7:34 AM
  • I like how you keep changing your answers.

    You: "Here try this ..."

    Me: "That didn't fix the issue."

    You: "Well that's not the right way to do it anyway. Here, try this instead..."

    Me: "That didn't fix the issue."

    You: "Well that's not the right way to do it anyway. Here, try this instead..."

    Me: "That didn't fix the issue."

    You: "Well that's not the right way to do it anyway. Here, try this instead..."

    Saturday, December 2, 2017 7:53 AM
  • Hello,

    Does it still work if there is 1 second delay before pasting? 

    Could you reproduce the issue using other machines? 

    Could you please share your XML and the whole script here to help us reproduce your issue? 

    Regards,

    Celeste


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, December 4, 2017 6:52 AM
    Moderator
  • It works much better if there's a 1-second delay. It's still not 100%. I can reproduce the error using other machines. Unfortunately, I cannot share the XML I am currently testing with as it is someone else's intellectual property.
    Tuesday, December 5, 2017 10:07 AM
  • I think you need to increase the delay time if 1-second is not enough.

    This issue occurs when the Word application is not ready to paste the next content. You could assume that when you paste a large content, the Work app will be unresponsive for a while, this is limited by Word app. 

    Regards,

    Tony


    Help each other

    Tuesday, December 5, 2017 11:52 AM
  • when a Word document is altered either from the UI or programmatically it causes a reflow.  Turn of all auto functions while  making large amounts of changes programmatically.  This includes spell check, autoformat and autocorrect.


    \_(ツ)_/

    Tuesday, December 5, 2017 12:24 PM