Homelab, Linux, JS & ABAP (~˘▾˘)~
 

[nodejs] Merge PDFs using pdf-lib

https://github.com/Hopding/pdf-lib

const { PDFDocument } = require('pdf-lib')

// files = [{ fileName: 'test1.pdf, content: arraybuffer },{ fileName: 'test2.pdf, content: arraybuffer }]

mergePdfs: async function (files) {
        try {
            const mergedPdf = await PDFDocument.create()

            for (let file of files) {
                const pdf = await PDFDocument.load(file.content)
                const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices())
                copiedPages.forEach((page) => mergedPdf.addPage(page))
            }

            const mergedPdfFile = await mergedPdf.save()
            const buffer = Buffer.from(mergedPdfFile)
            return await buffer.toString('base64') // return as buffer or base64 encoded file
        } catch (err) {
            console.error(err.message)
        }
}

[JavaScript] Download base64 encoded file within a browser

            const sBase64 = "JVBERi0xLjQKJcOkw7zDtsOfCjIgMCBvYmoKPDwvTGVuZ3....."
            const arrayBuffer = new Uint8Array([...window.atob(sBase64)].map(char => char.charCodeAt(0)))
            const fileLink = document.createElement('a')

            fileLink.href = window.URL.createObjectURL(new Blob([arrayBuffer]))
            fileLink.setAttribute('download', "example.pdf")
            document.body.appendChild(fileLink)
            fileLink.click()

Or use the npm package FileSaver.

import { saveAs } from "file-saver";

const sBase64 = "JVBERi0xLjQKJcOkw7zDtsOfCjIgMCBvYmoKPDwvTGVuZ3....."
const buffer = Buffer.from(sBase64, "base64") //Buffer is only available when using nodejs
saveAs(new Blob([buffer]), "example.pdf")