惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
博客园_首页
Google DeepMind News
Google DeepMind News
博客园 - Franky
The GitHub Blog
The GitHub Blog
GbyAI
GbyAI
有赞技术团队
有赞技术团队
Microsoft Azure Blog
Microsoft Azure Blog
G
Google Developers Blog
Recent Announcements
Recent Announcements
A
About on SuperTechFans
博客园 - 【当耐特】
博客园 - 三生石上(FineUI控件)
酷 壳 – CoolShell
酷 壳 – CoolShell
美团技术团队
罗磊的独立博客
IT之家
IT之家
博客园 - 聂微东
Stack Overflow Blog
Stack Overflow Blog
Jina AI
Jina AI
腾讯CDC
P
Proofpoint News Feed
Hugging Face - Blog
Hugging Face - Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

Learn Command Line Interface (CLI) Development with Dart: From Zero to a Fully Published Developer Tool How to Bypass Cloud SMTP Restrictions Using Brevo and HTTP APIs How to Build a Live Options Database in Python – A Complete Guide How to Migrate to S3 Native State Locking in Terraform How to Use SCons to Build Software Projects [Full Handbook] How to Run Open Source LLMs Locally and in the Cloud QuRT: The Real-Time OS Inside Your Phone's Processor [Full Handbook] The Real Infrastructure Behind Remote Work (It’s Not Just Wi-Fi) The Lithography Handbook: Machines, Markets, and the Next Wave of Semiconductor Startups ITCM vs DTCM vs DDR: Embedded Memory Types Explained [Full Handbook] AI Paper Review: Improving Language Understanding by Generative Pre-Training (GPT-1) How to Build a Market Research Copilot with MCP and Python [Full Handbook] How to Build a Scoped Note-Taking API with Django Rest Framework and SimpleJWT The Complete SOC 2 Type II Implementation Handbook for Engineers: A Month-by-Month Roadmap with Real Commands Mastering the JavaScript Event Loop Data Science Insights: Why the Mean Lies When Handling Messy Retail Data How to Build High-Ranking SEO Landing Page How to Query Data in DynamoDB Using .Net How to Unblock Your AI PR Review Bottleneck: A Tech Lead’s Guide to Building a Codebase-Aware Reviewer How to Navigate Microservices as a Frontend Engineer How to Compress PDF Files in the Browser Using JavaScript (Step-by-Step) Stanford's youngest instructor talks InfoSec, AI, and catching cheaters - Rachel Fernandez interview [Podcast #217] Product Experimentation with Propensity Scores: Causal Inference for LLM-Based Features in Python How to Build a Multi-Agent AI System with LangGraph, MCP, and A2A [Full Book] How to Land Your First Cloud or DevOps Role: What Hiring Managers Actually Look For How to Deploy a Serverless Spam Classifier Using Scikit-Learn, AWS Lambda, & API Gateway How to Dockerize a Go Application – Full Step-by-Step Walkthrough Learn Hardware, Cloud, DevOps, Networking, Security, Databases, DNS, Git, and Linux Inside TreeHacks 2026, Stanford’s Elite Student Hakc Inside Stanford’s Elite Student Hackathon [Full Documentary]
How to Split PDF Files in the Browser Using JavaScript (S...
Bhavin Sheth · 2026-04-27 · via freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
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.

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:

<script src="https://unpkg.com/pdf-lib@1.17.1/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:

<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:

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:

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:

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:

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

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

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

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

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

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