0

I'm trying to render a large PDF file from my S3 storage in chunks using React-PDF (PDF.js). I'm fetching the first 64KB of the PDF with a byte range request, but the PDF fails to load, showing the error "Failed to load PDF document." My goal is to load the first page of the PDF initially and then load additional pages as needed. Below is my current code:

    useEffect(() => {
    const loadPdf = async () => {
      try {
        const response = await fetch(
          "http://localhost:8080/encoded-file/66c3286c13b7b76bdf1d1d3c",
          {
            headers: {
              Range: "bytes=0-65535", // Request first 64KB chunk
            },
          }
        );
        const base64Data = await response.text();
        const pdfDataUri = `data:application/pdf;base64,${base64Data}`;
        setPdfData(pdfDataUri);
      } catch (error) {
        console.error("Error loading PDF:", error);
      }
    };

    loadPdf();
  }, []);

  return (
    <>
      {pdfData && (
        <Document
          file={pdfData}
          onError={(error) => console.log(error)}
          onLoadSuccess={(result) => setPageCount(result._pdfInfo.numPages)}
        >
          <div
            style={{
              height: window.innerHeight * 0.8,
              overflow: "scroll",
            }}
          >
            {[...Array(pageCount)].map((x, i) => (
              <Page
                key={i}
                pageNumber={i + 1}
                width={window.innerWidth * 0.4}
                height={window.innerHeight * 0.8}
              />
            ))}
          </div>
        </Document>
      )}
    </>
  );
};
2
  • Yeah the PDF binary raw has only 2 %%EOF, but it has many endstream and endobj here. i am talking about Linearized PDF which is obvious from the header `<</Linearized 1/L 14897021/O 153/E 112648/N 27/T 14896410/H [ 591 329]>>. the pdf.js is trying to download the whole file then renders it in my implementation. Commented Aug 19, 2024 at 14:07
  • The example seems decent actually, will check it. Commented Aug 19, 2024 at 20:47

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.