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.

Measure the fully rendered page after images, fonts, and client-side data have settled, then pass that measurement as the PDF paper height with every margin set explicitly. In Puppeteer, use the measured height in page.pdf(); in wkhtmltopdf, supply it through --page-height. This removes trailing whitespace without clipping content, provided you recheck late layout changes and page-break rules.

The reliable method

A PDF engine cannot know the final height of a page until the HTML has been laid out. The dependable sequence is:

  1. Render in the same engine that will create the PDF. CSS, JavaScript, fonts, and replaced elements can produce different dimensions in different engines.
  2. Wait for application data and assets. Do not measure while images are still loading, web fonts are swapping, or a client-side framework is inserting content.
  3. Measure the complete content. Use the document’s scroll height for a full-page document, or measure a deliberate content container if headers and footers must be excluded.
  4. Add only intentional padding. Do not add a guessed safety margin to compensate for an early measurement; fix the readiness condition instead.
  5. Set the PDF paper height to that value. Convert CSS pixels to the unit expected by your PDF interface when necessary.
  6. Set all four PDF margins explicitly. Use zero margins when the HTML and its print stylesheet already own the spacing.

A fixed paper format, a default print margin, or a measurement taken before late reflow is the usual reason a supposedly automatic PDF still has a blank band at the bottom.

Puppeteer: measure the page, then create a matching PDF

Puppeteer’s PDF API accepts height, width, margin, and preferCSSPageSize. PDF generation uses the print CSS media type by default. That means your print rules, not your screen rules, determine the measured layout unless you deliberately switch media.

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

Install Puppeteer with npm install puppeteer, then save this as html-to-fit-pdf.mjs:

import puppeteer from 'puppeteer';

const url = process.argv[2] || 'https://example.com/';
const browser = await puppeteer.launch({headless: true});
const page = await browser.newPage();

try {
  await page.setViewport({width: 1280, height: 900, deviceScaleFactor: 1});
  await page.goto(url, {waitUntil: 'networkidle0', timeout: 90000});

  // Wait for web fonts and every image that is part of the rendered page.
  await page.evaluate(async () => {
    if (document.fonts?.ready) await document.fonts.ready;
    const images = [...document.images];
    await Promise.all(images.map((image) => {
      if (image.complete) return Promise.resolve();
      return new Promise((resolve) => {
        image.addEventListener('load', resolve, {once: true});
        image.addEventListener('error', resolve, {once: true});
      });
    }));
  });

  // Give layout two animation frames to settle after asynchronous updates.
  await page.evaluate(() => new Promise((resolve) =>
    requestAnimationFrame(() => requestAnimationFrame(resolve))
  ));

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

  await page.pdf({
    path: 'output.pdf',
    width: '210mm',
    height: `${heightPx}px`,
    margin: {top: '0', right: '0', bottom: '0', left: '0'},
    printBackground: true,
    preferCSSPageSize: false
  });
} finally {
  await browser.close();
}

console.log(`Wrote output.pdf at ${heightPx}px high`);

Run it with node html-to-fit-pdf.mjs https://your-site.example/article. The script measures the root and body and takes the largest value, which protects against pages where one of those elements owns the overflow.

Measure a specific content container

Full-document measurement is not always appropriate. If a template has a fixed header that should not be included in the custom paper height, measure the content wrapper instead:

const heightPx = await page.evaluate(() => {
  const content = document.querySelector('#print-content');
  if (!content) throw new Error('Missing #print-content');
  return Math.ceil(content.getBoundingClientRect().height +
                   parseFloat(getComputedStyle(content).paddingTop || 0) +
                   parseFloat(getComputedStyle(content).paddingBottom || 0));
});

Use a container only when its box really contains every element that must appear. A child with overflow, an absolutely positioned element, or a margin that collapses outside the container can otherwise be left out. In those cases, measure the document or deliberately include the extra space in your calculation.

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.

Print CSS and @page precedence

Keep print-only changes in @media print:

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

#print-content {
  box-sizing: border-box;
  width: 100%;
}

If the stylesheet contains an @page size and you want that declaration to override Puppeteer’s width, height, or format, set preferCSSPageSize: true. If the measured height from JavaScript is authoritative, leave it false as in the example and avoid a conflicting fixed @page height.

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)

Puppeteer prints with the print media type by default. Use await page.emulateMediaType('screen') only when the screen stylesheet is intentionally the source for the PDF; otherwise it can make your measurement disagree with the eventual print layout.

Waiting for content that changes the required height

The measurement is only as good as the page state at that instant. A robust readiness strategy combines a navigation condition with application-specific checks.

  • Client-rendered data: wait for a selector that appears only after the data request has completed, such as [data-report-ready="true"].
  • Images: wait for document.images to report completion, and treat load errors as settled failures so one broken image does not hang the job indefinitely.
  • Fonts: await document.fonts.ready. A font swap can change line wrapping and therefore the paper height.
  • Animations and transitions: disable them in print CSS or wait until the final state. A moving element can produce a different height on every run.
  • Lazy loading: scroll through the page or otherwise trigger the site’s lazy-load mechanism before measuring. A full-page screenshot/PDF that measures before lazy images enter the DOM will be too short.
  • Late scripts: take a second measurement immediately before PDF creation if your application performs a final mutation after the first layout.

Do not rely on a long arbitrary delay as the only synchronization method. A readiness selector tied to the application is faster on short pages and safer on slow ones.

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

CSS pixels, physical units, and intentional padding

Puppeteer accepts CSS lengths such as px, mm, and in. You can pass the measured pixel count directly as ${heightPx}px, as shown above. If your calling layer requires millimetres, convert using the CSS reference scale (96 CSS pixels per inch and 25.4 millimetres per inch):

const heightMm = heightPx * 25.4 / 96;

Round up rather than down to avoid clipping fractional layout pixels, and add only the padding your design specifies. A fixed extra amount added to every document recreates the very blank space you are trying to remove, especially on short pages.

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

wkhtmltopdf: supply the measured height explicitly

wkhtmltopdf exposes fine-grained page dimensions through --page-height and --page-width, plus independent top, right, bottom, and left margin switches. The measurement normally happens in your calling application (for example, with a browser that can wait for the site’s JavaScript), after which you invoke wkhtmltopdf with that value.

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 content height converted to the unit accepted by your pipeline. A value that is too large leaves trailing whitespace; a value that is too small clips the last content. The same print CSS should remove body margins and any template spacing that the command-line margins do not account for.

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

When using the C API, the equivalent settings are the size.height, size.width, and margin fields such as margin.top and margin.bottom. Keep the width and height decisions in one layer so a CSS page size, command-line size, and library size do not silently compete.

Preventing blank space without creating new defects

Symptom Likely cause Correction
Blank band at the bottom on every PDF Default engine margins or an oversized paper format Set all margins explicitly and pass the measured height instead of a standard format.
Blank space appears only on pages with images Measurement occurred before image decoding or layout Wait for image completion, then allow a layout frame before measuring.
Text is clipped at the end Height was rounded down or content reflowed after measurement Round up, await fonts and late scripts, and measure immediately before PDF creation.
Content is missing outside the measured wrapper Collapsed margins, overflow, or absolutely positioned children Measure the document or include those boxes explicitly; inspect the wrapper’s computed layout.
Header or footer leaves an unexplained gap Reserved header/footer space or page-break rules Remove unused header/footer reservations and review break-before, break-after, and legacy page-break rules.
PDF differs from the browser preview Puppeteer used print CSS while the preview used screen CSS Align the media type intentionally and test the same CSS path used for PDF output.

Long documents, page breaks, and operational limits

A custom paper height creates one very tall page. That is useful for receipts, embeds, and single-page exports, but it is not the same as normal pagination on Letter or A4 paper. For a report intended for printing, keep a standard page size and fix the unwanted space with margins and page-break rules instead of forcing the entire report into one page.

For long single-page output, test viewer and printer limits as well as your PDF engine. Verify headings, tables, replaced elements, and links near the bottom. A page-break rule can reserve space or move a block even when the raw scroll height looks correct. Capture a representative short document, a document with long wrapped text, and the largest document your service permits.

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

Rendering waits, font downloads, image decoding, and JavaScript execution dominate runtime. Reuse a browser process when your service handles many jobs, but isolate pages and close them after each conversion. Cache stable assets where appropriate, and record the measured height and final PDF options so a clipped output can be diagnosed. There is no universal blank-space percentage or accuracy benchmark: the result depends on the page’s CSS, assets, and readiness logic.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Puppeteer or wkhtmltopdf?

Decision point Puppeteer wkhtmltopdf
Dynamic JavaScript applications Direct control over navigation, DOM measurement, fonts, and media type. Requires careful timing and often an external measurement step.
Dynamic paper height Pass a measured CSS-pixel height to page.pdf(). Pass the converted value through --page-height or library size settings.
Print CSS control Print media is the default; preferCSSPageSize controls CSS page-size precedence. Use the stylesheet together with explicit command-line or library dimensions.
Operational footprint Includes a Chromium runtime and its startup cost. Uses its own rendering binary; confirm that its CSS and JavaScript behavior matches your site.
Evidence available here Official options document dimensions and print behavior. Official usage and library references document dimensions and margins.

Choose the engine that matches your site’s CSS, JavaScript, and font behavior; the documented options do not establish a cross-engine rendering benchmark.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server. One GET request can return a PNG, JPEG, WebP, or PDF, while the service handles browser setup for you. It accepts consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and each response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers.

For PDF work, its capture options include paper size, margins, landscape mode, and page ranges. Other controls cover full-page lazy-image loading, CSS-selector element capture, dark mode, device and retina settings, custom CSS and JavaScript, click-before-capture actions, selector waits, network-idle waits, ad/tracker/request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, TTL-based caching, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, usage reporting, and an OpenAPI specification. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

Use the ScreenshotNeo API documentation for the current PDF parameters. A basic request looks like this:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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}`);

The Free plan includes 1,000 shots each month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan, and yearly billing provides two months free. Create a free ScreenshotNeo account to try it.

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

Final validation checklist

  • Render with the same engine and media type used for the final PDF.
  • Wait for data, images, fonts, lazy content, and final DOM mutations.
  • Measure the complete intended box after layout settles.
  • Round up and add only deliberate design padding.
  • Set width, height, and all four margins explicitly.
  • Resolve whether CSS @page or API dimensions have precedence.
  • Test short, long, image-heavy, and late-loading documents.
  • Inspect the bottom edge, page-break rules, headers, and footers in the resulting file.

Frequently Asked Questions

Can I make every PDF exactly one page tall?

Yes, if the content fits within the engine and viewer limits: measure the settled content and use that value as the custom paper height. For documents meant for ordinary printing, standard pagination is usually more practical.

Should I keep a nonzero bottom margin as insurance?

Only when that margin is part of the design. An insurance margin hides readiness or measurement errors and will appear as blank space on short documents.

Why does a font change alter the PDF height?

Different font metrics change line wrapping and line count. Wait for document.fonts.ready before measuring and ensure the same fonts are available in the PDF runtime.

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

Does a cached page need to be measured again?

Yes. Cache state can change which assets are immediately available, but the final DOM still must be measured after layout settles.

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.