Links, Hyperlinks into a canvas using PDF.js

前端 未结 2 2037
猫巷女王i
猫巷女王i 2021-02-15 18:45

I\'m using the PDF.js library to render a pdf into the canvas. That pdf has hyperlinks in there, The PDF.js library is drawing the pdf into the canvas but the hyperlinks don\'t

2条回答
  •  遇见更好的自我
    2021-02-15 19:46

    Enable Text Selection in PDF.JS


    Step 1: Adding a Element to Hold the Text Layer

    This div will be in addition to the element where the PDF is rendered, so the HTML will look like :

    
    

    Step 2 : Adding CSS for Text Layer

    Add the following to your CSS file :

    #text-layer { 
       position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        overflow: hidden;
        opacity: 0.2;
        line-height: 1.0;
    }
    
    #text-layer > div {
        color: transparent;
        position: absolute;
        white-space: pre;
        cursor: text;
        transform-origin: 0% 0%;
    }
    

    Step 3: Getting the PDF Text

    After the PDF has been rendered in the canvas, you need to get the text contents of the PDF, and place that text in the text layer.

    // page is the page context of the PDF page
    // viewport is the viewport required in renderContext
    // For more see https://usefulangle.com/post/20/pdfjs-tutorial-1-preview-pdf-during-upload-wih-next-prev-buttons    
    
    page.render(renderContext).then(function() {
        // Returns a promise, on resolving it will return text contents of the page
        return page.getTextContent();
    }).then(function(textContent) {
         // PDF canvas
        var pdf_canvas = $("#pdf-canvas"); 
    
        // Canvas offset
        var canvas_offset = pdf_canvas.offset();
    
        // Canvas height
        var canvas_height = pdf_canvas.get(0).height;
    
        // Canvas width
        var canvas_width = pdf_canvas.get(0).width;
    
        // Assign CSS to the text-layer element
        $("#text-layer").css({ left: canvas_offset.left + 'px', top: canvas_offset.top + 'px', height: canvas_height + 'px', width: canvas_width + 'px' });
    
        // Pass the data to the method for rendering of text over the pdf canvas.
        PDFJS.renderTextLayer({
            textContent: textContent,
            container: $("#text-layer").get(0),
            viewport: viewport,
            textDivs: []
        });
    });
    

    source: https://usefulangle.com/post/90/javascript-pdfjs-enable-text-layer

提交回复
热议问题