How to merge PDF generated with react-pdf with an existing PDF? (JS/node.js)

Viewed 1449

My task: I generate a PDF with react-pdf based on data in my app. Then I want to merge this generated PDF with an already existing PDF.

My problem: With react-pdf I can get access to the document's blob data, but as far as I understand, this file is not saved anywhere. However, all JS tools for merging PDFs I found, enable you to merge PDFs only if you pass paths to files.

Can you see any solutions to this problem? My idea was to save this generated PDF server-side, transform it somehow to PDF from BLOB, use some merging tool and then bring back the final merged PDF to client-side, but it seems quite (too?) complicated.

1 Answers

Here it my code for the same situation as you:

<Button
        className={classes.download}
        onClick={
            async () => {
                const doc = <InvoicePDF number={number} date={date} totalHours={totalHours} formattedHours={formattedHours} />
                const asPdf = pdf()

                asPdf.updateContainer(doc)

                let initialBlob = new Blob([fileRef.current.files[0]], { type: 'application/pdf' })
                let appendixBlob = await asPdf.toBlob()

                let merger = new PDFMerger()
                await Promise.all([initialBlob, appendixBlob].map(async (file) => await merger.add(file, null)))

                const mergedPdf = await merger.saveAsBlob()
                // merger = null
                // initialBlob = null
                // appendixBlob = null

                saveAs(mergedPdf, `Appendix${number}.pdf`)
            }}
    >
        Download
    </Button>

Where InvoicePDF is created with react-pdf/renderer and with pdf-merger-js I merge them.

It works, it does what it needs, but sometimes it does not merge them in the order I need.

Related