how can we do pdf merging using javascript

javascript, pdf

Solution

I found an entirely client-side solution using the PDF-LIB library: https://pdf-lib.js.org/

It uses the function mergeAllPDFs which takes one parameter: urls, which is an array of urls to the files.

Make sure to include the following in the header:

<script src='https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.js'></script>
<script src='https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js'></script>

Then:

async function mergeAllPDFs(urls) {
        
    // create an empty PDFLib object of PDFDocument to do the merging into
    const pdfDoc = await PDFLib.PDFDocument.create();
    
    // iterate over all documents to merge
    const numDocs = urls.length;    
    for(var i = 0; i < numDocs; i++) {

        // download the document
        const donorPdfBytes = await fetch(urls[i]).then(res => res.arrayBuffer());

        // load/convert the document into a PDFDocument object
        const donorPdfDoc = await PDFLib.PDFDocument.load(donorPdfBytes);

        // iterate over the document's pages
        const docLength = donorPdfDoc.getPageCount();
        for(var k = 0; k < docLength; k++) {
            // extract the page to copy
            const [donorPage] = await pdfDoc.copyPages(donorPdfDoc, [k]);

            // add the page to the overall merged document
            pdfDoc.addPage(donorPage);
        }
    }
    
    // save as a Base64 URI
    const pdfDataUri = await pdfDoc.saveAsBase64({ dataUri: true });

    // strip off the first part to the first comma "data:image/png;base64,iVBORw0K..."
    const data_pdf = pdfDataUri.substring(pdfDataUri.indexOf(',')+1);
}

Problem

I wanted to do client side scrpting for merging and splitting pdf, so i wanted to use itextsharp. Can that be used with javascript. I am new to Javascript. Please help me with your valuable suggestions.

Original source

Related problems