Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

55
Views
Output of react-pdf/renderer not compatible with pdf-lib

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:

bytestring-pdf

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.

7 months ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.