Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To export selected pages from an existing PDF, use pdf-lib: load the source, convert the reader’s one-based page numbers to zero-based indices, copy those pages into a new PDFDocument, and save the result. If your source is a web page rather than a PDF file, use Puppeteer’s page.pdf() and its pageRanges option instead. These are different operations: one extracts pages already in a PDF; the other prints selected pages generated by a browser.

Choose the workflow that matches your input

Input Node.js approach Selection syntax Runtime
Existing PDF file or bytes pdf-lib with copyPages() Zero-based integer indices Pure JavaScript; no browser required
HTML rendered by a browser Puppeteer page.pdf() PDF print page ranges, such as 1-3,6 Chromium automation
Existing PDF, viewer preference only setPrintPageRange() Viewer print-dialog range Does not remove pages

The displayed first page is normally page 1 to a person, while pdf-lib addresses it as index 0. Keep that conversion at your input boundary and validate every requested page before modifying the document.

Extract selected pages from an existing PDF with pdf-lib

Install the dependency

In a new Node.js project, install the library:

npm install pdf-lib

The package is pure JavaScript and is usable in Node.js, browsers, Deno, and React Native. Its document APIs cover modification, splitting, merging, and page copying.

Complete extraction script

This CommonJS script accepts human-facing page numbers, preserves their requested order (including a deliberate duplicate), and writes a new PDF.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
  • EDIT text, images & designs in PDF documents. ORGANIZE PDFs. Convert PDFs to Word, Excel & ePub.
  • READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.
  • CREATE, COMBINE, SCAN and COMPRESS PDFs
  • FILL forms & Digitally Sign PDFs. PROTECT and Encrypt PDFs
  • LIFETIME License for 1 Windows PC or Laptop. 5GB MobiDrive Cloud Storage Included.
const fs = require('node:fs/promises');
const { PDFDocument } = require('pdf-lib');

async function exportSelectedPages(inputPath, outputPath, displayedPages) {
  if (!Array.isArray(displayedPages) || displayedPages.length === 0) {
    throw new Error('Provide at least one displayed page number.');
  }
  if (!displayedPages.every(Number.isInteger)) {
    throw new Error('Page numbers must be integers.');
  }

  const sourceBytes = await fs.readFile(inputPath);
  const source = await PDFDocument.load(sourceBytes);
  const pageCount = source.getPageCount();

  // Convert one-based numbers (1 = first page) to pdf-lib indices (0 = first page).
  const indices = displayedPages.map((pageNumber) => {
    if (pageNumber < 1 || pageNumber > pageCount) {
      throw new Error(
        `Page ${pageNumber} is outside the document range 1-${pageCount}.`
      );
    }
    return pageNumber - 1;
  });

  const destination = await PDFDocument.create();
  const copiedPages = await destination.copyPages(source, indices);
  copiedPages.forEach((page) => destination.addPage(page));

  const outputBytes = await destination.save();
  await fs.writeFile(outputPath, outputBytes);
  return { pageCount, exported: displayedPages };
}

exportSelectedPages('input.pdf', 'selected.pdf', [1, 3, 4])
  .then((result) => console.log(`Exported pages ${result.exported.join(', ')} from a ${result.pageCount}-page PDF.`))
  .catch((error) => {
    console.error(error.message);
    process.exitCode = 1;
  });

Run it with node export-pages.js. The output contains only the selected pages, in the order passed to exportSelectedPages. For example, [4, 1, 4] intentionally produces page 4, page 1, then page 4 again.

Working with buffers instead of files

For an upload endpoint or object-storage stream, replace fs.readFile() with the received Uint8Array. The core sequence remains the same:

  1. Call PDFDocument.load(inputBytes).
  2. Read getPageCount() and validate the request.
  3. Call destination.copyPages(source, indices).
  4. Add every returned page to the destination.
  5. Call save() and return or store the resulting bytes.

Parsing ranges such as “2-4,8”

Do not pass a page-range string directly to copyPages(); it expects an array of zero-based indices. Convert and validate it first:

function parseDisplayedRange(text, pageCount) {
  const result = [];
  for (const part of text.split(',')) {
    const item = part.trim();
    if (!item) continue;
    const match = /^(d+)(?:-(d+))?$/.exec(item);
    if (!match) throw new Error(`Invalid range: ${item}`);
    const start = Number(match[1]);
    const end = match[2] ? Number(match[2]) : start;
    if (start < 1 || end < start || end > pageCount) {
      throw new Error(`Range ${item} is outside 1-${pageCount}.`);
    }
    for (let page = start; page <= end; page++) result.push(page - 1);
  }
  if (result.length === 0) throw new Error('The range is empty.');
  return result;
}

Use the returned indices in copyPages. Decide explicitly whether repeated pages and overlapping ranges are allowed; the parser above keeps them, which makes the behavior predictable.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Generate a PDF from HTML and print selected pages with Puppeteer

Use Puppeteer when the “pages” do not exist yet and must be produced by a browser. page.pdf() returns a Promise<Uint8Array>; its pageRanges option selects paper pages. Print CSS is used by default. If the PDF should match screen styling, call page.emulateMediaType('screen') before generating it.

Rank #2
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  try {
    const page = await browser.newPage();
    await page.goto('https://example.com/report', {
      waitUntil: 'networkidle0',
      timeout: 90000
    });

    // Omit this line to use print CSS (the default).
    // await page.emulateMediaType('screen');

    await page.pdf({
      path: 'selected-web-pages.pdf',
      format: 'A4',
      printBackground: true,
      pageRanges: '1-3,6'
    });
  } finally {
    await browser.close();
  }
})();

Here 1-3,6 is a print range, not a pdf-lib index array. Web content can reflow, so a small CSS or viewport change may alter which content lands on a paper page. Set the viewport, wait for fonts and lazy content, and test the resulting pagination.

What not to use for extraction

PDFDocument.setPrintPageRange() sets the range initially selected when a viewer opens its print dialog. It does not delete pages or create a smaller PDF. A recipient can still access every original page. Use copyPages() when the output file itself must contain only the chosen pages.

PDFKit is primarily a PDF creation library. Its Node build supports filesystem access, compression, and streams, but its normal page-flush behavior makes it less direct for extracting arbitrary pages from an existing document.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Feature fidelity and operational limits

Validate the PDF features you need

Page extraction is not a guarantee that every document feature will behave exactly as in the source. Test representative files containing the features your application depends on:

  • AcroForm fields and other interactive forms
  • Annotations, hyperlinks, and embedded actions
  • Bookmarks or outlines
  • Metadata, attachments, encryption, and unusual fonts

The pdf-lib documentation warns that its whole-document copy() operation does not copy all information, including examples such as AcroForms and outlines. That warning is not proof that copyPages() loses the same items, so verify the actual operation with your files instead of promising universal preservation.

Rank #3
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
  • Edit PDFs with Ease. Modify text, images, and layouts directly within your PDF documents.
  • Convert & Organize. Export PDFs to Word, Excel, or ePub, and organize files with ease.
  • Read & Annotate. Enjoy intuitive reading modes and powerful tools to comment, highlight, and mark up PDFs.
  • Create & Manage PDFs. Create new PDFs, combine multiple files, scan documents, and compress for easy sharing.
  • Fill & Sign Forms. Complete forms and digitally sign documents with secure e-signature tools.

Memory, concurrency, and reliability

  • Loading and saving are byte-oriented operations; size worker memory for the largest PDFs you accept.
  • Use a temporary output name and rename it after a successful save so a failed request does not publish a partial file.
  • Limit concurrent jobs according to available memory, and impose request, upload, and execution time limits at your service boundary.
  • Keep the original bytes until the output has been validated and delivered.
  • There are no authoritative universal speed or size limits established here; benchmark with representative production documents.

Security checks

Treat uploaded PDFs and URLs as untrusted input. Enforce file-size and page-count limits, isolate browser workers, restrict outbound navigation for Puppeteer where appropriate, and never execute user-supplied JavaScript in your Node process outside the intended browser context.

Troubleshooting selected-page exports

Symptom Likely cause Fix
“Page is outside range” A displayed page number was not converted or is beyond getPageCount(). Validate 1 through pageCount, then subtract one exactly once.
Output is empty No indices were supplied, or no copied pages were added. Reject empty selections and call addPage() for every copied page.
Pages appear in the wrong order The input was sorted or ranges were expanded unexpectedly. Preserve the caller’s array order and define duplicate behavior.
Forms, links, or outlines differ Feature preservation varies by document and operation. Test representative files and choose a toolchain that meets the required fidelity.
Puppeteer prints the wrong content Fonts, images, lazy content, or network requests were unfinished. Wait for the required selectors/resources, set a stable viewport, and inspect print CSS.
Browser launch fails in deployment Chromium is unavailable or blocked by the runtime sandbox. Install a compatible browser, configure its executable path or container, and review sandbox permissions.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your source is a URL and you simply need a clean capture or PDF, ScreenshotNeo provides a single API request instead of maintaining Puppeteer and Chromium. It accepts cookie and consent banners before capture, removes more than 60 known consent platforms plus newsletter popups and chat widgets, and lets you turn each cleanup step off. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; response headers identify the page verdict and billing result.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a PDF capture, call the API as documented at https://screenshotneo.com/docs/:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

The same endpoint can return PNG, JPEG, WebP, or PDF and offers controls for full-page and element captures, device and viewport settings, print paper and margins, page ranges, custom CSS and JavaScript, waits, blocking, headers, cookies, user agents, authorization, timezone, geolocation, caching, signed links, asynchronous webhooks, bulk capture, and usage reporting. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The Free plan includes 1,000 screenshots each month with no card. Paid plans start at $5 for 3,000 shots; every feature is included on every plan. Start with the free ScreenshotNeo account.

FAQ

Can I export pages without changing the original PDF?

Yes. Load the original bytes and save a separate destination document; the source file is not modified.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
OfficeSuite: Word documents, Excel Sheets, PowerPoint Slides & PDF Editor & Converter
  • All-in-one office pack - Documents, Sheets, Slides & PDF
  • Cross-platform (Android, iOS, Windows PC)
  • Supports Microsoft Office formats
  • Use 30+ charts & 250+ formulas in Sheets
  • In-depth features for document creation & formatting

Should user page numbers be one-based?

Yes. One-based numbers match what readers see; convert them to zero-based indices immediately before calling copyPages().

When is Puppeteer the better choice?

Use it when the source is HTML that must be laid out by a browser, rather than an existing PDF whose pages already exist.

Frequently Asked Questions

Can I export pages in a different order?

Yes. Pass indices in the desired order; copied pages are added sequentially, so duplicates and reordering are possible when your validation policy permits them.

Does selecting a print range reduce an existing PDF file?

No. A print-range preference changes the viewer’s initial dialog selection; only copying pages into a new document creates a reduced file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How should I test production PDFs?

Include representative forms, annotations, links, outlines, metadata, fonts, and encrypted or unusually structured files, then inspect the generated PDFs in the viewers your users rely on.

The Bottom Line

Use pdf-lib and copyPages() for selected pages from an existing PDF; use Puppeteer’s pageRanges for selected printed pages from browser-rendered HTML. Keep their indexing and fidelity assumptions separate, validate inputs, and test the document features your application must preserve.

Quick Recap

Bestseller No. 1
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.; CREATE, COMBINE, SCAN and COMPRESS PDFs
$99.99
Bestseller No. 2
PDF Reader, PDF Viewer, PDF Editor- file document
PDF Reader, PDF Viewer, PDF Editor- file document
PDF Reader; PDF Viewer; PDF Editor
$6.85
Bestseller No. 3
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
Edit PDFs with Ease. Modify text, images, and layouts directly within your PDF documents.; Convert & Organize. Export PDFs to Word, Excel, or ePub, and organize files with ease.
$99.99
Bestseller No. 4
OfficeSuite: Word documents, Excel Sheets, PowerPoint Slides & PDF Editor & Converter
OfficeSuite: Word documents, Excel Sheets, PowerPoint Slides & PDF Editor & Converter
All-in-one office pack - Documents, Sheets, Slides & PDF; Cross-platform (Android, iOS, Windows PC)

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.