Reputation: 1
I'm trying to render a PDF with PDFJS, but get a warning Setting up fake worker
. What does it mean in practice?
console
Warning: Setting up fake worker.
code
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/pdf.js/3.0.279/pdf.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/pdf.js/3.0.279/pdf.worker.min.js"></script>
</head>
<body>
<canvas id="pdf"></canvas>
</body>
<script>
'use strict';
let pdfPath = 'https://path-to-pdf.pdf';
pdfjsLib.getDocument(pdfPath).promise.then(pdf=>{
pdf.getPage(1).then(page=>{
const viewport = page.getViewport({scale: 1}), canvas = document.getElementById('pdf'), context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
const renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
}).then(_=>{
}, err=>{
console.error('Error: '+err);
});
</script>
</html>
Upvotes: 0
Views: 5592
Reputation: 1
The reason you're getting the fake worker and the warning is because you're importing pdf.worker.min.js in your HTML file. What you should be doing instead is setting
GlobalWorkerOptions.workerSrc = './pdf.worker.min.js'
as kca notes. But also remove the HTML script import.
Upvotes: -1
Reputation: 6121
The pdfjs "fake worker" behaves in the same way as the "real" worker does, but it runs in the main thread instead of a web worker.
Always use a real worker, ignoring this warning will make the website slow.
pdfjs expects you to provide the location of the pdf.worker.js
file (or pdf.worker.min.js
), which comes with the pdfjs package (currently under /node_modules/pdfjs-dist/build/pdf.worker.js
).
If the worker is correctly provided and its location specified, then pdfjs will create a web worker which will render PDF files "in the background", i.e. not blocking the main thread. I.e. the website stays responsive while the PDF is created.
If you don't set the pdf-worker, or the pdf-worker can not be found in the location that you specified, then pdfjs doesn't create a web worker, but something that looks exactly like the web worker but runs in the main thread.
As this affects the performance of the website a lot (and most often is a mistake, not intentional), pdfjs prints a warning in the console Setting up fake worker
.
Generally:
pdf.worker.js
(or pdf.worker.min.js
) must be available,To solve the problem there are different ways, also depending on the environment and framework. Here are some hints:
pdf.worker.js
is reachable for your script (e.g. check by typing http://localhost:3000/pdf.worker.js
in the browsers address bar). One option is to copy the file pdf.worker.js
into a folder that can be reached by the browser (aka. "public folder").pdf.worker.js
file, like pdfjs.GlobalWorkerOptions.workerSrc = './pdf.worker.min.js'
pdfjs
and pdf.worker.js
are the sameUpvotes: 1