As mentioned in the
Setting up the worker section, the worker version has to be the same as the version of
`pdfjs-dist`
package.
Otherwise, you you will see the error message like this:
The API version "2.6.347" does not match the Worker version "2.1.266"
Where `2.6.347`
is the version of `pdfjs-dist`
that you can see in the `package.json`
file:
{
"dependencies": {
"pdfjs-dist": "^2.6.347",
...
}
}
And `2.1.266`
is the version of Worker which is passed to the `Worker`
component as
<Worker workerUrl="https://unpkg.com/pdfjs-dist@2.1.266/build/pdf.worker.min.js">...</Worker>
It isn't convenient and error prone when you upgrade `pdfjs-dist`
but forget to set the same version for the worker.
This post demonstrates a simple way that uses the
Webpack bundler to compile and set up the worker source based on the current installed
`pdfjs-dist`
package.
Install worker-loader
npm install --save-dev worker-loader
Set the pdfjs-dist path
Ask Webpack to load `pdfjs-dist/webpack`
when it sees `pdfjs-dist`
import. Change your Webpack configuration as following:
const path = require('path');
const webpack = require('webpack');
module.exports = {
plugins: [
new webpack.NormalModuleReplacementPlugin(
/^pdfjs-dist$/,
resource => {
resource.request = path.join(__dirname, './node_modules/pdfjs-dist/webpack');
},
),
...
],
};
Build pdfjs worker
const path = require('path');
module.exports = {
entry: {
main: './src/index.tsx',
'pdf.worker': path.join(__dirname, './node_modules/pdfjs-dist/build/pdf.worker.js'),
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].bundle.js'
},
...
};
Webpack will build a worker named `pdf.worker.bundle.worker.js`
located in the `dist`
directory.
Set the worker source
Finally, you can set the worker source to the file compiled in the previous section:
import { Worker } from '@react-pdf-viewer/core';
<Worker workerUrl="/pdf.worker.bundle.worker.js">...</Worker>;