0

I downloaded/installed React-Pdf,

"react-pdf": "^9.2.1",

I need to show a Byte-Array PDF which is dynamically generated.

    const response = await createPdf(payload);

    // Decode Base64-encoded data
    let binaryString = window.atob(response);
    let binaryLen = binaryString.length;
    // Construct an array required by the Blob object
    let bytes = new Uint8Array(binaryLen);
    for (let i = 0; i < binaryLen; i++) {
        let ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
    }

    // Now set state variable
    setPdfByteArray(bytes);

Rendered component:

                {pdfByteArray !== null && 
                <>
                    <Document
                        file={{data: pdfByteArray}}
                        onLoadSuccess={console.log}
                        onLoadError={console.error}
                    >
                    </Document>
                </>        

Error:

Error: No "GlobalWorkerOptions.workerSrc" specified.

Call Stack
get workerSrc
node_modules\react-pdf\node_modules\pdfjs-dist\build\pdf.mjs (12218:1)
PDFWorker._initialize
node_modules\react-pdf\node_modules\pdfjs-dist\build\pdf.mjs (12105:1)
new PDFWorker
node_modules\react-pdf\node_modules\pdfjs-dist\build\pdf.mjs (12073:1)
Module.getDocument
node_modules\react-pdf\node_modules\pdfjs-dist\build\pdf.mjs (11214:1)

So I followed their instructions to Import Worker

For most cases, the following example will work:

import { pdfjs } from 'react-pdf';

pdfjs.GlobalWorkerOptions.workerSrc = new URL(
  'pdfjs-dist/build/pdf.worker.min.mjs',
  import.meta.url,
).toString();

But now it doesn't build, and outputs some huge file to the console. My result from this screen is what's shown in this post's screenshot:

https://github.com/wojtekmaj/react-pdf/issues/1822#issuecomment-2152893933

At the end of yarn build:

                                          ^^^^^^
`----

Caused by:
    0: failed to parse input file
    1: Syntax Error


> Build failed because of webpack errors
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Then I tried the workaround suggested here:

Try to use //unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs this instead of new URL method.

and got this new error:

Error: Setting up fake worker failed: "Failed to fetch dynamically imported module: http://unpkg.com/pdfjs-dist@$%7Bpdfjs.version%7D/build/pdf.worker.min.mjs".
1

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.