I want to display a PDF file from within the public folder in my next application using react-pdf but I keep getting the PDF not found error- here's my setup:
// pdf component
import { pdfjs, Document, Page } from "react-pdf";
import pdf from '../../public/document.pdf';
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/build/pdf.worker.min.js',
import.meta.url,
).toString();
// pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`;
const PDFViewer = () => (
<Document file={pdf}>
<Page />
</Document>
)
I imported this component for use in my main component like this:
import dynamic from "next/dynamic";
const PDFViewer = dynamic(() => import('@/components/PDFViewer'), { ssr: false })
export default function Main() {
return (
<div>
<PDFViewer />
</div>
)
}
In the next.config.js I try to config raw-loader package to load PDF file like this:
const nextConfig = {
webpack: (config) => {
config.module.rules.push({
test: /\.(pdf)$/i,
loader: 'file-loader',
options: {
name: './public/document.pdf'
}
})
}
return config
}
The folder structure looks like this:
- project
- components
- pages
- public
- document.pdf
- types
- next.config.js
And here's the message I'm getting in the console:
Warning: MissingPDFException: Missing PDF "http://localhost:3000/_next/public/document.pdf".
How can this be rectified?
I ran into the same issue and I decide to fix it without using the react-pdf. I modified the webpack to this on the next.config.js:
And since Next.js does not recognize pdf files I also created a file called types.d.ts and added:
declare module "*.pdf";I hope it helps