Depa
Depa

Reputation: 509

How to enable text selection in PDF.js

I'm trying to use pdf.js to display pdfs. I already can display a pdf, but text selection isn't enabled. Can somebody give a small example on how to enable text selection in pdf.js?

I already tried several things, but without any success.

my code currently looks like this:

PDFJS.getDocument('someRandom.pdf').then(function(pdf){
  pdf.getPage(1).then(function(page) {
    // you can now use *page* here
    var scale = 1.5;
    var viewport = page.getViewport(scale);

    var canvas = document.getElementById('the-canvas');
    var context = canvas.getContext('2d');
    canvas.height = viewport.height;
    canvas.width = viewport.width;

    var renderContext = {
      canvasContext: context,
      viewport: viewport
    };
   page.render(renderContext);

  });
});

I also included this :

<script src="../pdfjs/pdf.js"></script>
<script>PDFJS.workerSrc ="../pdfjs/pdf.worker.js"</script>

This example renders the pdf, but text selection isn't enabled. I guess I am really missing some basic knowledge about pdf.js, but its hard to get some good example since the documentation isn't that good (at least for me).

I also tried out this example here but the console is throwing an error and keep saying new PDFJS.DefaultAnnotationsLayerFactory() is undefined.

Upvotes: 10

Views: 11458

Answers (2)

Depa
Depa

Reputation: 509

It took me some time, but it's finally working. There are some really good examples here. It's from the official repo (Yeah, my bad I didn't find them).

For anybody who is interested, here is what I've done (Don't know if you really need to do step 2 and 3, I just paste the example that worked for me):

1.Clone the git repo

git clone git://github.com/mozilla/pdf.js.git
  1. go into the folder and run npm installand afterwards node make server (If you haven't installed node.js, you have to do that first)

  2. run node make generic components (also inside the pdf.js folder)

Now you can just copy the build directory inside your project ( You can also copy slideviewer.js or pageviewer.js from the folder exapmle/components into your project if you like to use them instead of creating your viewer.js). My fault was to copy only the pdf.js and some other js into my project. It kept throwing errors because of missing some other js files from that build folder.

Upvotes: 3

Reflective
Reflective

Reputation: 3917

Detailed explanation how to do it in minimal.js heading comnents.

https://github.com/vivin/pdfjs-text-selection-demo/blob/master/js/minimal.js

I tried this example in the past and it worked for me.

Upvotes: 1

Related Questions