I am trying to render a PDF into memory using @react-pdf/renderer
's pdf
method then feed the resulting bytes into pdf-lib
's PDFDocument
object. The reason I'm doing this is because react-pdf
doesn't allow for embedding (merging) other PDFs and the merging library we're using (pdf-merger-js
) doesn't support returning the page numbers of the merged PDF, meaning we can't properly render our table of contents.
What is happening is that after taking the output of @react-pdf/renderer.pdf(...)
, encoding it as base64
and passing it to pdf-lib.PDFDocument.load(...)
, the preview of the resulting PDF in the browser is a bytestring like below. We've had no issue creating this PDF preview before our introduction of pdf-lib
:
The code that is doing this is as follows (toc
== Table of Contents, both arguments are collections of react-pdf
elements):
const mergePdfsToObjectUrl = async (toc: ReactElement, pdfPages: any[]) => {
if (toc && pdfPages?.length > 0) {
const pdfString = await pdf(toc);
const string = await pdfString.toString();
const base64string = encode(string);
const tocPdf = await PDFDocument.load(base64string);
// Create a new document
const doc = await PDFDocument.create();
// Add individual content pages
const tocPdfPages = await doc.copyPages(tocPdf, tocPdf.getPageIndices());
for (const page of tocPdfPages) {
doc.addPage(page);
}
// Write the PDF to a file
const pdfBytes = await doc.save();
const url = URL.createObjectURL(new Blob([pdfBytes]));
return url;
}
I've tried everything from different codecs to different pipelines for transforming the react-pdf
data into a usable bytestring, but nothing seems to work.