2

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.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147

1 Answers1

1

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, ..

vijay kani
  • 140
  • 8