» npm install pdfjs-dist
Videos
What is PDF.js used for?
Is PDF.js free to use?
How to use PDF.js in React?
Here's a super ugly workaround for client-components, until something better is proposed (I hate this too, but it works):
npm i pdfjs-dist
Edit 1: A hook might be better for reusability:
Create Your Hook
"use client";
import {useEffect} from "react";
import * as PDFJS from "pdfjs-dist/types/src/pdf";
export const usePDFJS = (onLoad: (pdfjs: typeof PDFJS) => Promise<void>, deps: (string | number | boolean | undefined | null)[] = []) => {
const [pdfjs, setPDFJS] = useState<typeof PDFJS>(null);
// load the library once on mount (the webpack import automatically sets-up the worker)
useEffect(() => {
import("pdfjs-dist/webpack.mjs").then(setPDFJS)
}, []);
// execute the callback function whenever PDFJS loads (or a custom dependency-array updates)
useEffect(() => {
if(!pdfjs) return;
(async () => await onLoad(pdfjs))();
}, [ pdfjs, ...deps ]);
}
Typescript Fix
Your compiler might complain about a typescript issue; if so, I just added an index.d.ts (note the .d.ts) at the same level as my hook:
declare module 'pdfjs-dist/webpack.mjs' { export * from 'pdfjs-dist' }
Use Your Hook
"use client";
import {usePDFJS} from "...";
export default function Page() {
usePDFJS(async (pdfjs) => {
console.log(pdfjs)
})
}
There's a pretty lengthy discussion over on Github issues where people have managed to get it working either on client:
I decided to follow a simple path, I downloaded the stable version from the official website. I put all the files in the public folder. Then I added this tag to my component:
<script src="/pdfjs/pdf.mjs" type="module" />
then adding code in useEffect:
const pdfjs = window.pdfjsLib as typeof import('pdfjs-dist/types/src/pdf')
const pdfjsWorker = await import('pdfjs-dist/build/pdf.worker.min.mjs');
pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;
const pdfDocument = pdfjs.getDocument('http://localhost:3000/pdf-files/myFile.pdf')
console.log('pdfDocument', pdfDocument);
Or server-side, via appDir (e.g. app/api/pdf/route.js)
import * as pdfjs from 'pdfjs-dist/build/pdf.min.mjs';
await import('pdfjs-dist/build/pdf.worker.min.mjs');
export async function POST(req, res) {
const pdf = await pdfjs.getDocument(
'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf'
).promise;
const page = await pdf.getPage(1);
const textContent = await page.getTextContent();
return NextResponse.json({ message: textContent }, { status: 200 });
}
I've personally just tested this last API-one on Next.js 14.1.1 and it works just fine after a npm install pdfjs-dist
i am trying to make an view page of the pdf create using jspdf twith the help of pdfjs-dist ini vue 3.
vue - 3.4.21
pdfjs-dist - 4.3.136
jspdf - 2.5.1
This issue seems to arise due to esModule option introduced in [email protected].
The fix for this was merged in (pre-release) [email protected]
You can fix this by either upgrading pdfjs-dist to v2.6.347 OR downgrading worker-loader to v2.0.0
I just had to solve this issue myself...
This issue
Module not found: Error: Can't resolve 'module' in '/home/giampaolo/dev/KJ_import/KJ-JS/node_modules/webpack/lib/node'
Is caused by worker-loader loading NodeTargetPlugin, which in turn runs require("module") which I think (but I'm not 100%) is for native node modules, which when running Webpack targeted for web is not relevant
This issue can be mitigated with Webpack config
{
node: {
module: "empty"
}
}
Afterwards, things move along farther, but I needed further mitigations:
import pdfjsLib from "pdfjs-dist/webpack";
This runs pdfjs-dist/webpack.js:27 which is
var PdfjsWorker = require("worker-loader!./build/pdf.worker.js");
Which is attempting to load pdf.worker.js (which worker-loader should be packaging) and then tries to instantiate the class:
pdfjs.GlobalWorkerOptions.workerPort = new PdfjsWorker();
The issue I had was that Webpack packaged pdf.worker.js as an esModule (the default for worker-loader), so the way it was require'd needs to be unwrapped with the default property on the imported esModule (said another way, the instantiation would have to be new PdfjsWorker.default()
I was able to mitigate this with the NormalModuleReplacementPlugin plugin, which is able to re-write the require statement based on a regex match/replace, which is matching the original require string and replacing it with one that sets the worker-loader option esModule=false, followed by the absolute path to the pdf.worker.js file on the local system:
new webpack.NormalModuleReplacementPlugin(
/worker-loader!\.\/build\/pdf\.worker\.js$/,
"worker-loader?esModule=false!" + path.join(__dirname, "../", "node_modules", "pdfjs-dist", "build", "pdf.worker.js")
)
It's important to match the complete original require string of /worker-loader!\.\/build\/pdf\.worker\.js$/ and not just the pdf.worker.js part, because you could end up in an infinite replace loop.
You need to fix the replacement string to be a proper path for your project, which would probably be
"worker-loader?esModule=false!" + path.join(__dirname, "node_modules", "pdfjs-dist", "build", "pdf.worker.js")
I have a ../ in my path because this code is being executed inside storybooks .storybook/ folder, so I have go up a directory to get to node_modules/
And with those two changes, everything for PDF.js seems to be working.
And lastly, if you want to ignore the warnings about the missing FetchCompileWasmPlugin and FetchCompileAsyncWasmPlugin modules, you can setup the webpack IgnorePlugin to just ignore these imports, my assumption is they're WASM based and not actually needed
plugins: [
new webpack.IgnorePlugin({ resourceRegExp: /FetchCompileWasmPlugin$/ }),
new webpack.IgnorePlugin({ resourceRegExp: /FetchCompileAsyncWasmPlugin$/ })
]
I'm guessing there might be some out-of-date mismatch of worker-loader and the modules in the currently installed Webpack version, but these WASM modules don't seem to be necessary for our purposes