Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteIn a Next.js App Router project, receive the PDF in a Route Handler, use pdf-lib to copy the selected pages into a new document, then return the generated PDF bytes. Validate the upload and page selection before parsing, and check your hosting provider’s request, memory, and execution limits before accepting large files.
How PDF splitting works in a Next.js Route Handler
A Route Handler is a public HTTP endpoint. It can read an uploaded file from request.formData() and return a non-UI response such as a PDF file. For the App Router, create app/api/split/route.ts. Next.js documents this pattern in its backend-for-frontend guide.
pdf-lib works in Node.js and browsers and has no native dependencies, according to its project documentation. Its API supports copying pages from a loaded document into another document. Install it with your package manager; for npm, run:
npm install pdf-lib
Build a single-PDF page extraction endpoint
This example accepts a multipart form with a PDF field named file and a comma-separated pages field. Page numbers are user-facing, 1-based numbers: for example, 1,3-5 extracts pages 1, 3, 4, and 5 into one output PDF. The code caps upload size and page count as application policy; adjust those limits to match your users and deployment, rather than treating them as universal platform limits.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
-
Create
app/api/split/route.ts. -
Install
pdf-libas shown above. -
Add the handler below. It validates the multipart fields, enforces a byte limit, checks the PDF signature as an additional sanity check, validates every requested page against the source page count, and returns a PDF response.
import { PDFDocument } from 'pdf-lib';
export const runtime = 'nodejs';
const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
const MAX_PAGES = 200;
function parsePages(value: string, pageCount: number): number[] | null {
const selected = new Set<number>();
const parts = value.split(',').map((part) => part.trim());
if (parts.length === 0 || parts.some((part) => part === '')) return null;
for (const part of parts) {
const match = /^(d+)(?:-(d+))?$/.exec(part);
if (!match) return null;
const start = Number(match[1]);
const end = match[2] ? Number(match[2]) : start;
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end)) return null;
if (start < 1 || end < start || end > pageCount) return null;
for (let page = start; page <= end; page++) selected.add(page - 1);
}
return [...selected].sort((a, b) => a - b);
}
export async function POST(request: Request) {
try {
const form = await request.formData();
const file = form.get('file');
const pagesValue = form.get('pages');
if (!(file instanceof File)) {
return Response.json({ error: 'Upload a PDF in the file field.' }, { status: 400 });
}
if (typeof pagesValue !== 'string' || pagesValue.length === 0) {
return Response.json({ error: 'Provide pages, such as 1,3-5.' }, { status: 400 });
}
if (file.size === 0 || file.size > MAX_UPLOAD_BYTES) {
return Response.json({ error: 'The uploaded file is empty or exceeds the upload limit.' }, { status: 413 });
}
const input = new Uint8Array(await file.arrayBuffer());
const signature = new TextDecoder().decode(input.subarray(0, 5));
if (signature !== '%PDF-') {
return Response.json({ error: 'The uploaded file does not appear to be a PDF.' }, { status: 415 });
}
const source = await PDFDocument.load(input);
const pageCount = source.getPageCount();
if (pageCount === 0 || pageCount > MAX_PAGES) {
return Response.json({ error: 'The PDF has no pages or exceeds the page limit.' }, { status: 400 });
}
const indices = parsePages(pagesValue, pageCount);
if (!indices || indices.length === 0) {
return Response.json({ error: 'Invalid page selection. Use page numbers and ascending ranges within the PDF.' }, { status: 400 });
}
const output = await PDFDocument.create();
const copied = await output.copyPages(source, indices);
for (const page of copied) output.addPage(page);
const bytes = await output.save();
return new Response(bytes, {
headers: {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename="pages.pdf"',
'Cache-Control': 'no-store',
},
});
} catch {
return Response.json({ error: 'Could not process this PDF.' }, { status: 400 });
}
}
The signature check is not a complete security test or proof that a file is safe. Likewise, a browser-supplied MIME type and a filename extension are not reliable evidence of content. The validation is a basic gate; choose stricter controls based on your threat model and supported input set. Review the installed pdf-lib version’s behavior and API details in its PDFDocument API reference.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Call the endpoint from a form
A minimal browser form can submit the file and page selection as multipart data:
const form = new FormData();
form.append('file', fileInput.files[0]);
form.append('pages', '1,3-5');
const response = await fetch('/api/split', { method: 'POST', body: form });
if (!response.ok) {
const result = await response.json();
throw new Error(result.error ?? 'PDF splitting failed');
}
const pdf = await response.blob();
const link = document.createElement('a');
link.href = URL.createObjectURL(pdf);
link.download = 'pages.pdf';
link.click();
URL.revokeObjectURL(link.href);
Extract multiple PDFs or split every page
The endpoint above creates one output containing all selected pages. To create separate PDFs—for example, one file per page or one file per requested range—create a fresh PDFDocument for each output, call copyPages with that output’s indices, add the copied pages, and save each document. The pdf-lib API documents page copying; the packaging and delivery choice is an application decision.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
- Several downloads: return a manifest or provide separate download requests. This avoids building one large response, but requires a way to keep or regenerate outputs.
- One archive: package the PDFs in a ZIP and return it. Choose and validate an archive library separately; the cited PDF documentation does not prescribe one.
- Large jobs: consider asynchronous processing and object storage if the chosen host cannot comfortably process or return the files within its request limits.
Do not assume a generated file written to a local path will be available to a later request. Some hosting providers run Route Handlers as lambda functions, where writable filesystem access, shared data across requests, and long-running execution may be limited. Check your host’s current request size, memory, execution-time, and storage rules before choosing the delivery design.
Choose browser or server-side processing
pdf-lib supports both browser and Node.js use. There is no universal speed or safety winner established by the documentation; the choice depends on file sensitivity, device capacity, operational controls, and deployment constraints.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
| Consideration | Browser processing | Server processing |
|---|---|---|
| Does the original file leave the device? | Not if all processing is implemented locally; verify that your app does not upload it elsewhere. | Yes. The endpoint receives the uploaded bytes, so handle them as sensitive input. |
| Limits and responsiveness | Depends on the target device’s available memory and responsiveness, especially on mobile; test your intended file sizes and devices. | Bounded by your host’s request, memory, and execution limits. |
| Central policy and access control | Less centralized: validation and processing happen on the client. | Provides a central place for validation, authentication, authorization, and audit controls. |
| File delivery or retention | The browser can create the output locally for download. | You must decide how to return, store, or delete the output; avoid persistence without a reason. |
Validate uploads, protect the endpoint, and handle failures
Next.js warns: “Never trust incoming request data. Validate content type and size, and sanitize against XSS before use.” Its backend-for-frontend guide, labeled last updated March 25, 2026, also discusses timeouts, rate limiting, access control, and avoiding sensitive information in client-facing errors and logs.
- Enforce limits before expensive work: apply request-body and upload-size limits at the host or proxy as well as in the handler. Limit page counts, concurrent jobs, and processing time to suit your service.
- Treat the route as public: require authentication and authorization for restricted tools. Rate-limit public processing where abuse could consume resources.
- Keep errors safe: return useful but non-sensitive messages to the client; do not reveal stack traces or document contents. Avoid logging uploaded bytes, sensitive page data, or unnecessary identifiers.
- Avoid needless retention: process in memory when appropriate, and if you store uploads or results, define access, expiry, and cleanup behavior.
- Test your supported PDFs: the cited documentation does not establish universal compatibility for encrypted, malformed, signed, or form-heavy files. Decide what you support and handle failures without claiming every PDF can be split.
Troubleshooting common problems
| Symptom | Likely cause | What to check or change |
|---|---|---|
| 400 response about missing file or pages | The multipart field names do not match the route, or the request omitted the selection. | Send a file field and a pages string, such as 1,3-5. |
| 413 response | The file exceeds the example’s configured byte limit or a platform limit. | Reduce the file size or deliberately adjust application policy after checking the hosting provider’s request limits. |
| 415 response | The initial bytes did not match the PDF signature check. | Confirm that the user selected a real PDF. Do not treat changing the filename or MIME type as a fix. |
| Invalid page selection | Page numbers are outside the document, use descending ranges, or contain unsupported syntax. | Use positive 1-based numbers and ascending ranges within the actual page count, for example 2-4,7. |
| Generic processing error | The document may be unreadable by the installed library version or the request may have failed during parsing or saving. | Test the file against your supported input policy, inspect server-side diagnostics without logging sensitive content, and verify the installed API/version. |
| Request times out or memory is exhausted | The upload or output is too demanding for the device or deployment environment. | Reduce allowed file/page sizes, test concurrency, or move large jobs to an architecture with suitable execution and storage limits. |
| Download is empty or unusable | The client handled a non-OK JSON error as a PDF, or output delivery failed. | Check response.ok before reading a blob and confirm the response content type is application/pdf. |
Or skip the browser setup
For website screenshots, ScreenshotNeo is a separate service—not a PDF-splitting library. It takes a URL and returns a screenshot or PDF with one GET request. Its clean-capture flow accepts cookie/consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers say which outcome occurred. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for AI agents and MCP clients.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
For a PDF capture of a webpage, the cURL request is:
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -d format=pdf -o page.pdf
See the ScreenshotNeo API documentation for request options. ScreenshotNeo’s free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. It captures webpages as PDFs, but it does not split an uploaded PDF. Sign up free to try ScreenshotNeo.
Frequently Asked Questions
Can pdf-lib split a PDF in the browser as well as in Node.js?
Yes. Its project documentation lists support for browsers and Node.js; whether browser processing suits your users depends on their devices and your implementation.
Does this route preserve signatures or support every encrypted PDF?
The cited documentation does not establish universal support for encrypted, signed, malformed, or form-heavy PDFs. Define and test the input types your app will support.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

