\n\n```\n\n* We'll use **pdf-lib** to merge and modify PDFs\n\n* We'll use **pdf.js** to render previews in the browser\n\nThis combination is very powerful and commonly used in real projects.\n\n## Creating the Upload Interface\n\nStart with a simple drag-and-drop area:\n\n```\n
\n \n
\n```\n\nUsers can either drag files or click to select.\n\nOnce files are selected, we read them using:\n\n```\nconst arrayBuffer = await file.arrayBuffer();\n```\n\nThis allows us to pass the file into our PDF libraries.\n\n## Rendering PDF Previews\n\nTo improve usability, we'll show a preview of each uploaded PDF.\n\nUsing **pdf.js**, we can render pages like this:\n\n```\nconst pdf = await pdfjsLib.getDocument(arrayBuffer).promise;\nconst page = await pdf.getPage(1);\n\nconst viewport = page.getViewport({ scale: 1.5 });\ncanvas.height = viewport.height;\ncanvas.width = viewport.width;\n\npage.render({\n canvasContext: context,\n viewport: viewport\n});\n```\n\nThis gives users visual feedback before merging.\n\n## Reordering Files (Drag and Drop)\n\nOrder matters when merging PDFs.\n\nInstead of forcing users to upload in sequence, we'll allow reordering.\n\nWe can use a library like **Sortable.js** for this:\n\n```\nnew Sortable(document.getElementById('pdf-grid'), {\n animation: 150\n});\n```\n\nThis enables drag-and-drop sorting and instant visual updates.\n\n## Sorting and Reordering PDFs (Important)\n\nThis is where the tool becomes more practical in real-world use.\n\nInstead of forcing users to upload files in a specific order, the tool allows them to rearrange PDFs before merging.\n\nUsers can manually drag and drop files to adjust the sequence, or use built-in sorting options such as arranging files alphabetically or by file size. This makes it easy to quickly organize multiple documents without re-uploading them.\n\nThis flexibility ensures that the final merged document follows the exact order the user needs. In real-world scenarios, this is especially useful when combining reports, invoices, or other documents where sequence is important.\n\nHere’s a simple example of how you might sort uploaded files:\n\n```\nfunction sortFiles(files, type) {\n return files.sort((a, b) => {\n if (type === \"name-asc\") {\n return a.name.localeCompare(b.name);\n }\n\n if (type === \"name-desc\") {\n return b.name.localeCompare(a.name);\n }\n\n if (type === \"size-asc\") {\n return a.size - b.size;\n }\n\n if (type === \"size-desc\") {\n return b.size - a.size;\n }\n\n return 0;\n });\n}\n```\n\nThis allows precise control over what gets merged.\n\n## Merging PDFs Using JavaScript\n\nNow comes the core logic. We'll use **pdf-lib** to combine pages:\n\n```\nconst { PDFDocument } = PDFLib;\n\nconst mergedPdf = await PDFDocument.create();\n\nfor (const file of files) {\n const pdf = await PDFDocument.load(file.arrayBuffer);\n const pages = await mergedPdf.copyPages(pdf, selectedPages);\n\n pages.forEach(page => mergedPdf.addPage(page));\n}\n\nconst pdfBytes = await mergedPdf.save();\n```\n\nFinally, we'll create a downloadable file:\n\n```\nconst blob = new Blob([pdfBytes], { type: 'application/pdf' });\n```\n\n## Improving User Experience\n\nA simple merge tool works, but a good tool feels smooth.\n\nSmall improvements make a big difference.\n\nFor example:\n\n* showing previews before merging\n\n* allowing users to remove files\n\n* enabling page navigation\n\n* providing instant feedback\n\nThese details turn a basic feature into a real product.\n\n## Demo: How the PDF Merger Works\n\nHere’s how the full flow looks in practice:\n\n### Step 1: Upload PDFs\n\n![Image 3: PDF merger tool interface showing drag and drop upload area with select files button](https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/f7b544ed-e1df-40c2-a2bd-c9245850d7b5.png)\nUsers can drag and drop PDF files into the upload area or select them manually.\n\n### Step 2: Preview Files\n\n![Image 4: Preview of uploaded PDF files showing document thumbnails and file details before merging](https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/a60a38b9-d535-4856-afbf-3a9ccb427d2d.png)\nEach uploaded file is displayed with a preview as well as pdf files details (name, size, nos of page, and so on), so users can verify the content before merging.\n\n### Step 3: Reorder Files\n\n![Image 5: PDF sorting options interface showing manual order and sorting by name or file size](https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/6c93b3da-3857-4760-a64b-87edc739178e.png)\nUsers can arrange the order of PDFs using drag-and-drop or sorting options as well as manual options. This ensures the final merged document follows the correct sequence.\n\n### Step 4: Merge PDFs\n\n![Image 6: Merge PDFs button used to combine multiple PDF files into a single document](https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/5b8f22ab-ca44-4686-9c3a-647983e6ae08.png)\nOnce everything is arranged, users can click the merge button to combine all selected PDFs into a single file.\n\n### Step 5: Download the Final PDF\n\n![Image 7: Merged PDF preview with file details and download button after combining documents](https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/d55d61d9-ac46-4c22-8f64-885a87d693cc.png)\nThe merged PDF is generated instantly in the browser, and users can preview , rename, and download it without any server interaction.\n\n## Important Notes from Real-World Use\n\nWhen building tools like a PDF merger, handling large files efficiently becomes important.\n\nIf multiple large PDFs are loaded at once, it can slow down the browser or consume too much memory. Instead of processing everything at once, it’s better to handle files step by step.\n\nFor example, instead of loading all PDFs together, you can process them one by one:\n\n```\nconst { PDFDocument } = PDFLib;\n\nconst mergedPdf = await PDFDocument.create();\n\nfor (const file of files) {\n const arrayBuffer = await file.arrayBuffer();\n const pdf = await PDFDocument.load(arrayBuffer);\n\n const pages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());\n\n pages.forEach(page => mergedPdf.addPage(page));\n}\n```\n\nThis approach keeps memory usage lower and avoids freezing the browser when working with larger files.\n\nYou can also improve performance by limiting file size or the number of files users can upload at once. This helps keep the tool responsive even on lower-powered devices.\n\nAnother important aspect is privacy. Since everything runs directly in the browser, files are never uploaded to a server. This means sensitive documents stay on the user’s device.\n\nBut it’s still important to be transparent about this. In real-world tools, you should clearly mention that all processing happens locally and no files are stored or transmitted.\n\nThis client-side approach improves both performance and user trust, especially when working with private or confidential documents.\n\n## Common Mistakes to Avoid\n\nA common mistake is skipping validation. If users upload invalid files or empty inputs, the merge process can fail.\n\nAnother issue is ignoring page ranges. If parsing is incorrect, users may get unexpected results.\n\nAlso, relying on fixed layouts or assumptions can break the experience across different files. Testing with different PDF types is important.\n\n## Conclusion\n\nIn this tutorial, you built a browser-based PDF merger using JavaScript.\n\nMore importantly, you learned how to process files locally in the browser, render previews for better usability, handle user input safely, and manage dynamic document structures when working with PDFs.\n\nThis approach removes the need for a backend and keeps everything fast, private, and efficient.\n\nOnce you understand this pattern, you can extend it to build more advanced tools. For example, you could create features like PDF splitting, compression, editing, or other document-based utilities using the same core ideas.\n\nAnd that’s where things start getting really interesting.\n\n* * *\n\n* * *\n\nLearn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. [Get started](https://www.freecodecamp.org/learn)","speakable":{"@type":"SpeakableSpecification","cssSelector":["[data-speakable='summary']","[data-speakable='takeaways']"]},"author":{"@type":"Organization","name":"freeCodeCamp.org","url":"https://www.freecodecamp.org"},"publisher":{"@type":"Organization","name":"traeai","url":"https://www.traeai.com","logo":{"@type":"ImageObject","url":"https://www.traeai.com/icon.svg"},"sameAs":["https://github.com/cq0206/traeai"]},"mainEntityOfPage":"https://www.traeai.com/articles/d98b2ce3-5644-49f1-a8b1-05fd3ee035c4"},{"@type":"WebSite","@id":"https://www.traeai.com/#website","url":"https://www.traeai.com","name":"traeai","description":"traeai 为开发者、研究员和内容团队筛选高质量 AI 技术内容,提供摘要、评分、趋势雷达与知识库产出。","inLanguage":["zh-CN","en"],"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://www.traeai.com/?q={search_term_string}"},"query-input":"required name=search_term_string"}},{"@type":"BreadcrumbList","@id":"https://www.traeai.com/articles/d98b2ce3-5644-49f1-a8b1-05fd3ee035c4#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"首页","item":"https://www.traeai.com/"},{"@type":"ListItem","position":2,"name":"文章","item":"https://www.traeai.com/brief"},{"@type":"ListItem","position":3,"name":"freeCodeCamp.org","item":"https://www.traeai.com/sources"},{"@type":"ListItem","position":4,"name":"How to Merge PDF Files in the Browser Using JavaScript (Step-by-Step)","item":"https://www.traeai.com/articles/d98b2ce3-5644-49f1-a8b1-05fd3ee035c4"}]}]}
freeCodeCamp.org

How to Merge PDF Files in the Browser Using JavaScript (Step-by-Step)

7.8内容质量
How to Merge PDF Files in the Browser Using JavaScript (Step-by-Step)

TL;DR · AI 摘要

介绍如何使用 JavaScript 在浏览器中合并 PDF 文件,无需后端支持。

核心要点

  • 实现拖放上传和页面选择功能
  • 基于浏览器完成 PDF 合并
  • 适合处理隐私敏感文件
#JavaScript#PDF#前端
打开原文
Image 1: How to Merge PDF Files in the Browser Using JavaScript (Step-by-Step)
Image 1: How to Merge PDF Files in the Browser Using JavaScript (Step-by-Step)

Working with PDFs is something almost every developer needs to know how to do.

Sometimes you need to combine reports or invoices, or simply merge multiple documents into a single clean file.

Most tools that handle this either require installing software or uploading files to a server, which can be slow and not always ideal – especially when dealing with private documents.

But what if you could merge PDFs directly in the browser, without any backend?

That’s exactly what we’ll build in this tutorial.

By the end, you’ll have a fully working browser-based PDF merger. It will allow users to upload files, preview them, reorder documents using drag-and-drop, select specific pages, and download the final merged PDF instantly.

Image 2: Browser-based PDF merger tool with drag-and-drop upload interface
Image 2: Browser-based PDF merger tool with drag-and-drop upload interface

Table of Contents

  1. How PDF Merging Works in the Browser
  1. Project Setup
  1. What Library Are We Using?
  1. Creating the Upload Interface
  1. Rendering PDF Previews
  1. Reordering Files Drag and Drop
  1. Sorting and Reordering PDFs (Important)
  1. Merging PDFs Using JavaScript
  1. Improving User Experience
  1. Demo: How the PDF Merger Works
  1. Important Notes from Real-World Use
  1. Common Mistakes to Avoid
  1. Conclusion

How PDF Merging Works in the Browser

At a high level, merging PDFs means loading multiple PDF files, extracting pages from each, and combining them into a single document.

Traditionally, this process happens on a server. Files are uploaded, processed, and then returned to the user.

But modern JavaScript libraries make it possible to do all of this directly in the browser. Instead of sending files anywhere, the entire process runs locally on the user’s device.

This approach has a few practical advantages. It makes the process faster because there’s no upload time involved. It also improves privacy, since files never leave the user’s system. And from a development perspective, it removes the need for backend processing altogether.

Project Setup

We’ll keep this project simple.

You only need:

  • an HTML file
  • JavaScript
  • a few libraries

No backend required.

What Library Are We Using?

We’ll use two important libraries:

code
<script src="https://unpkg.com/[email protected]/dist/pdf-lib.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.min.js"></script>
  • We'll use pdf-lib to merge and modify PDFs
  • We'll use pdf.js to render previews in the browser

This combination is very powerful and commonly used in real projects.

Creating the Upload Interface

Start with a simple drag-and-drop area:

code
<div id="upload-area">
  <input type="file" id="file-input" multiple accept="application/pdf">
</div>

Users can either drag files or click to select.

Once files are selected, we read them using:

code
const arrayBuffer = await file.arrayBuffer();

This allows us to pass the file into our PDF libraries.

Rendering PDF Previews

To improve usability, we'll show a preview of each uploaded PDF.

Using pdf.js, we can render pages like this:

code
const pdf = await pdfjsLib.getDocument(arrayBuffer).promise;
const page = await pdf.getPage(1);

const viewport = page.getViewport({ scale: 1.5 });
canvas.height = viewport.height;
canvas.width = viewport.width;

page.render({
  canvasContext: context,
  viewport: viewport
});

This gives users visual feedback before merging.

Reordering Files (Drag and Drop)

Order matters when merging PDFs.

Instead of forcing users to upload in sequence, we'll allow reordering.

We can use a library like Sortable.js for this:

code
new Sortable(document.getElementById('pdf-grid'), {
  animation: 150
});

This enables drag-and-drop sorting and instant visual updates.

Sorting and Reordering PDFs (Important)

This is where the tool becomes more practical in real-world use.

Instead of forcing users to upload files in a specific order, the tool allows them to rearrange PDFs before merging.

Users can manually drag and drop files to adjust the sequence, or use built-in sorting options such as arranging files alphabetically or by file size. This makes it easy to quickly organize multiple documents without re-uploading them.

This flexibility ensures that the final merged document follows the exact order the user needs. In real-world scenarios, this is especially useful when combining reports, invoices, or other documents where sequence is important.

Here’s a simple example of how you might sort uploaded files:

code
function sortFiles(files, type) {
  return files.sort((a, b) => {
    if (type === "name-asc") {
      return a.name.localeCompare(b.name);
    }

    if (type === "name-desc") {
      return b.name.localeCompare(a.name);
    }

    if (type === "size-asc") {
      return a.size - b.size;
    }

    if (type === "size-desc") {
      return b.size - a.size;
    }

    return 0;
  });
}

This allows precise control over what gets merged.

Merging PDFs Using JavaScript

Now comes the core logic. We'll use pdf-lib to combine pages:

code
const { PDFDocument } = PDFLib;

const mergedPdf = await PDFDocument.create();

for (const file of files) {
  const pdf = await PDFDocument.load(file.arrayBuffer);
  const pages = await mergedPdf.copyPages(pdf, selectedPages);

  pages.forEach(page => mergedPdf.addPage(page));
}

const pdfBytes = await mergedPdf.save();

Finally, we'll create a downloadable file:

code
const blob = new Blob([pdfBytes], { type: 'application/pdf' });

Improving User Experience

A simple merge tool works, but a good tool feels smooth.

Small improvements make a big difference.

For example:

  • showing previews before merging
  • allowing users to remove files
  • enabling page navigation
  • providing instant feedback

These details turn a basic feature into a real product.

Demo: How the PDF Merger Works

Here’s how the full flow looks in practice:

Step 1: Upload PDFs

Image 3: PDF merger tool interface showing drag and drop upload area with select files button
Image 3: PDF merger tool interface showing drag and drop upload area with select files button

Users can drag and drop PDF files into the upload area or select them manually.

Step 2: Preview Files

Image 4: Preview of uploaded PDF files showing document thumbnails and file details before merging
Image 4: Preview of uploaded PDF files showing document thumbnails and file details before merging

Each uploaded file is displayed with a preview as well as pdf files details (name, size, nos of page, and so on), so users can verify the content before merging.

Step 3: Reorder Files

Image 5: PDF sorting options interface showing manual order and sorting by name or file size
Image 5: PDF sorting options interface showing manual order and sorting by name or file size

Users can arrange the order of PDFs using drag-and-drop or sorting options as well as manual options. This ensures the final merged document follows the correct sequence.

Step 4: Merge PDFs

Image 6: Merge PDFs button used to combine multiple PDF files into a single document
Image 6: Merge PDFs button used to combine multiple PDF files into a single document

Once everything is arranged, users can click the merge button to combine all selected PDFs into a single file.

Step 5: Download the Final PDF

Image 7: Merged PDF preview with file details and download button after combining documents
Image 7: Merged PDF preview with file details and download button after combining documents

The merged PDF is generated instantly in the browser, and users can preview , rename, and download it without any server interaction.

Important Notes from Real-World Use

When building tools like a PDF merger, handling large files efficiently becomes important.

If multiple large PDFs are loaded at once, it can slow down the browser or consume too much memory. Instead of processing everything at once, it’s better to handle files step by step.

For example, instead of loading all PDFs together, you can process them one by one:

code
const { PDFDocument } = PDFLib;

const mergedPdf = await PDFDocument.create();

for (const file of files) {
  const arrayBuffer = await file.arrayBuffer();
  const pdf = await PDFDocument.load(arrayBuffer);

  const pages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());

  pages.forEach(page => mergedPdf.addPage(page));
}

This approach keeps memory usage lower and avoids freezing the browser when working with larger files.

You can also improve performance by limiting file size or the number of files users can upload at once. This helps keep the tool responsive even on lower-powered devices.

Another important aspect is privacy. Since everything runs directly in the browser, files are never uploaded to a server. This means sensitive documents stay on the user’s device.

But it’s still important to be transparent about this. In real-world tools, you should clearly mention that all processing happens locally and no files are stored or transmitted.

This client-side approach improves both performance and user trust, especially when working with private or confidential documents.

Common Mistakes to Avoid

A common mistake is skipping validation. If users upload invalid files or empty inputs, the merge process can fail.

Another issue is ignoring page ranges. If parsing is incorrect, users may get unexpected results.

Also, relying on fixed layouts or assumptions can break the experience across different files. Testing with different PDF types is important.

Conclusion

In this tutorial, you built a browser-based PDF merger using JavaScript.

More importantly, you learned how to process files locally in the browser, render previews for better usability, handle user input safely, and manage dynamic document structures when working with PDFs.

This approach removes the need for a backend and keeps everything fast, private, and efficient.

Once you understand this pattern, you can extend it to build more advanced tools. For example, you could create features like PDF splitting, compression, editing, or other document-based utilities using the same core ideas.

And that’s where things start getting really interesting.

  • * *
  • * *

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started