How do I retrieve text from user selection in pdf.js?

前端 未结 2 1712
隐瞒了意图╮
隐瞒了意图╮ 2020-12-16 05:47

This question is specific to pdf.js, a javascript based pdf renderer. I\'m building a custom version where I need to extract the text that I select inside the pdf.

相关标签:
2条回答
  • 2020-12-16 06:23

    pdf.js has a file viewer.html inside the directory web.

    you have to do the following two steps in viwer.html

    1. Add Event Listener onselectionchange.
    2. Define the event handling function onselectionchange().
    <script>
    
      // addEventListener version
      document.addEventListener('selectionchange', () => {
        console.log(document.getSelection());
      });
    
      // onselectionchange version
      document.onselectionchange = () => {
        var text = getSelectedText();
    
        if(text)
        {
          alert(text); 
    
        }
      };
    
      function getSelectedText() {
         if (window.getSelection) {
            return window.getSelection().toString();
         } 
         else if (document.selection) {
             return document.selection.createRange().text;
         }
         return '';
      }
    </script>
    
    0 讨论(0)
  • 2020-12-16 06:24

    What you are looking for is window.getSelection() method. This method returns a specific Selection object with the range of the selected text on the web page.

    Here is how you can use getSelection() together with pdf.js:

    function getHightlightCoords() {
    var pageIndex = PDFViewerApplication.pdfViewer.currentPageNumber - 1; 
    var page = PDFViewerApplication.pdfViewer.getPageView(pageIndex);
    var pageRect = page.canvas.getClientRects()[0];
    var selectionRects = window.getSelection().getRangeAt(0).getClientRects();
    var viewport = page.viewport;
    var selected = selectionRects.map(function (r) {
      return viewport.convertToPdfPoint(r.left - pageRect.x, r.top - pageRect.y).concat(
         viewport.convertToPdfPoint(r.right - pageRect.x, r.bottom - pageRect.y)); 
    });
    return {page: pageIndex, coords: selected};
    }
    
    
    function showHighlight(selected) {
    var pageIndex = selected.page; 
    var page = PDFViewerApplication.pdfViewer.getPageView(pageIndex);
    var pageElement = page.canvas.parentElement;
    var viewport = page.viewport;
    selected.coords.forEach(function (rect) {
      var bounds = viewport.convertToViewportRectangle(rect);
      var el = document.createElement('div');
      el.setAttribute('style', 'position: absolute; background-color: pink;' + 
        'left:' + Math.min(bounds[0], bounds[2]) + 'px; top:' + Math.min(bounds[1], bounds[3]) + 'px;' +
        'width:' + Math.abs(bounds[0] - bounds[2]) + 'px; height:' + Math.abs(bounds[1] - bounds[3]) + 'px;');
      pageElement.appendChild(el);
    });
    }
    
    0 讨论(0)
提交回复
热议问题