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

推荐订阅源

B
Blog RSS Feed
C
CERT Recently Published Vulnerability Notes
P
Proofpoint News Feed
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
云风的 BLOG
云风的 BLOG
H
Help Net Security
Recorded Future
Recorded Future
The Register - Security
The Register - Security
F
Full Disclosure
N
Netflix TechBlog - Medium
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
爱范儿
爱范儿
Security Archives - TechRepublic
Security Archives - TechRepublic
Simon Willison's Weblog
Simon Willison's Weblog
Cisco Talos Blog
Cisco Talos Blog
I
InfoQ
T
Tenable Blog
T
Tor Project blog
人人都是产品经理
人人都是产品经理
D
DataBreaches.Net
NISL@THU
NISL@THU
Google DeepMind News
Google DeepMind News
博客园 - 叶小钗
B
Blog
V
V2EX
Jina AI
Jina AI
L
LangChain Blog
月光博客
月光博客
W
WeLiveSecurity
U
Unit 42
AWS News Blog
AWS News Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园 - 聂微东
V
Visual Studio Blog
A
Arctic Wolf
T
Tailwind CSS Blog
The Cloudflare Blog
SecWiki News
SecWiki News
S
SegmentFault 最新的问题
Hacker News - Newest:
Hacker News - Newest: "LLM"
宝玉的分享
宝玉的分享
MyScale Blog
MyScale Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
S
Securelist
www.infosecurity-magazine.com
www.infosecurity-magazine.com
腾讯CDC
雷峰网
雷峰网

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 Measure Your AI Citation Rate Across ChatGPT, Perplexity, and Claude How to Deploy a Full-Stack Next.js App on Cloudflare Workers with GitHub Actions CI/CD How to Build a Multi-Tenant SaaS Platform with Next.js, Express, and Prisma How I Completed 15 freeCodeCamp Certifications in 4 Months: A Structured Learning Journey How to Build an Agentic Terminal Workflow with GitHub Copilot CLI and MCP Servers How AI Changed the Economics of Writing Clean Code How to Apply STRIDE Threat Modeling and SonarQube Analysis for Secure Software Development How to Set Up OpenID Connect (OIDC) in GitHub Actions for AWS How to Build Your Own Language-Specific LLM [Full Handbook] How to Build a Self-Learning RAG System with Knowledge Reflection How to Trace Multi-Agent AI Swarms with Jaeger v2 How I Tested Malaysia's Open Data Portals with Plain English How I Built a Production-Ready CI/CD Pipeline for a Monorepo-Based Microservices System with Jenkins, Docker Compose, and Traefik The Hidden Tax of Infrastructure: Why Your Team Shouldn’t Be Running It Anymore From Metrics to Meaning: How PaaS Helps Developers Understand Production From Symptoms to Root Cause: How to Use the 5 Whys Technique Product Experimentation for AI Rollouts: Why A/B Testing Breaks and How Difference-in-Differences in Python Fixes It How to Create a GPU-Optimized Machine Image with HashiCorp Packer on GCP 3D Web Development with Blender and Three.js How to Fix a Failing GitHub PR: Debugging CI, Lint Errors, and Build Errors Step by Step How to Merge PDF Files in the Browser Using JavaScript (Step-by-Step) How to Handle Stripe Webhooks Reliably with Background Jobs How to Build an Automatic Knowledge Graph for Your Blog with PHP and JSON-LD Understanding Proxies and Reverse Proxies: Your Gateway to Secure Networking The Evolution of Nvidia Blackwell GPU Memory Architecture How to Use PostgreSQL as a Cache, Queue, and Search Engine The New Definition of Software Engineering in the Age of AI Reclaim Your Time – Master Automation with Zapier How to Create Dynamic Emails in Go with React Email Why Many Beginner Self-Taught Developers Struggle (And What to Do About It) How to Build a Headless WordPress Frontend with Astro SSR on Cloudflare Pages How to Make Your GitHub Profile Stand Out How to Use Context Hub (chub) to Build a Companion Relevance Engine Why Chrome OS Is the Operating System the AI Era Was Built For How to Build Microservices-Based REST APIs for Healthcare Portals How to friction-max your learning with software engineer Jessica Rose [Podcast #216] Shadow AI Explained: Why Employees Are Using AI Behind Your Back Traditional Scraping vs AI Scraping: A Practical Guide for Developers and Data Teams How Database Indexes Work – A Practical Guide with PostgreSQL Examples How to Streamline Search in Web Applications with Elasticsearch How to Build an Open Source Data Lake for Batch Ingestion OpenAI Codex Essentials – AI Assisted Agentic Development Course Learn Software System Design How to Generate PDF Files in the Browser Using JavaScript (With a Real Invoice Example) How to Get Started with Terraform Service-to-Service Communication: When to Use REST, gRPC, and Event-Driven Messaging A Developer’s Guide to Lazy Loading in React and Next.js The Data Quality Handbook: Data Errors, the Developer's Role, and Validation Layers Explained. United States Residential Proxy: Why Local IP Accuracy Matters for SERP, Ads, and Pricing How to Build a Fashion App That Helps You Organize Your Wardrobe How to Build an Admin Dashboard Sidebar with shadcn/ui and Base UI The AI Governance Handbook: How to Build Responsible AI Systems That Actually Ship How to Build a Local DevOps HomeLab with Docker, Kubernetes, and Ansible How to Use Mixins in Flutter [Full Handbook] How to Prep for Technical Interviews – A Guide for Web Developers GPT-5.4 vs GLM-5: Is Open Source Finally Matching Proprietary AI? Data Visualization Tools for Svelte Developers How to Keep Human Experts Visible in Your AI-Assisted Codebase Efficient Data Processing in Python: Batch vs Streaming Pipelines Explained How to Build and Deploy Multi-Architecture Docker Apps on Google Cloud Using ARM Nodes (Without QEMU) How to Build a Secure AI PR Reviewer with Claude, GitHub Actions, and JavaScript How to Build a Positioning-Based Crude Oil Strategy in Python [Full Handbook] How to learn programming and CS in the AI hype era – interview with dev and prof Mark Mahoney [Podcast #215] CUDA Programming for NVIDIA H100s How to Build Reliable AI Systems. How to Build an Online Marketplace with Next.js, Express, and Stripe Connect How to Build a Cost-Efficient AI Agent with Tiered Model Routing The WebCodecs Handbook: Native Video Processing in the Browser The Bluetooth LE Audio Handbook: From "Why Does My Call Sound Like a Tin Can?" to AOSP Implementation How to Set Up OpenClaw and Design an A2A Plugin Bridge
How to Split PDF Files in the Browser Using JavaScript (Step-by-Step)
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