Javacript source code to merge multiple pdf files to a single pdf file

This article provides the source code in JavaScript to merge multiple PDF files. If you have a large number of PDF files and want to share them with friends, you may ike to merge the pdf files together and send a single pdf file.

Here is the source code. You may place the source code in the head or body tag of your html page file

    <script src="https://cdn.jsdelivr.net/npm/pdf-lib@1.14.0/dist/pdf-lib.min.js"></script>
    <script>
      const pdfFilesInput = document.getElementById('pdf-files');
      const mergeBtn = document.getElementById('merge-btn');
      const clearBtn = document.getElementById('clear-btn');
      
        mergeBtn.addEventListener('click', async () => {
       
          const pdfFiles = pdfFilesInput.files;
          if (pdfFiles.length === 0) {alert("Select Pdf File"); return;} 
          const numFiles = Math.min(20, pdfFiles.length); 
          if(numFiles<20){
            const mergedPdf = await PDFLib.PDFDocument.create();

            for (let i = 0; i < numFiles; i++) {
              const pdfFile = pdfFiles[i];
              const pdfBytes = await pdfFile.arrayBuffer();
              const pdfDoc = await PDFLib.PDFDocument.load(pdfBytes);
              const pages = await mergedPdf.copyPages(pdfDoc, pdfDoc.getPageIndices());
              pages.forEach(page => mergedPdf.addPage(page));
            }

            const mergedPdfBytes = await mergedPdf.save();
            const mergedPdfBlob = new Blob([mergedPdfBytes], { type: 'application/pdf' });
            const mergedPdfUrl = URL.createObjectURL(mergedPdfBlob);

            const downloadLink = document.createElement('a');
            downloadLink.href = mergedPdfUrl;
            downloadLink.download = 'merged.pdf';
            downloadLink.click();
          }
          else{
            alert("Limit exceded");
            location.reload();
            pdfFilesInput.value = '';
          }
        });
        clearBtn.addEventListener('click', () => {
          location.reload();
          pdfFilesInput.value = '';
        });
 document.querySelectorAll(".drop-zone__input").forEach((inputElement) => {
      const dropZoneElement = inputElement.closest(".drop-zone");

      dropZoneElement.addEventListener("ondrop", (e) => {
        inputElement.click();
      });

      inputElement.addEventListener("change", (e) => {
        if (inputElement.files.length) {
          updateThumbnail(dropZoneElement, inputElement.files[0]);
        }
      });

      dropZoneElement.addEventListener("dragover", (e) => {
        e.preventDefault();
        dropZoneElement.classList.add("drop-zone--over");
      });

      ["dragleave", "dragend"].forEach((type) => {
        dropZoneElement.addEventListener(type, (e) => {
          dropZoneElement.classList.remove("drop-zone--over");
        });
      });

      dropZoneElement.addEventListener("drop", (e) => {
        e.preventDefault();
        if (e.dataTransfer.files.length) {
          inputElement.files = e.dataTransfer.files;
          updateThumbnail(dropZoneElement, e.dataTransfer.files[0]);
        }
        dropZoneElement.classList.remove("drop-zone--over");
      });
    });
   </script>


That is all.

If you liked this article please do leave a reply and share it with friends.

Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.