Javascript : Extract Selected Text from PDF to Input Textbox in Javascript

219 Views Asked by At

I am working on one Project in which a Text from PDF which is Selected should be copied to Input Textbox where a Cursor is focused.

There are 2 Windows.

1 : Where Input Textbox is there 2 : PDF is there.

Is there any way to copy text which is selected from PDF window and paste to Input Textbox in another Window using Javascript ?

Below is the code I have tried.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<script>
    function getSelectionText() {
            var text = "";
            var activeEl = document.activeElement;
            var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null;
            if (
                (activeElTagName == "textarea") || (activeElTagName == "input" &&
                    /^(?:text|search|password|tel|url)$/i.test(activeEl.type)) &&
                (typeof activeEl.selectionStart == "number")
            ) {
                text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd);
            } else if (window.getSelection) {
                text = window.getSelection().toString();
            }
            return text;
        }

        document.onmouseup = document.onkeyup = document.onselectionchange = function () {
            document.getElementById("sel").value = getSelectionText();
        };

</script>
<body>
    
    Selection:
    <br>
    <textarea id="sel" rows="3" cols="50"></textarea>
    <p>Please select this text.</p>
    <input value="Some text in a text input">

    <iframe height="300" width="700" src="https://www.africau.edu/images/default/sample.pdf" >
   


</body>
</html>

Any help would be great.

2

There are 2 best solutions below

7
Hamed Ghasemi On

You can use the following code But you have to adjust the origin policy according to your needs so that the code works

document.getElementById("Your_Iframe_Tag_ID").contentWindow.document.getSelection()
1
Cat drinking a cat On

Each browser's default PDF viewers handles itself differently, and additionally, the user may have an extension/plugin to use their desired PDF viewer.

There is no one code fits all solution for this unless you use a custom PDF viewer like PDF.js (Open Source) or focus on a single browser/PDF viewer.

If you decide to use PDF.js your answer can be found here: How do I retrieve text from user selection in pdf.js?

Alternatively, if you decide on just Chrome PDF viewer: How can I get selected text in pdf in Javascript?

P.S.: If you're crazy enough you can just not use a custom viewer and simply go through every single popular PDF viewers (extension, plugins or otherwise) and add support for them individually.