user25934652
user25934652

Reputation: 3

Ckeditor 4 copy content to word ducument

Ckeditor 4 contents to be copied to Microsoft Word docuemnt.

HTML:

<button id="copy">Copy</button>
<textarea id="textarea">
    <h1>Title</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</textarea>

JS:

var editor = CKEDITOR.replace( 'textarea' );

document.getElementById('copy').onclick = function(){
    var content = CKEDITOR.instances.textarea.getData(),
        newElement = document.createElement("textarea");
  
    newElement.style.position = 'absolute';
    newElement.style.left = '99999px';
    newElement.innerHTML = content;
    document.body.appendChild(newElement)
    newElement.select();
    document.execCommand('copy');
}

Here is a fiddle for testing: https://jsfiddle.net/oL04y3g5/

This code will copy the html source which is:

<h1>Title</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>

Pasting this into a word document will display it as plain text not how it should look like.

How to copy the same way as if I select the text inside the box and paste it into a word document?

Upvotes: 0

Views: 65

Answers (1)

SELA
SELA

Reputation: 6793

You need to have a hidden div and once the user clicks on the copy get everything into the clipboard. By doing so it will get the inner content of the textarea.

Refer the sample code below:

var editor = CKEDITOR.replace('textarea');
document.getElementById('copy').onclick = function () {
    var content = CKEDITOR.instances.textarea.getData();  
    var hiddenDiv = document.createElement('div'); // Create a sample hidden div element
    hiddenDiv.style.position = 'absolute'; // add sample styling
    hiddenDiv.style.left = '-9999px';
    hiddenDiv.style.whiteSpace = 'pre-wrap';
    hiddenDiv.innerHTML = content;
    document.body.appendChild(hiddenDiv);
    var range = document.createRange();
    range.selectNodeContents(hiddenDiv);   
    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);  
    document.execCommand('copy'); // Copy things out
    selection.removeAllRanges(); // Remove everything out
    document.body.removeChild(hiddenDiv);
};
<script src="https://cdn.ckeditor.com/4.16.2/standard/ckeditor.js"></script>
<button id="copy">Copy</button>
<textarea id="textarea">
    <h1>Title</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</textarea>

Refer the working JSFiddle here

Upvotes: 0

Related Questions