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

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Extra whitespace in a headless Chrome PDF usually comes from one of four places: CDP print margins, a paper-size mismatch that causes scaling, Chrome-generated headers and footers, or the page’s own print CSS. Fix it by setting every relevant Page.printToPDF option explicitly, then checking @page and print-only layout rules.

Identify which kind of blank space you have

Look at the PDF before changing code. The pattern points to the setting responsible:

  • Even strips on all four edges: inspect marginTop, marginBottom, marginLeft and marginRight. CDP expresses these values in inches. Omitting them can leave a nonzero default; a Java CDP reference documents approximately 1 cm per side.
  • A band only at the top or bottom containing a date, URL or page number: Chrome’s generated header/footer is enabled. Set displayHeaderFooter to false.
  • The whole page appears reduced with larger-looking borders: requested paper dimensions and CSS @page dimensions are disagreeing. Check preferCSSPageSize.
  • Whitespace that follows a component, page break or print-only element: inspect the document’s print CSS. CDP cannot remove space created by your own layout rules.

Keep the HTML and CSS constant while testing one setting at a time. Otherwise a change in layout can be mistaken for a CDP fix.

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

Set CDP margins explicitly

Page.printToPDF accepts four independent margins: marginTop, marginBottom, marginLeft and marginRight. All are measured in inches, not pixels, points or CSS millimetres.

#1 Best Overall
Brother DCP-L2640DW Wireless Compact Monochrome Multi-Function Printer, Copy, Scan, Duplex, Mobile Printing
  • 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)

For edge-to-edge output, pass 0 for all four values. That is appropriate only when the target printer, viewer or downstream workflow allows content to reach the sheet edge. For a document that needs a safe printable area, use the intended nonzero values instead of blindly setting every margin to zero.

Do not rely on omitted parameters. A client or browser version may supply a default margin, and the resulting whitespace can look like a CSS bug. Make the values part of your application’s PDF configuration so that a browser upgrade does not silently change the result.

Coordinate paper dimensions with CSS @page

CDP also accepts paperWidth and paperHeight, in inches. Separately, the page can declare a print sheet in CSS:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
@media print {
  @page {
    size: 8.5in 11in;
    margin: 0;
  }
}

By default, preferCSSPageSize is false. In that mode Chrome fits the document to the requested paper dimensions, which can scale the content and make the surrounding blank area appear larger than expected. Set preferCSSPageSize to true when the CSS @page size should control the sheet. Then verify the resulting PDF: the CSS size, CDP margins and the content’s print layout must still agree.

Choose one source of truth for each project:

Goal CDP paper settings preferCSSPageSize CSS
Application-controlled fixed sheet Set paperWidth and paperHeight explicitly false Keep @page compatible
Document-controlled sheet Provide dimensions only if your client requires them true Define the intended @page size
Edge-to-edge document Set all four margins to 0 Choose according to the size strategy Remove conflicting print margins

Disable generated headers and footers

Chrome can add a date/time, page URL and page number around the document. These are not part of your HTML, so changing body margins will not remove them. Set displayHeaderFooter to false in the CDP command.

Rank #2
Brother HL-L2405W Wireless Compact Monochrome Laser Printer with Mobile Printing, Black & White Output | Includes Refresh Subscription Trial(1), Works with Alexa
  • 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

The equivalent headless command-line switch is --no-pdf-header-footer. Older Chrome releases used a previous flag name, so check the browser version if an old automation script still appears to add these elements. In a Java CDP call, prefer the protocol setting rather than depending on a launch flag.

A Java implementation that sends the CDP command

Selenium’s generated DevTools classes are versioned. The v124 reference cited for Selenium 4.22.0 must not be copied unchanged into a project using another Selenium or Chrome version. The following approach uses Selenium’s generic CDP bridge, so the payload is visible and easy to compare with the protocol fields; still verify the command against the browser version in your build.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Navigate to the page and wait until the content needed in the PDF is present.
  2. Build a map for Page.printToPDF, including all margins, paper dimensions, header/footer state and CSS-size preference.
  3. Send the command through executeCdpCommand.
  4. Decode the returned Base64 PDF data and write it as bytes.
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class PdfWithControlledMargins {
  public static void main(String[] args) throws IOException {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("--headless=new");
    ChromeDriver driver = new ChromeDriver(options);

    try {
      driver.get("https://example.com/report");
      // Replace this wait with an explicit wait for your real page.
      driver.findElement(By.tagName("body"));

      Map<String, Object> settings = new HashMap<>();
      settings.put("displayHeaderFooter", false);
      settings.put("paperWidth", 8.5);
      settings.put("paperHeight", 11.0);
      settings.put("marginTop", 0.0);
      settings.put("marginBottom", 0.0);
      settings.put("marginLeft", 0.0);
      settings.put("marginRight", 0.0);
      settings.put("preferCSSPageSize", true);
      settings.put("printBackground", true);

      Map<String, Object> result = driver.executeCdpCommand(
          "Page.printToPDF", settings);
      String base64 = (String) result.get("data");
      Files.write(Path.of("report.pdf"), Base64.getDecoder().decode(base64));
    } finally {
      driver.quit();
    }
  }
}

This example deliberately uses zero margins and CSS-controlled paper size to demonstrate the controls. Change those values to your intended output; zero is not a universal correction. If your Selenium version exposes a generated Page.printToPDF method, use the same fields and confirm the exact argument order and Optional types in that version’s API.

Inspect print CSS after CDP settings

When explicit margins and displayHeaderFooter:false do not explain the space, inspect rules active under @media print and @page. Common causes include a print-only top banner, a fixed-height wrapper, an element with min-height, or a page-break rule that leaves an intentional gap.

Use browser DevTools’ Rendering or emulated print media view to compare the screen and print layouts. Check computed dimensions for the first and last visible content elements, not just the document body. A body margin, an @page margin and a CDP margin are separate layers; removing one does not remove the others.

@media print {
  /* Example only: match these values to your design. */
  @page { margin: 0.25in; }
  body { margin: 0; }
  .print-only-toolbar { display: none; }
}

This is a diagnostic pattern, not a universal stylesheet. Preserve margins required for readability, binding, printer hardware or legal forms.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Canon imageCLASS LBP6030w - Monochrome Single-Function Wireless Compact Wireless Laser Printer, 1 Year Limited Warranty, 19 PPM, White - Print Only
  • 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.

Version and dependency checks

  • Record the Chrome/Chromium version used in CI and locally.
  • Record the Selenium version and the DevTools protocol version it targets.
  • Check whether your Java client uses generated DevTools classes or a generic CDP command method.
  • Re-run a known HTML fixture after upgrades and compare page size, content scale, four margins and header/footer presence.

Selenium publishes versioned DevTools APIs; a signature documented for Selenium 4.22.0 and protocol v124 is not a promise that another dependency line has the same method signature.

Troubleshooting blank space and failed PDFs

Whitespace remains after setting all margins to zero

Confirm that the PDF was generated by the new code and that no wrapper configuration overwrites the map. Then inspect @page, body margins and print-only elements. If the space is only at the top or bottom and contains text, verify displayHeaderFooter is actually false.

The content is scaled down

Compare paperWidth/paperHeight with the CSS @page size. With preferCSSPageSize:false, Chrome fits content to the requested dimensions. Set it to true when CSS should govern, or make both dimensions agree.

The Java code does not compile

Generated DevTools APIs differ by Selenium version and may require Optional values or a different parameter order. Use the generic executeCdpCommand payload above, or translate each field using the exact API reference for your dependency rather than copying a v124 example.

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.

The PDF contains a URL, date or page number

Set displayHeaderFooter to false. If you launch Chrome separately, also check the headless header/footer switch supported by that browser version.

Rank #4
Brother HL-L2460DW Wireless Compact Monochrome Laser Printer with Duplex, Mobile Printing, Black & White Output | Includes Refresh Subscription Trial(1), Works with Alexa
  • 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

The PDF is blank or missing late content

Wait for the application’s real readiness condition before calling Page.printToPDF. A body element existing only proves that navigation created a DOM; it does not prove that asynchronous data, fonts or images have finished loading. Use an explicit Selenium wait for a page-specific selector and test the same wait in CI.

Only one page has an unexpected gap

Inspect page-break rules and the element immediately before the gap in print media. A forced break, fixed height or unbreakable flex/grid item can create page-specific whitespace even when global margins are correct.

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

Performance, reliability and cost considerations

PDF generation is sensitive to page readiness and layout complexity. Reusing a browser session can avoid repeated startup cost, but isolate jobs when pages contain user-specific cookies or state. Keep the wait condition specific so you do not print before data arrives, while avoiding an unnecessarily long fixed sleep.

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

For reliable comparisons, fix the browser version, viewport, device scale factor, fonts and HTML fixture. Capture the generated PDF’s page dimensions and hash in CI; a visual diff can then distinguish a margin regression from a content change. Do not infer correctness from file size alone.

CDP itself does not charge per PDF. Your costs come from browser infrastructure, CI time and any service used to host or render the page. If you need a managed screenshot rather than a Java-controlled PDF pipeline, a hosted API can remove browser maintenance.

Best Value
HP LaserJet M110w Wireless Black & White Printer, Print, Fast speeds, Easy Setup, Mobile Printing, Best-for-Small Teams
  • 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

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server. A single GET request returns a PNG, JPEG, WebP or PDF, so you do not have to maintain Chrome, Selenium or CDP for a hosted capture. The API accepts the URL and returns the file; see the ScreenshotNeo documentation for request options.

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

ScreenshotNeo removes cookie/consent banners, newsletter popups and chat widgets before the capture. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed as clean shots, and response headers identify the page verdict and billing result. Its MCP server provides take_screenshot, get_page_info and capture_pdf tools for Claude, Cursor and other MCP clients.

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.

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

Create a free ScreenshotNeo account to get the 1,000 monthly screenshots without adding a card.

Additional client examples

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}`);

Frequently Asked Questions

Are CDP margins measured in CSS pixels?

No. The Page.printToPDF margin fields are inches. Convert your intended physical margin before placing the value in the command.

Should I always set preferCSSPageSize to true?

No. Use true when the document’s CSS @page dimensions should control the sheet; otherwise coordinate explicit CDP paper dimensions and leave it false.

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

Can CSS remove Chrome’s generated URL and page number?

No. Those are browser-generated header/footer elements. Disable them with displayHeaderFooter:false or the corresponding headless setting.

Why does a v124 Selenium example fail in my project?

Selenium DevTools Java APIs are versioned. The method signature and imports must match your Selenium and browser protocol versions.

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.