Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I wanted to use pdf.js for a project of mine but I faced an issue of importing it, basically, the CDN doesn't work

Here is my code

    <!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/pdfjs-dist@2.7.570/build/pdf.min.js"></script>
</head>
<canvas id="my-canvas"></canvas>
<script>
    pdfjsLib.getDocument('./ahmed.pdf').then(doc => {
        console.log("this file has" + doc._pdfInfo.numPages);
</script>
</body>
</html>

and that is the errors that my console shows

Deprecated API usage: No "GlobalWorkerOptions.workerSrc" specified.

Uncaught TypeError: pdfjsLib.getDocument(...).then is not a function

So what should i do to solve this problem and thank you so much

You have to set GlobalWorkerOptions.workerSrc to /build/pdf.worker(.min).js of same version:

pdfjsLib.GlobalWorkerOptions.workerSrc =
  "https://cdn.jsdelivr.net/npm/pdfjs-dist@2.7.570/build/pdf.worker.min.js"; 👈 
pdfjsLib.getDocument('./ahmed.pdf').promise.then(doc => {
  console.log(`This document has ${doc._pdfInfo.numPages} pages.");

And, as @Pasi has mentioned, you have to promisify .getDocument() by chaining .promise on it. Without it, there is no .then().

See the "Hello World with document load error handling" example on this page to get started: https://mozilla.github.io/pdf.js/examples/

(Your snippet is missing .promise after getDocument() and setting the workerSrc property)

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.