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

To make a PDF end where your rendered HTML ends, measure the page after images, fonts, and JavaScript content have finished laying out, then pass that measurement as the PDF paper height. Set every PDF margin explicitly—usually to zero when the HTML already supplies its own spacing. In Puppeteer, also account for print CSS and the preferCSSPageSize option; in wkhtmltopdf, use --page-height, --page-width, and explicit margin switches.

The reliable sequence

Blank space is normally caused by a paper size that is taller than the document, not by the HTML itself. A robust implementation follows this order:

  1. Render in the same engine that will create the PDF. Browser layout and a different measurement browser can disagree on fonts, JavaScript, and replaced elements.
  2. Wait for all content that affects height. Include application data, images, web fonts, and any delayed components.
  3. Measure after layout settles. Measure the container you intend to print, or the document’s maximum scroll/offset height.
  4. Add only intentional padding. Do not add a safety value merely to hide a race condition; fix the late-loading content instead.
  5. Set paper dimensions and all margins. A measured content height is useful only if the PDF engine is not adding its own top, bottom, left, or right margins.
  6. Test long and unusual content. Images, long words, page-break rules, headers, and fonts can reflow after the first measurement.

The measured height is usually in CSS pixels. Convert it only when your PDF API requires another unit. Keep the conversion in one place and document the assumed CSS pixel density; do not mix an arbitrary pixel-to-millimetre constant with a browser scale setting.

Puppeteer: fit the PDF to rendered content

Puppeteer’s page.pdf() generates a PDF using the print CSS media type by default. Its PDF options include height, width, margin, and preferCSSPageSize. When preferCSSPageSize is true, a CSS @page declaration takes priority over the API’s width, height, or format.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Epson Workforce ES-50 Compact & Lightweight Mobile Document Scanner
  • PORTABLE SCANNER FOR USE ON-THE-GO — The fastest and lightest mobile single-sheet-fed compact document scanner in its class¹
  • QUICK DOCUMENT SCANNING ― This Epson ultra-fast scanner scans a single page as quickly as 5.5 seconds²; Windows and Mac compatible
  • VERSATILE PAPER HANDLING ― Portable scanner scans documents up to 8.5 x 72 in; Also easily digitizes receipts and ID cards to make accounting, bookkeeping, and organizing simpler
  • INTUITIVE, HIGH-SPEED SOFTWARE — Epson ScanSmart Software³ is a smart tool allowing you to easily scan, review, and save; Stay organized easily with the help of this Epson scanner
  • EASY SETUP — USB-powered connect to your computer for quick and simple scanning; No batteries or external power supply required to operate portable document scanner; Standard Connectivity: USB 2.0

Complete Node.js example

const puppeteer = require('puppeteer');

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

    // Wait for web fonts. The optional chaining keeps this safe on pages
    // where the Font Loading API is unavailable.
    await page.evaluate(() => document.fonts?.ready);

    // If your application has a specific readiness signal, wait for it too.
    // await page.waitForSelector('#report-ready', {timeout: 30000});

    const heightPx = await page.evaluate(() => {
      const root = document.documentElement;
      const body = document.body;
      return Math.max(
        root.scrollHeight,
        root.offsetHeight,
        body ? body.scrollHeight : 0,
        body ? body.offsetHeight : 0
      );
    });

    if (!Number.isFinite(heightPx) || heightPx <= 0) {
      throw new Error(`Invalid measured height: ${heightPx}`);
    }

    await page.pdf({
      width: '210mm',
      height: `${heightPx}px`,
      margin: {top: '0', right: '0', bottom: '0', left: '0'},
      printBackground: true,
      // Set true only when your @page rule should control page size.
      preferCSSPageSize: false
    });
  } finally {
    await browser.close();
  }
})();

Replace the URL and write the returned PDF to a file in your application (for example, by passing a path property to page.pdf()). The example deliberately uses a fixed width and a measured height. If your design should own both dimensions, define them in print CSS and set preferCSSPageSize: true instead of supplying competing API dimensions.

Use print CSS deliberately

@media print {
  html, body { margin: 0; padding: 0; }
  @page { margin: 0; }
  .screen-only { display: none !important; }
}

Because Puppeteer prints with print media by default, rules inside @media print affect the PDF. Call page.emulateMediaType('screen') only when the screen stylesheet is intentionally the output you want; otherwise, screen-only spacing and controls can produce surprising dimensions.

Measure a content wrapper when the document shell is not part of the PDF

Document-level scroll height includes every element that contributes to the page. If a fixed application shell, hidden overflow region, or an intentionally excluded footer surrounds the printable content, measure a dedicated wrapper instead:

const heightPx = await page.$eval('#print-root', element => {
  const box = element.getBoundingClientRect();
  const style = getComputedStyle(element);
  const padding = parseFloat(style.paddingTop) + parseFloat(style.paddingBottom);
  return Math.ceil(box.height + padding);
});

Choose one measurement strategy. Do not measure a wrapper and then add the document’s full scroll height, or you will reproduce the very trailing space you are trying to remove. If margins collapse outside the wrapper, put the intended spacing on padding or measure the outer element that owns it.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

Waiting for dynamic content before measuring

networkidle0 waits for network activity to become quiet, but it cannot know that your application has finished rendering. A page may fetch data after an idle period, decode an image later, or replace a fallback font after measurement.

Rank #2
Sale
Brother DS-640 Compact Mobile Document Scanner, (Model: DS640)
  • FAST SPEEDS - Scans color and black and white documents a blazing speed up to 16ppm (1). Color scanning won’t slow you down as the color scan speed is the same as the black and white scan speed.
  • ULTRA COMPACT – At less than 1 foot in length and only about 1. 5lbs in weight you can fit this device virtually anywhere (a bag, a purse, even a pocket).
  • READY WHENEVER YOU ARE – The DS-640 mobile scanner is powered via an included micro USB 3. 0 cable allowing you to use it even where there is no outlet available. Plug it into you PC or laptop and you are ready to scan.
  • WORKS YOUR WAY – Use the Brother free iPrint&Scan desktop app for scanning to multiple “Scan-to” destinations like PC, Network, cloud services, Email and OCR. (2) Supports Windows, Mac and Linux and TWAIN/WIA for PC/ICA for Mac/SANE drivers. (3)
  • OPTIMIZE IMAGES AND TEXT – Automatic color detection/adjustment, image rotation (PC only), bleed through prevention/background removal, text enhancement, color drop to enhance scans. Software suite includes document management and OCR software. (4)
  • Wait for a deterministic selector such as #report-ready after the application has inserted its final data.
  • Wait for document.fonts.ready so changed glyph metrics do not move line breaks.
  • Wait for images to decode, especially when their dimensions are not fixed in CSS.
  • Use a short, justified delay only for a known third-party animation or widget; a blind long delay increases latency without guaranteeing readiness.
await page.waitForFunction(() => {
  const images = [...document.images];
  return images.every(img => img.complete && img.naturalWidth > 0);
}, {timeout: 30000});
await page.evaluate(() => document.fonts?.ready);
await page.waitForSelector('#report-ready', {timeout: 30000});

Reserve space for media with explicit width and height (or an aspect ratio) where possible. That reduces layout shifts and makes the final measurement reproducible.

CSS page size, margins, and page breaks

A fixed @page height or a standard format such as A4 can be taller than a short report. Conversely, a measured height that is too small clips content. Headers, footers, forced page breaks, and page-break avoidance can also create additional pages or reserved areas even when the body’s height looks correct.

  • Remove browser and engine margins when HTML spacing is authoritative.
  • Inspect @page, break-before, break-after, and break-inside rules.
  • Keep deliberate top and bottom padding in the measured element, rather than adding an unexplained PDF margin.
  • For multi-page documents, remember that “fit content height” does not mean every page has a custom height. A very tall single page may be unsuitable for printing; use normal paper dimensions when page portability matters.

wkhtmltopdf: set page height from your measurement

wkhtmltopdf exposes direct command-line switches for fine-grained dimensions: --page-height <unitreal> and --page-width <unitreal>. It also provides --margin-top, --margin-bottom, --margin-left, and --margin-right. Measure the rendered content in the calling application, convert the result to the unit used by your command, and then invoke wkhtmltopdf.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
wkhtmltopdf 
  --page-width 210mm 
  --page-height 420mm 
  --margin-top 0 
  --margin-right 0 
  --margin-bottom 0 
  --margin-left 0 
  input.html output.pdf

Replace 420mm with the measured height converted by your pipeline. The corresponding libwkhtmltox settings expose size.height, size.width, size.pageSize, and margin fields such as margin.top and margin.bottom. A value that is too large recreates trailing blank space; a value that is too small clips the last lines or replaced elements.

Choosing between Puppeteer and wkhtmltopdf

Choose the engine that matches the site’s CSS and JavaScript rather than assuming one has a universal advantage. Compare these practical axes:

Rank #3
Canon imageFORMULA R10 - Portable Document Scanner, USB Powered, Duplex Scanning, Document Feeder, Easy Setup, Convenient, Perfect for Mobile Users, White
  • STAY ORGANIZED – Easily convert your paper documents into digital formats like searchable PDF files, JPEGs, and more.Power Consumption : 2.5W or less (Energy Saving Mode: 0.7W). Suggested Daily Volume : 500 scans..Does it contain liquid: no
  • CONVENIENT AND PORTABLE –lightweight and small in size, you can take the scanner anywhere from home offices, classrooms, remote offices, and anywhere in between
  • HANDLES VARIOUS MEDIA TYPES – Digitize receipts, business cards, plastic or embossed cards, reports, legal documents, and more
  • FAST AND EFFICIENT – No technical hurdles or complicated setups here; easily scan both sides of a document at the same time, in color or black-and-white, at up to 12 pages-per-minute, and with a 20 sheet automatic feeder
  • BROAD COMPATIBILITY – Works with both Windows and Mac devices, be it laptop or computer
Concern Puppeteer wkhtmltopdf
Dimension controls height, width, margin, and CSS precedence through preferCSSPageSize --page-height, --page-width, and margin switches; equivalent library settings are available
Media mode Print CSS is the default; screen media can be selected deliberately Use the print behavior and switches supported by your installed build
Dynamic pages Can wait for selectors, fonts, network state, and application logic in the browser Requires you to configure the available loading and JavaScript behavior and measure consistently
Operational decision Prefer when the page relies on modern browser JavaScript and fonts Prefer when your existing pipeline already matches its rendering behavior and options

The documentation for these options describes controls, not a benchmark of blank-space rates or rendering fidelity. Test representative pages from your own application.

Troubleshooting blank space and clipping

There is a uniform band at the bottom

Check PDF bottom margin, CSS @page margin, and a fixed paper format first. Set all margins explicitly and inspect whether the chosen API height is larger than the measured value.

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

The last paragraph is clipped

The measurement probably occurred before an image, font, or client-rendered component changed layout, or the unit conversion rounded down. Wait for readiness, measure again, and round upward by a minimal intentional amount only after verifying the source of the reflow.

Only pages containing images are wrong

Wait until every image is complete and has a non-zero natural width. Give images dimensions or an aspect ratio so decoding cannot move surrounding text after measurement.

Text wraps differently in the PDF

Print CSS may select a different font or width. Load the intended web fonts before measuring, use the same viewport and width for measurement and PDF creation, and inspect @media print overrides.

Rank #4
IRIScan Express 4 Black Compact Portable USB Simplex Document Scanner, 8 PPM for Contracts, Invoices and Business Cards, Compatible with Windows, Readiris PDF Included
  • IRIScan Express, portable scanner : scans color and black and white documents a blazing speed up to 8ppm simplex. Color scanning won’t slow you down as the color scan speed is the same as the black and white scan speed.
  • IRIScan Express mobile scanner is powered via an included micro USB 2. 0 cable allowing you to use it even where there is no outlet available. Plug it into you PC or laptop and you are ready to scan. USB cable provided. AC Adapter not provided and not needed.
  • IRIScan flatbed scanner uses a simplex scanning mode allows for quick and straightforward scanning of single-sided documents. IRIScan with its full portable features is the ideal document scanners for computers.
  • IRIScan document scanner : Versatile scanning capabilities, including scanning to Word, PDF, and Excel formats with companion software provided Readiris OCR
  • Receipt scanner and card scanner with Additional features include scanning business cards directly to Outlook, photo scanning, and receipt scanning for efficient document management

A hidden element still increases height

visibility:hidden, off-screen positioning, and reserved containers can still occupy layout space. Use display:none for content that must not contribute, or measure a wrapper that excludes it.

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

Content appears after the PDF is created

Replace arbitrary sleeps with an application readiness marker and wait for it. Then wait for fonts and images and perform the measurement as the final layout operation before calling the PDF API.

Page-break rules create unexpected blank areas

Inspect forced breaks and break-inside: avoid on large blocks. A block that cannot fit may be moved to the next page, leaving apparently unused space by design.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability, and cost considerations

  • Reuse browser processes carefully. Reusing a Puppeteer browser can reduce startup cost, but create a fresh page per job and clear cookies or storage when documents must be isolated.
  • Bound every wait. Set navigation, selector, image, and font timeouts so one broken third-party request cannot hold a worker forever.
  • Capture diagnostics. Log the measured height, viewport width, final URL, and which readiness checks completed. Save a failing HTML snapshot when policy permits.
  • Validate extremes. Test empty data, very long text, missing images, large tables, right-to-left text, and documents near page-size limits.
  • Choose page strategy intentionally. A single custom-height page is useful for receipts and compact reports; standard pages are usually better for office printing and binding.

There is no published accuracy percentage or blank-space benchmark for either engine in the option documentation. Your acceptance test should compare the PDF’s final bounding content, not merely whether the process exited successfully.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server that can return a clean screenshot or PDF from one GET request. For a direct call, use the documented endpoint and credentials:

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.
Best Value
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
  • Scanner type: Document
  • Connectivity technology: USB
  • With Auto Scan Mode, the scanner automatically detects what you're scanning
  • Digitize documents and images
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for selecting PDF output and paper settings. It removes cookie and consent banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Frequently asked questions

Should I add a fixed extra height to prevent clipping?

No. First eliminate late layout changes and unit-conversion errors. An unexplained buffer trades clipping for blank space and will vary across documents.

Can I use a custom height with ordinary A4 printing?

You can, but a single tall page may not fit common printers. Use measured height for compact, receipt-like output; use a standard page format when physical pagination matters.

Does network idle prove that a page is ready?

No. Application rendering, font replacement, image decoding, and timers can occur after network activity becomes quiet. Pair network waiting with an application readiness signal and asset checks.

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

Why does enabling CSS page size change my result?

With Puppeteer’s preferCSSPageSize enabled, the CSS @page size takes precedence over API dimensions. Remove conflicting rules or choose one source of truth.

Frequently Asked Questions

Is a zero PDF margin always correct?

Only when the HTML or its print stylesheet owns all intended spacing. If the document requires a printer-safe border, put that spacing in the design and include it in the measured area.

What should the height measurement include?

Include every visible element intended for the PDF, including intentional padding. Exclude application chrome and hidden layout regions by measuring a dedicated printable wrapper.

Quick Recap

Bestseller No. 3
Canon imageFORMULA R10 - Portable Document Scanner, USB Powered, Duplex Scanning, Document Feeder, Easy Setup, Convenient, Perfect for Mobile Users, White
Canon imageFORMULA R10 - Portable Document Scanner, USB Powered, Duplex Scanning, Document Feeder, Easy Setup, Convenient, Perfect for Mobile Users, White
BROAD COMPATIBILITY – Works with both Windows and Mac devices, be it laptop or computer; This product is not intended for scanning photographs on photo paper / photographic media
$184.00
Bestseller No. 4
IRIScan Express 4 Black Compact Portable USB Simplex Document Scanner, 8 PPM for Contracts, Invoices and Business Cards, Compatible with Windows, Readiris PDF Included
IRIScan Express 4 Black Compact Portable USB Simplex Document Scanner, 8 PPM for Contracts, Invoices and Business Cards, Compatible with Windows, Readiris PDF Included
Find our Software here : irislink.com/start; IRIScan Express is only compatible Windows platform and not macintosh
$129.00
Bestseller No. 5
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
Scanner type: Document; Connectivity technology: USB; With Auto Scan Mode, the scanner automatically detects what you're scanning
$75.00

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.

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