I am using pdfjs and pdf-lib for rendering pdf fetching from ajax call. this is where I get bytes from pdfDoc, set numNumPages and setModifiedPdfBytes.
useEffect(() => {
if (pdfBytes == null) return;
async function modifyAllPages(pdfBytes) {
try {
const pdfDoc = await PDFDocument.load(pdfBytes);
const pages = pdfDoc.getPages();
//....rest of logic
const modifiedPdfBytes = await pdfDoc.save();
return modifiedPdfBytes;
} catch (error) {
throw new Error('Error modifying PDF: ' + error.message);
}
}
async function handleModification() {
try {
// Calculate the number of pages synchronously
const pdfDoc = await PDFDocument.load(pdfBytes);
const pages = pdfDoc.getPages();
setNumPages(pages.length);
// Modify the pages asynchronously
const modifiedPdfBytes = await modifyAllPages(pdfBytes);
setModifiedPdfBytes(modifiedPdfBytes);
console.log('Modified PDF bytes:', modifiedPdfBytes);
} catch (error) {
console.error(error.message);
}
}
handleModification();.
}, [pdfBytes, pdfCryptoInfo]);
and this is where I render it
return (
<>
<div>{base64PdfString}</div>
<div>{numPages}</div>
{
base64PdfString && (
<div ref={setContainerRef}>
{Array.from({ length: numPages || 0 }, (_, index) => index + 1).map((pageNumber) => (
<div
key={pageNumber}
style={{
marginRight: '10px', // Adjust spacing between pages
marginBottom: '10px', // Adjust spacing between pages
display: 'flex',
flexDirection: 'column',
alignItems: 'center'
}}
>
{/* Render each page conditionally based on the current page */}
<PageRenderer
pageNumber={pageNumber}
base64PdfString={base64PdfString}
containerWidth={containerWidth}
/>
</div>
))}
</div>
)}
</>
);
I render twice successively for two pdf doc input. In second call it sees numPages of previous call.
How to consistently pass paramters both base64PdfString and numPages consistently?
I tried this:
// Modify the pages asynchronously
const modifiedPdfBytes = await modifyAllPages(pdfBytes);
setModifiedPdfBytes(modifiedPdfBytes); //added this line for make it sync.