Run PDF.js canvas rendering in a web-worker
See original GitHub issueConfiguration:
- Chrome 71
- Operating system and its version: any
- PDF.js version: 2.0.943
- Is a browser extension: no
Steps to reproduce the problem:
- 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 })
})
- 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:
- Created 5 years ago
- Reactions:11
- Comments:6
Top GitHub Comments
How do you use pdf.js inside a web-worker?
I imported it by this.
But when using
getDocument
. It returns an errorI 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
.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:
It works good in my project. But I’m not sure if this will cause any potential problems.