iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Puppeteer does not provide a documented “last N pages” token. First determine the final page number using the same print content, CSS, fonts, paper size, margins and scale that will be used for export. Then convert the desired tail into an explicit range and pass it to page.pdf(). For example, if the rendered document has 240 pages and you need the final 10, use pageRanges: '231-240'.
What Puppeteer can and cannot select
The pageRanges option accepts ordinary page numbers and ranges, including comma-separated selections such as 1-5, 8, 11-13. An empty range prints the whole document. The documented syntax does not define a suffix expression such as last-5, a negative range, or a built-in “last N pages” query.
That means the job has two separate stages:
- Establish the page count under the final print conditions.
- Build an explicit range for the ending pages and generate the PDF with that range.
If the final page is P and you want N pages, the first page is Math.max(1, P - N + 1). A 240-page document and a 10-page tail therefore become 231-240. This arithmetic is yours to perform; Puppeteer’s documented API does not perform it automatically.
A reliable two-stage implementation
1. Prepare the page exactly as it will be printed
Use the same URL, HTML, print styles, fonts, viewport, paper format, margins, scale and browser options in both the counting step and the final export. A changed heading wrap, late-loading font or different margin can move a page break and invalidate previously calculated numbers.
#1 Best Overall
- BEST FOR SMALL BUSINESSES – Engineered for extraordinary productivity, the Brother DCP-L2640DW Monochrome (Black & White) 3-in-1 combines laser printer, scanner, copier in one compact footprint and delivers high-quality black & white prints
- FAST PRINTER WITH EFFICIENT SCANNING – Produces documents quickly with print speeds up to 36 ppm(2) and scan speeds up to 23.6/7.9 ipm(3) (black/color). A 50-page auto document feeder(4) allows for convenient, time saving multi-page scanning and copying
- FLEXIBLE CONNECTION OPTIONS – Easily navigate the changing demands of your business with secure multi-device connectivity via built-in dual-band wireless (2.4GHz / 5GHz) and Ethernet. Or connect locally to a single computer via USB interface
- BROTHER MOBILE CONNECT APP – Print, scan, and manage your wireless printer anytime, from almost anywhere from your mobile device. Order Brother Genuine Supplies, track toner usage, and complete more work on-the-go(5)
- CHOOSE BROTHER GENUINE TONER – When it’s time to replace your toner, be sure to choose Brother Genuine TN830 or TN830XL replacement toner. And with Refresh EZ Print Subscription Service, you’ll never worry about running out of toner again and you’ll enjoy savings of up to 50%(6) on Brother Genuine Toner. Get started with Refresh today with a Free Trial(1)
Page.pdf() uses the print CSS media type by default. If the document is intended to look like the screen version, call page.emulateMediaType('screen') before producing the PDF. Puppeteer’s PDF generation guide also states that PDF generation waits for fonts by default, which is important because font metrics can alter pagination.
2. Obtain the page count in an application-specific way
The official API documentation does not prescribe a page-count function or a universal recipe for measuring printed pages. Your application must supply that step. Common approaches include maintaining a page count from a document-generation pipeline, rendering a pagination-aware intermediate document, or splitting source content into known print sections. Whatever method you use, it must use the same print inputs as the final export.
Do not assume that a preliminary PDF and a final PDF will paginate identically if their content or print settings differ. Treat the count as valid only after checking representative documents, especially those containing long tables, images, custom fonts, floats or dynamic content.
Rank #2
- BEST FOR HOMES & HOME OFFICES – Engineered for consistent, premium print quality, the Brother HL-L2405W Monochrome (Black & White) Laser Printer delivers sharp, crisp prints at an affordable price. Prints one-sided documents at speeds up to 30ppm(2)
- COMPACT, CONNECTED PRINTER – Flexible connection options make this an ideal printer for home use and at-home offices. Securely connect to multiple devices with built-in dual-band wireless (2.4GHz/5GHz) or locally to a single computer via USB interface
- BROTHER MOBILE CONNECT APP – Manage your printer remotely and print from your mobile device anytime, from almost anywhere. Order Brother Genuine Supplies, track toner usage, and complete more work on-the-go(3)
- VERSATILE PAPER HANDLING – Enjoy seamless, reliable everyday printing with the 250-sheet paper tray(4) and a manual feed slot that enables printing on envelopes and specialty pape
- BROTHER IS AT YOUR SIDE – Backed by Brother with a 1-year limited warranty and free online, call, or live chat support for the life of your printer
3. Pass explicit page numbers to page.pdf()
const pdf = await page.pdf({
pageRanges: '231-240',
});
This selects one contiguous tail. For a non-contiguous selection, use comma-separated ranges, for example pageRanges: '235-240, 245'. To print everything, use an empty string (or omit the option), rather than trying to express “all except the first pages.”
Complete Puppeteer example
The following Node.js program shows the export half of the workflow. It assumes your application has already established that the document ends on page 240 and wants its last 10 pages. Replace the URL and range with values generated by your own pagination step.
import puppeteer from 'puppeteer';
import { writeFile } from 'node:fs/promises';
const url = 'https://example.com/long-document';
const lastPage = 240; // Supplied by your pagination/counting step
const pagesWanted = 10;
const firstPage = Math.max(1, lastPage - pagesWanted + 1);
const pageRanges = `${firstPage}-${lastPage}`;
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
await page.goto(url, { waitUntil: 'networkidle0' });
// Use this only when the PDF should follow screen CSS rather than print CSS.
// await page.emulateMediaType('screen');
const pdf = await page.pdf({
format: 'A4',
printBackground: true,
pageRanges,
path: 'last-pages.pdf',
});
// page.pdf() returns a Uint8Array. The path option has already written it;
// this line is useful when you also need the bytes in application code.
await writeFile('last-pages-copy.pdf', pdf);
console.log(`Wrote pages ${pageRanges}`);
} finally {
await browser.close();
}
If the source requires a different paper size, margins, landscape orientation, scale, headers or footers, put those options in both the counting process and this call. A range is interpreted against the complete print layout, not against the number of DOM sections or screen scroll regions.
Rank #3
- FAST PRINT SPEEDS: Print up to 19 pages per minute.
- COMPACT DESIGN: Space-saving, compact design fits anywhere in your home, school or small office.
- WIRELESS CONNECTIVITY: Print from almost anywhere in your workspace using your compatible mobile device.
- PAPER CAPACITY: Up to 150 sheets.
- SUSTAINABILITY: Uses less than 2 watts in Energy Saver mode.
Handling dynamic and large documents
Wait for content that affects pagination
networkidle0 can be useful when the page loads data before printing, but it is not a guarantee that every application has finished its own rendering. If a known element signals readiness, wait for that selector; a controlled delay may be appropriate for animations or client-side layout. Ensure images have loaded and fonts are available before relying on the page count.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesKeep the two passes deterministic
- Use identical HTML and data. A timestamp, random identifier or rotating advertisement can change page breaks.
- Use the same viewport and device scale settings.
- Keep paper size, margins, scale, orientation and print-background settings identical.
- Use the same browser and installed fonts when counting and exporting.
- Disable animations or freeze transitions if they can change measured layout.
Choose an output interface
page.pdf() resolves to a Uint8Array. Puppeteer also exposes page.createPDFStream(), which resolves to a web ReadableStream<Uint8Array>. Choose the form that fits your storage or HTTP pipeline. A stream changes how generated bytes are consumed; the API documentation does not establish that it reduces the browser’s memory needed to lay out a large document or generate the PDF.
What “large” changes—and what it does not
A large HTML document can increase layout time, asset loading time and the amount of data your process must handle. However, the consulted Puppeteer documentation does not publish a maximum page count, memory limit, speed benchmark or safe threshold for large PDFs. Do not promise that streaming, a particular page range or a fixed browser setting will solve memory pressure without measuring your actual workload.
Rank #4
- BEST FOR HOME OFFICES & SMALL TEAMS – Engineered for consistent, premium print quality, the Brother HL-L2460DW Monochrome (Black & White) Laser Printer produces documents that are clear, crisp, and easy to review and share, all at an affordable price
- COMPACT, CONNECTED, EXCEPTIONALLY EFFICIENT– Connect with built-in dual-band wireless (2.4GHz/5GHz), Ethernet, or to a single computer via USB interface. Prints at speeds up to 36ppm(2), plus automatic duplex printing saves time and reduces paper waste
- BROTHER MOBILE CONNECT APP – Manage your wireless printer remotely and print from your mobile device anytime, from almost anywhere. Order Brother Genuine Supplies, track toner usage, and complete more work on-the-go(3)
- VERSATILE PAPER HANDLING – Tackle high-volume black & white printing with the 250-sheet capacity paper tray.(4) The manual feed slot enables printing on envelopes and specialty paper
- BROTHER IS AT YOUR SIDE – Backed by Brother with a 1-year limited warranty and free online, call, or live chat support for the life of your printer
Printing only the final pages reduces the bytes in the resulting file, but the browser still needs to construct the document’s print layout to know where those pages fall. Selecting 231-240 is therefore not documented as a way to make the initial HTML layout proportional only to ten pages.
Troubleshooting
The output is blank or has the wrong pages
- Cause: The range was calculated from a different layout than the export.
- Fix: Recount with identical content, fonts, print media, paper settings, margins and scale. Verify the first and last page numbers on a full test export.
pageRanges is ignored or rejected
- Cause: The value is not valid explicit syntax.
- Fix: Use numbers and hyphenated ranges such as
231-240, with commas between separate selections. Remove unsupported words such aslastor negative numbers. Check the installed Puppeteer version’s API reference if behavior differs.
The last page contains content expected on the previous page
- Cause: Fonts, images or late JavaScript changed line wrapping or element heights.
- Fix: Wait for the relevant selectors and assets, keep font availability consistent, and make the page deterministic before counting.
The PDF looks different from the browser window
- Cause: PDF generation uses print media by default.
- Fix: Keep print CSS if that is the desired design. Otherwise call
page.emulateMediaType('screen')beforepage.pdf(), and recount under that media type.
Streaming did not fix memory usage
- Cause:
createPDFStream()changes byte delivery, not the documented layout process. - Fix: Profile the real workload, reduce unnecessary DOM and assets, and investigate browser or host limits separately. The API documentation supplies no memory guarantee.
The requested tail is longer than the document
Clamp the first page to one, as in Math.max(1, lastPage - pagesWanted + 1). For a document ending on page 7 with a request for 10 pages, the valid range is 1-7.
Recommended Free Tools
Validation checklist before production
- Confirm that the count and export use the same URL or generated HTML.
- Confirm print versus screen media explicitly.
- Confirm fonts, images and dynamic data are ready before counting.
- Log the discovered last page, requested count and final range.
- Reject malformed or inverted ranges before calling Puppeteer.
- Inspect a sample where a heading, table or image crosses a page boundary.
- Retest when templates, fonts, browser versions or print CSS change.
Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server. It is useful when you need an image or PDF without maintaining your own browser capture service, but it does not replace Puppeteer’s explicit page-range calculation for an HTML PDF workflow. Before capture, it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.
For a one-call capture, see the ScreenshotNeo documentation and use:
Best Value
- FROM AMERICA'S MOST TRUSTED PRINTER BRAND – Perfect for small teams printing professional-quality black & white documents and reports. Perfect for 1-3 people
- WORLD'S SMALLEST LASER IN ITS CLASS – Precision laser printing that fits anywhere
- FAST PRINT SPEEDS – Up to 21 black-and-white pages per minute single-sided
- WIRELESS WITH SELF-RESET – Helps you stay connected
- PRINT FROM ANY DEVICE – Wireless printing from any mobile device, PC or tablet. Works with Microsoft, Mac, AirPrint, Android, Chromebook and more
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo supports PNG, JPEG, WebP and PDF output, full-page captures with lazy images loaded, element selection, custom CSS and JavaScript, waits, blocking rules, headers and cookies, device and viewport settings, resizing, caching, signed links, asynchronous webhooks and bulk capture of up to 100 URLs per call. Every feature is on every plan: 1,000 shots per month are free with no card; paid plans start at $5 for 3,000 shots. Learn about ScreenshotNeo or sign up for the free plan.
Key takeaways
- Compute the final printed page number yourself; Puppeteer documents explicit ranges, not a “last N” expression.
- Use
pageRangessuch as231-240after matching the final print conditions. page.pdf()returns bytes, whilecreatePDFStream()returns a byte stream; neither is documented as a layout-memory fix.- Recount whenever content, fonts, print CSS or PDF settings change.
Frequently Asked Questions
Can I write pageRanges: 'last-5' or use a negative number?
No documented Puppeteer syntax provides that shortcut. Determine the ending page number and pass a normal explicit range such as 231-240.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Does selecting a tail range avoid rendering the earlier HTML pages?
The documentation does not promise that. The browser still needs the document’s print layout to determine pagination, so measure your workload rather than assuming proportional savings.
When should I use createPDFStream() instead of pdf()?
Use the stream when your application naturally writes or forwards chunks; use pdf() when a Uint8Array is more convenient. The documented return types do not establish a speed or memory advantage.
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.

