\n```\n\nThis library allows us to:\n\n* load PDFs\n\n* copy pages\n\n* create new documents\n\n## Creating the Upload Interface\n\nStart with a simple file input:\n\n```\n\n\n\n\nDownload Split PDF\n```\n\nThis interface allows users to upload a PDF file, specify which pages they want to extract, and trigger the splitting process with a single click. Once the process is complete, the download link becomes visible so they can save the new PDF.\n\n## Reading the PDF File\n\nNow let’s read the uploaded file:\n\n```\nconst fileInput = document.getElementById(\"upload\");\n\nif (!fileInput.files.length) {\n alert(\"Please upload a PDF file\");\n return;\n}\n\nconst file = fileInput.files[0];\nconst arrayBuffer = await file.arrayBuffer();\n```\n\nThis converts the file into a format the library can use.\n\nUsers can control how the PDF is split in multiple ways.\n\nThey can manually enter page ranges like `1-3,5`, which allows precise selection of pages. For example, entering `1-3` extracts pages 1 to 3, while `5` selects only page 5.\n\nIn addition to manual input, the tool also provides predefined options such as splitting all pages, extracting only even or odd pages, or splitting the document into fixed-size ranges. These options make it easier for users who don’t want to type page ranges manually.\n\nTo support manual input, we use a simple parser that converts the user’s input into valid page indexes:\n\n```\nfunction parsePages(input, totalPages) {\n const pages = [];\n\n input.split(',').forEach(part => {\n if (part.includes('-')) {\n const [start, end] = part.split('-').map(Number);\n for (let i = start; i <= end; i++) {\n if (i <= totalPages) pages.push(i - 1);\n }\n } else {\n const num = parseInt(part);\n if (num <= totalPages) pages.push(num - 1);\n }\n });\n\n return pages;\n}\n```\n\nThis approach gives flexibility, allowing both simple and advanced ways to select pages depending on the user’s needs.\n\n## Splitting the PDF Using JavaScript\n\nNow comes the main logic:\n\n```\nasync function splitPDF() {\n const fileInput = document.getElementById(\"upload\");\n const pageInput = document.getElementById(\"pages\").value;\n\n if (!fileInput.files.length || !pageInput.trim()) {\n alert(\"Please upload a PDF and enter page numbers\");\n return;\n }\n\n const file = fileInput.files[0];\n const arrayBuffer = await file.arrayBuffer();\n\n const { PDFDocument } = PDFLib;\n\n const originalPdf = await PDFDocument.load(arrayBuffer);\n const totalPages = originalPdf.getPageCount();\n\n const selectedPages = parsePages(pageInput, totalPages);\n\n const newPdf = await PDFDocument.create();\n\n const copiedPages = await newPdf.copyPages(originalPdf, selectedPages);\n\n copiedPages.forEach(page => newPdf.addPage(page));\n\n const pdfBytes = await newPdf.save();\n\n const blob = new Blob([pdfBytes], { type: \"application/pdf\" });\n\n const link = document.getElementById(\"download\");\n link.href = URL.createObjectURL(blob);\n link.download = \"split.pdf\";\n link.style.display = \"inline\";\n link.innerText = \"Download Split PDF\";\n}\n```\n\nThis:\n\n* loads the original file\n\n* extracts selected pages\n\n* creates a new PDF\n\n* prepares it for download\n\n## Generating and Downloading the PDF\n\nOnce the PDF is created:\n\n```\nlink.href = URL.createObjectURL(blob);\nlink.download = \"split.pdf\";\n```\n\nThe browser handles the download instantly — no server needed.\n\n## Demo: How the PDF Split Tool Works\n\nHere’s how the full flow looks in practice using the tool:\n\n### Step 1: Upload Your PDF\n\n![Image 3: PDF splitter tool interface showing drag and drop upload area with select PDF button](https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/59361d9e-1f64-428e-8098-49b0976bd3ae.png)\nStart by dragging and dropping your PDF file into the upload area, or click the button to select a file from your device. Once uploaded, the tool instantly processes the document and prepares it for splitting.\n\n### Step 2: Preview Pages\n\n![Image 4: PDF splitter preview showing multiple pages as thumbnails for visual selection](https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/b6cae555-6b9d-4ea9-afe5-877803574ceb.png)\nAfter uploading, all pages of the PDF are displayed as thumbnails. This gives you a clear visual overview of the document so you can decide how you want to split it.\n\n### Step 3: Choose Split Mode and Options\n\n![Image 5: PDF splitter settings with options for page range, all pages, fixed range, and odd or even page splitting](https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/e7ee8c00-8247-41ce-9459-4de7f5e8b1ef.png)\nNext, choose how you want to split the PDF. You can select options like splitting by page range, extracting all pages, splitting odd or even pages, or dividing the document into fixed-size sections. This flexibility makes it easy to handle different use cases without manually selecting every page.\n\n### Step 4: Split the PDF\n\n![Image 6: PDF splitter interface showing split PDF button and start over option](https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/185b297f-f16e-4269-a885-6dd48903db23.png)\nOnce your settings are ready, click the split button. The browser processes the file locally and generates the new PDFs based on your selected mode.\n\n### Step 5: Download the Results\n\n![Image 7: PDF splitter result showing multiple generated files with download buttons and download all option](https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/c3fdf474-9052-4661-9c82-c34515a4423c.png)\nAfter processing, the split files are displayed with download options. You can download individual files or download all of them at once. Everything happens instantly in the browser without uploading your files anywhere.\n\n## Important Notes from Real-World Use\n\nWhen working with PDF splitting, input validation is important.\n\nUsers may enter invalid ranges or page numbers that don’t exist. Always validate and limit input to available pages.\n\nHandling large PDFs can also affect performance. Instead of processing everything at once, you can handle operations step by step to keep the browser responsive.\n\nAnother key consideration is privacy. Since all processing happens in the browser, files never leave the user’s device. This makes the tool safer for sensitive documents.\n\nIn real-world applications, it’s important to clearly communicate that files are not uploaded or stored anywhere.\n\n## Common Mistakes to Avoid\n\nOne common issue is not validating user input. If users enter incorrect page ranges, the tool may fail or produce unexpected results.\n\nAnother mistake is forgetting that page indexes start at zero internally. If you don’t adjust for this, you may extract the wrong pages.\n\nAlso, skipping edge cases like empty input or large files can make the tool unreliable.\n\n## Conclusion\n\nIn this tutorial, you built a browser-based PDF splitter using JavaScript.\n\nYou learned how to read PDF files, extract specific pages, and generate a new document entirely in the browser.\n\nThis approach removes the need for a backend and keeps everything fast and private.\n\nIf you’d like to see a complete working version of this idea, you can try it here: [Split PDF](https://allinonetools.net/split-pdf/)\n\nOnce you understand this pattern, you can extend it further to build more advanced PDF tools like merging, compression, or editing.\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/d18008d2-43f3-40ee-a98c-3a8b42cbaa6f"},{"@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/d18008d2-43f3-40ee-a98c-3a8b42cbaa6f#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 Split PDF Files in the Browser Using JavaScript (Step-by-Step)","item":"https://www.traeai.com/articles/d18008d2-43f3-40ee-a98c-3a8b42cbaa6f"}]}]}
freeCodeCamp.org

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

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

TL;DR · AI 摘要

使用 pdf-lib 库在浏览器中实现 PDF 文件分割,无需服务器支持,保护用户隐私。

核心要点

  • pdf-lib 库可直接在浏览器中处理 PDF 文件
  • 通过简单 HTML 和 JavaScript 实现 PDF 分页提取
  • 无需上传文件,提升用户数据安全性
#JavaScript#PDF#前端#pdf-lib
打开原文
Image 1: How to Split PDF Files in the Browser Using JavaScript (Step-by-Step)
Image 1: How to Split PDF Files in the Browser Using JavaScript (Step-by-Step)

Working with PDFs is part of everyday development.

Sometimes you don’t need the entire document. You just need a few pages — maybe a specific section, a report summary, or selected invoice pages.

Most tools require uploading files or installing software. But modern browsers are powerful enough to handle this locally.

In this tutorial, you’ll learn how to build a browser-based PDF splitter using JavaScript, where everything runs directly in the user’s browser.

By the end, you’ll understand how to extract specific pages from a PDF, create a new document from those pages, and download the result instantly.

Image 2: split pdf files,extract pages
Image 2: split pdf files,extract pages

Table of Contents

How PDF Splitting Works in the Browser

Splitting a PDF means taking a single document and extracting specific pages into a new file.

Traditionally, this kind of processing is handled on a server. But with modern JavaScript libraries like pdf-lib, we can do everything directly in the browser.

The process is straightforward. A user uploads a PDF file, the browser reads it, and we can display a preview of its pages to help users understand what they’re working with. Based on the selected split mode or page input, we then extract only the required pages and copy them into a new PDF document.

All of this happens locally in the browser, which makes the process faster and ensures that user files never leave their device.

Project Setup

We’ll keep this project simple.

You only need:

  • an HTML file
  • JavaScript
  • a PDF processing library

No backend or server is required.

What Library Are We Using?

We’ll use pdf-lib, a lightweight JavaScript library for working with PDFs.

Add it using a CDN:

code
<script src="https://unpkg.com/[email protected]/dist/pdf-lib.min.js"></script>

This library allows us to:

  • load PDFs
  • copy pages
  • create new documents

Creating the Upload Interface

Start with a simple file input:

code
<input type="file" id="upload" accept="application/pdf">
<input type="text" id="pages" placeholder="Enter pages (e.g. 1-3,5)">
<button onclick="splitPDF()">Split PDF</button>

<a id="download" style="display:none;">Download Split PDF</a>

This interface allows users to upload a PDF file, specify which pages they want to extract, and trigger the splitting process with a single click. Once the process is complete, the download link becomes visible so they can save the new PDF.

Reading the PDF File

Now let’s read the uploaded file:

code
const fileInput = document.getElementById("upload");

if (!fileInput.files.length) {
  alert("Please upload a PDF file");
  return;
}

const file = fileInput.files[0];
const arrayBuffer = await file.arrayBuffer();

This converts the file into a format the library can use.

Users can control how the PDF is split in multiple ways.

They can manually enter page ranges like 1-3,5, which allows precise selection of pages. For example, entering 1-3 extracts pages 1 to 3, while 5 selects only page 5.

In addition to manual input, the tool also provides predefined options such as splitting all pages, extracting only even or odd pages, or splitting the document into fixed-size ranges. These options make it easier for users who don’t want to type page ranges manually.

To support manual input, we use a simple parser that converts the user’s input into valid page indexes:

code
function parsePages(input, totalPages) {
  const pages = [];

  input.split(',').forEach(part => {
    if (part.includes('-')) {
      const [start, end] = part.split('-').map(Number);
      for (let i = start; i <= end; i++) {
        if (i <= totalPages) pages.push(i - 1);
      }
    } else {
      const num = parseInt(part);
      if (num <= totalPages) pages.push(num - 1);
    }
  });

  return pages;
}

This approach gives flexibility, allowing both simple and advanced ways to select pages depending on the user’s needs.

Splitting the PDF Using JavaScript

Now comes the main logic:

code
async function splitPDF() {
  const fileInput = document.getElementById("upload");
  const pageInput = document.getElementById("pages").value;

  if (!fileInput.files.length || !pageInput.trim()) {
    alert("Please upload a PDF and enter page numbers");
    return;
  }

  const file = fileInput.files[0];
  const arrayBuffer = await file.arrayBuffer();

  const { PDFDocument } = PDFLib;

  const originalPdf = await PDFDocument.load(arrayBuffer);
  const totalPages = originalPdf.getPageCount();

  const selectedPages = parsePages(pageInput, totalPages);

  const newPdf = await PDFDocument.create();

  const copiedPages = await newPdf.copyPages(originalPdf, selectedPages);

  copiedPages.forEach(page => newPdf.addPage(page));

  const pdfBytes = await newPdf.save();

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

  const link = document.getElementById("download");
  link.href = URL.createObjectURL(blob);
  link.download = "split.pdf";
  link.style.display = "inline";
  link.innerText = "Download Split PDF";
}

This:

  • loads the original file
  • extracts selected pages
  • creates a new PDF
  • prepares it for download

Generating and Downloading the PDF

Once the PDF is created:

code
link.href = URL.createObjectURL(blob);
link.download = "split.pdf";

The browser handles the download instantly — no server needed.

Demo: How the PDF Split Tool Works

Here’s how the full flow looks in practice using the tool:

Step 1: Upload Your PDF

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

Start by dragging and dropping your PDF file into the upload area, or click the button to select a file from your device. Once uploaded, the tool instantly processes the document and prepares it for splitting.

Step 2: Preview Pages

Image 4: PDF splitter preview showing multiple pages as thumbnails for visual selection
Image 4: PDF splitter preview showing multiple pages as thumbnails for visual selection

After uploading, all pages of the PDF are displayed as thumbnails. This gives you a clear visual overview of the document so you can decide how you want to split it.

Step 3: Choose Split Mode and Options

Image 5: PDF splitter settings with options for page range, all pages, fixed range, and odd or even page splitting
Image 5: PDF splitter settings with options for page range, all pages, fixed range, and odd or even page splitting

Next, choose how you want to split the PDF. You can select options like splitting by page range, extracting all pages, splitting odd or even pages, or dividing the document into fixed-size sections. This flexibility makes it easy to handle different use cases without manually selecting every page.

Step 4: Split the PDF

Image 6: PDF splitter interface showing split PDF button and start over option
Image 6: PDF splitter interface showing split PDF button and start over option

Once your settings are ready, click the split button. The browser processes the file locally and generates the new PDFs based on your selected mode.

Step 5: Download the Results

Image 7: PDF splitter result showing multiple generated files with download buttons and download all option
Image 7: PDF splitter result showing multiple generated files with download buttons and download all option

After processing, the split files are displayed with download options. You can download individual files or download all of them at once. Everything happens instantly in the browser without uploading your files anywhere.

Important Notes from Real-World Use

When working with PDF splitting, input validation is important.

Users may enter invalid ranges or page numbers that don’t exist. Always validate and limit input to available pages.

Handling large PDFs can also affect performance. Instead of processing everything at once, you can handle operations step by step to keep the browser responsive.

Another key consideration is privacy. Since all processing happens in the browser, files never leave the user’s device. This makes the tool safer for sensitive documents.

In real-world applications, it’s important to clearly communicate that files are not uploaded or stored anywhere.

Common Mistakes to Avoid

One common issue is not validating user input. If users enter incorrect page ranges, the tool may fail or produce unexpected results.

Another mistake is forgetting that page indexes start at zero internally. If you don’t adjust for this, you may extract the wrong pages.

Also, skipping edge cases like empty input or large files can make the tool unreliable.

Conclusion

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

You learned how to read PDF files, extract specific pages, and generate a new document entirely in the browser.

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

If you’d like to see a complete working version of this idea, you can try it here: Split PDF

Once you understand this pattern, you can extend it further to build more advanced PDF tools like merging, compression, or editing.

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