简体   繁体   中英

How to alert selected text from pdf using javascript?

I have embedded a page with a pdf and a button. I want that when user select some text from pdf and click on button then it should alert with the text that he/she has selected. Following is my code :

<html>
<head>
<script>
function getSelText(){
    var txt = '';
    if (window.getSelection) {
        txt = window.getSelection();
    } else if (document.getSelection) {
        txt = document.getSelection();
    } else if (document.selection) {
        txt = document.selection.createRange().text;
    } else return;
    //document.Editor.selectedtext.value =  txt;
    alert(txt);
    console.log("Text = "+txt);
}
</script>
</head>
<body>
<input type="button" value="Get selection" onmousedown="getSelText()"> 
<embed src="SamplePDF.pdf" width="700px" height="650px" id="pdf" onblur="CopyToClipboard(this)">
</body>
</html>

I have tried this but this is only work for non-pdf data, please help me out.

Check out PDF.js , it's a commonly used JavaScript library that contains a lot of methods for PDF manipulation.

1) PDFJS.getDocument( data ).then( function(pdf) {

// set your Pdf to the Function 2) pdf.getPage(i).then( function(page){

// Read the Number of Pages

3) page.getTextContent().then( function(textContent){

//Get the Data Context For Event handler,

In the viewer.js , there are some listeners like:

window.addEventListener('mousedown', function mousedown(evt) {..}
window.addEventListener('mousemove', function keydown(evt) {..}

You can use those to do the logic of your dragging, selecting, ..

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