简体   繁体   中英

Problem displaying PDF in React from UInt8Array (react-pdf)

I'm trying to build a PDF viewer in React, I've already built the backend to upload the files and fetch the buffer data. But I'm having some problems with react-pdf, as I can't seem to serve the right type of data. This is the code I've written:

const [data, setData] = useState();
  useEffect(() => {
    fetch("http://localhost:5000/files/pdf-test.pdf")
      .then((res) => res.text())
      .then((res) => setData(new Buffer(res, "binary")));
  });

  return (
    <>
      <Document file={{ data: data }} />
    </>
  );

This is one of the few tries I've made, in this one the backend serves the binary data of the file, and if we console log the last .then we can see that I'm serving the Document a UInt8Array, which is the recommended data format:

数据

Apart from the code in the image, I've also tried it with binary and an ArrayBuffer, but still no results, changing both the backend and frontend code. The error I get is: 在此处输入图像描述

TL;DR : I'm trying to display PDF files in React with react-pdf using their buffer but I can't manage to do it. I have already made a backend to upload files (express-fileupload) and store them so that their data can be fetched.

Thank u for helping, and I'm open to other approaches to the problem

For RCA (react-create-app) you need to config the worker in order to view your PDF file.

import { Document, Page, pdfjs } from 'react-pdf';

Then configure it like this:

pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

Usage:

const [uint8Arr, setUint8Arr] = useState();

function getUint8Array() {
 let reader = new FileReader();

            // reader.readAsDataURL(selectedFile); base64
            reader.readAsArrayBuffer(selectedFile);
            reader.onloadend = async (e) => {
                if ( e.target?.result instanceof ArrayBuffer) {
                    const uint8Array = new Uint8Array(e.target.result);
                    setUint8Arr(uint8Array) <---- 

                    // more callbacks(file.name, Buffer.from(new Uint8Array(target.result)));
                }
            };
}
<Document file={{
            data: uint8Arr <----
        }} onLoadSuccess={() => console.log('SUCCESS LOAD')}>
            <Page pageNumber={1} />
        </Document>

Hope that this will fix your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM