question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Run PDF.js canvas rendering in a web-worker

See original GitHub issue

Configuration:

  • Chrome 71
  • Operating system and its version: any
  • PDF.js version: 2.0.943
  • Is a browser extension: no

Steps to reproduce the problem:

  1. Write a web worker like this:
function onmessage () {
  const pdfDocument = await pdfjs.getDocument('/some-hard-coded.pdf')
  const page = await pdfDocument.getPage(1)
  const viewport = pdfPage.getViewport(1)
  const width = 250
  const height = viewport.height * (width / viewport.width)
  const canvas = new OffscreenCanvas(width, height)
  const canvasContext = canvas.getContext('2d', { alpha: false })
  return page.render({ canvasContext, viewport })
})
  1. Call this with e.g. w = new Worker('sample-pdf.js');

What is the expected behavior? (add screenshot)

PDF would render to the OffscreenCanvas

What went wrong? (add screenshot)

ReferenceError: document is not defined at GenericFontLoader.insertRule (pdf.js:10154) at GenericFontLoader.bind (pdf.js:10205) at WorkerTransport.<anonymous> (pdf.js:9177) at LoopbackPort.MessageHandler._onComObjOnMessage (pdf.js:12833) at LoopbackPort.<anonymous> (pdf.js:8681) at Array.forEach (<anonymous>)

i.e. this is failing:

styleElement = this.styleElement = document.createElement(‘style’);

The problem is the absence of a DOM. The issue might be one of documentation, as PDF.js has a Node example, or there may be issues lurking in the deep. In any case I wanted to report it in case there were some obvious guidelines here.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:11
  • Comments:6

github_iconTop GitHub Comments

6reactions
tandat2209commented, Apr 24, 2020

How do you use pdf.js inside a web-worker?

I imported it by this.

// Worker.ts
import { pdfjs } from "react-pdf";
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

pdfjs.getDocument(...) => errors

But when using getDocument. It returns an error

Uncaught (in promise) Error: Setting up fake worker failed: “webpack_require(…).ensure is not a function”

1reaction
GeoffreyChen777commented, Mar 21, 2022

I finally figured out how to use the OffscreenCanvas in a web worker to render the PDF.

In the worker script, we need to use workerPort to set the GlobalWorkerOptions.

const pdfjs = require('pdfjs-dist');
const worker = new Worker('pdf.worker.js');
pdfjs.GlobalWorkerOptions.workerPort = worker;

we also need to provide a fake ownerDocument, If we don’t do that, the PDF can still be rendered, but fonts and figures is incorrect:

    const document = {
      fonts: self.fonts,
      createElement: (name) => {
        if (name == 'canvas') {
          return new OffscreenCanvas(1, 1);
        }
        return null;
      },
    };

    const pdf = await pdfjs.getDocument({
      url, // @ts-ignore
      ownerDocument: document,
    }).promise;

It works good in my project. But I’m not sure if this will cause any potential problems.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Using pdf.js inside a WebWorker? - javascript - Stack Overflow
I'm using pdf.js to generating images from pdf documents. Here is my code import { pdfjs } from "react-pdf"; pdfjs.GlobalWorkerOptions.
Read more >
Rendering PDF Files in the Browser with PDF.js - PSPDFKit
In this tutorial, we'll go a bit deeper and examine one of the most popular open source libraries for rendering PDF files in...
Read more >
How PDF.js Works
In this article, we walk you through how PDF.js works to render PDFs, what technologies it uses, and implications for projects using PDF.js....
Read more >
Rendering PDF pages with PDF.js and Vue - rossta.net
This tutorial demonstrates how to create Vue.js components that can render PDFs along with tools like webpack, PDF.js, and the canvas ...
Read more >
Custom PDF Rendering in JavaScript with Mozilla's PDF.Js
PDF.js supports two modes of rendering. It's default and popular mode of rendering is Canvas based. But it also allows you to render...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found