I hope I don’t break any rules but this is a solution that took me a lot of time to find and I wish it would help someone else.
If you are using React
and want to display a PDF there are several ways, but one of the ones that I needed required me to use the pdfjs-dist
package (for some cases you might encounter the need for @react-pdf-viewer
, which has the same relevance to here as well).
So, to make sure these packages work for you please make sure you use these versions:
"@react-pdf-viewer/core": "^3.4.0",
"pdfjs-dist": "^2.11.338",
and if you want the toolbar use this:
"@react-pdf-viewer/toolbar": "^3.4.0",
(for fast installation use this: npm install @react-pdf-viewer/[email protected] @react-pdf-viewer/[email protected] [email protected]
)
After installing all of the versions, in some required area of the code make these imports:
import { Worker, Viewer } from "@react-pdf-viewer/core";
import "@react-pdf-viewer/core/lib/styles/index.css";
import { toolbarPlugin } from "@react-pdf-viewer/toolbar";
import "@react-pdf-viewer/toolbar/lib/styles/index.css";
import { GlobalWorkerOptions } from "pdfjs-dist";
GlobalWorkerOptions.workerSrc = `https://unpkg.com/[email protected]/build/pdf.worker.min.js`;
I know it not the best practice to put the initialization at the top like so, but to be honest, if it ain’t broken don’t fix it.
After that, in the return part of the RFC do this:
<BlobProvider
document={
<Document>
<Page>
<Text>Something something</Text>
</Page>
</Document>
}>
{({ loading, url, blob }) => (
<div style={{ height: "100%" }}>
{blob && (
<Worker workerUrl={`https://unpkg.com/[email protected]/build/pdf.worker.min.js`}>
<Viewer fileUrl={URL.createObjectURL(blob)} />
</Worker>
)}
</div>
)}
</BlobProvider>
And by then you should have a working PDF viewer that actually works.
I really hope this helped anyone, if not, then this is my way stressing out how terrible of an experience to find out how to make this work this was (especially the versions part).