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>
)}
</>
);
};
%%EOF, but it has manyendstreamandendobjhere. 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.