Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML editor and pasting images from Word

We have made a very simple html editor (contenteditable="true") and users can paste images copied from other web pages, but if the user copy an image from word, word will paste the src as file://temp/someimg.jpg and the browser will not load the image.

<img src="file://..../.jgp">

But if I run the web page on my dev computer (http://127.0.0.1) and do the same, word will paste the image src as "data:image/jpeg;base64....."

Is there some way I can make word paste the base64 encoded picture to the editor always and not only the file:// location?

like image 690
Mr Zach Avatar asked Jun 10 '17 04:06

Mr Zach


People also ask

Can you copy an image from the Web and paste it directly to MS Word?

Open Paint in Accessories and paste with Ctrl+v. Select the required area and copy by either Ctrl+c or by right clicking. Then go to your word document page and paste with Ctrl+v. Your job's done.

How do I copy and paste a picture from a picture to word?

Select the picture or pictures you want to copy. Click Home, and then click Copy . Click the folder where you want to paste the copy, and then click Paste .


1 Answers

You will need to handle the paste event and read the clipboard for image content. Please find the prototype in below snippet (tested in google chrome) which demonstrates the same.

// create paste event listener
window.addEventListener("paste", pasteHandler);

// handle paste events
function pasteHandler(e) {
  if (e.clipboardData) {
    var items = e.clipboardData.items;
    if (items) {
      for (var i in items) { // iterate through clipbord items
        var item = items[i];
        if (item.kind == "file") {  //image is a file
        
          // create image source
          var blob = item.getAsFile();
          var URLObj = window.URL || window.webkitURL;
          var source = URLObj.createObjectURL(blob);
          var pastedImage = new Image();
          pastedImage.src = source;
          
          // add it in editor
          document.getElementById("editor").innerHTML = document.getElementById("editor").innerHTML + pastedImage.outerHTML;
        }
      }
    }
  }
}
#editor{
  min-width: 400px;
  min-height: 250px;
  border: solid;
  border-width: thin;
  padding: 10px;
}
<div id="editor" contenteditable=true>Copy an image from word<br/>Press Ctrl+v to paste it here <br/></div>
like image 97
Prasad Kothavale Avatar answered Nov 01 '22 17:11

Prasad Kothavale