October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
CSS

How to Add a Screenshot to a PDF With HTML and CSS (Puppeteer Guide)

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

Direct answer: put the screenshot in your HTML with an <img> element, size it with CSS, then render the page with a browser PDF engine such as Puppeteer. Add print-specific CSS, wait until images and fonts are ready, and call page.pdf(). Puppeteer uses the print media type by default; call page.emulateMediaType('screen') when the PDF must use screen styles instead.

1. Prepare the screenshot asset

Obtain a PNG, JPEG, or WebP image and make it reachable by the page that Chromium will render. You can use a file path, an HTTP(S) URL, or a data URL. A local file is convenient for a script that runs on your own machine; a hosted URL is useful in a service; a data URL makes the document self-contained but can make the HTML very large.

Use meaningful alternative text even when the PDF is primarily visual. It helps screen readers and provides a useful fallback if the image cannot load.

<img src="screenshot.png" alt="Checkout page showing the order confirmation">

Keep the original aspect ratio. The safest baseline rule is:

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
img.screenshot {
  display: block;
  max-width: 100%;
  height: auto;
}

max-width:100% prevents a wide capture from extending beyond its containing block, while height:auto avoids distortion. If the screenshot must have a fixed display width, set only the width and leave the height automatic.

2. Build an HTML document that prints cleanly

Place the image in normal document flow and reserve room for the surrounding title, caption, and notes. The following complete document is suitable for a one-page report or as a template for longer PDFs.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Screenshot report</title>
  <style>
    @page {
      size: A4;
      margin: 18mm;
    }
    * { box-sizing: border-box; }
    body {
      margin: 0;
      color: #1f2937;
      background: #ffffff;
      font: 14px/1.5 Arial, sans-serif;
    }
    h1 { margin: 0 0 8mm; font-size: 24px; }
    figure { margin: 0; }
    .screenshot {
      display: block;
      max-width: 100%;
      height: auto;
      border: 1px solid #d1d5db;
    }
    figcaption {
      margin-top: 3mm;
      color: #4b5563;
      font-size: 12px;
    }
    .notes { margin-top: 8mm; }
    .avoid-break { break-inside: avoid; page-break-inside: avoid; }
    @media print {
      .screen-only { display: none !important; }
    }
  </style>
</head>
<body>
  <h1>Checkout screenshot</h1>
  <figure class="avoid-break">
    <img class="screenshot" src="screenshot.png"
         alt="Checkout page showing the order confirmation"
         onerror="this.alt='Screenshot could not be loaded';">
    <figcaption>Captured 29 September 2026.</figcaption>
  </figure>
  <section class="notes">
    <h2>Notes</h2>
    <p>The image above is included as ordinary HTML content.</p>
  </section>
</body>
</html>

3. Render the HTML with Puppeteer

Install Puppeteer in a Node.js project, then load the HTML and write a PDF. Use a file URL for local assets, or replace it with your application URL.

npm install puppeteer
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({headless: true});
  try {
    const page = await browser.newPage();
    await page.goto('file:///absolute/path/to/report.html', {
      waitUntil: 'networkidle0'
    });

    await page.evaluate(async () => {
      await document.fonts.ready;
      const images = Array.from(document.images);
      await Promise.all(images.map(img => {
        if (img.complete) return img.decode ? img.decode().catch(() => {}) : Promise.resolve();
        return new Promise(resolve => {
          img.addEventListener('load', resolve, {once: true});
          img.addEventListener('error', resolve, {once: true});
        });
      }));
    });

    await page.pdf({
      path: 'report.pdf',
      format: 'A4',
      printBackground: true,
      margin: {top: '18mm', right: '18mm', bottom: '18mm', left: '18mm'},
      preferCSSPageSize: true,
      waitForFonts: true
    });
  } finally {
    await browser.close();
  }
})();

The PDF call generates with the print CSS media type by default. If your design is written for the screen and should be reused unchanged, set the media type before exporting:

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 #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)
await page.emulateMediaType('screen');
await page.pdf({path: 'screen-styled.pdf', printBackground: true});

Choose one strategy deliberately. Print CSS is generally easier to make predictable on paper; screen emulation preserves screen-oriented rules but may require more explicit sizing.

4. Control page size, margins, and orientation

PDF geometry is controlled by Puppeteer options and, when enabled, your CSS @page rule. Decide whether CSS or JavaScript owns the final size. With preferCSSPageSize:true, a declared @page size takes precedence; otherwise the format, width, and height options determine the sheet.

Requirement Setting Practical effect
Paper preset format: 'A4' or another supported format Uses a named paper size.
Custom paper width and height Sets explicit dimensions.
Landscape page landscape: true Swaps the orientation for wide screenshots.
Whitespace around content margin Reserves printable margins.
CSS-defined paper preferCSSPageSize: true Lets @page size control the PDF.
Colored backgrounds printBackground: true Includes CSS background graphics.
Selected pages pageRanges: '1-2' Exports only the requested range.
Overall scaling scale Scales rendered content; test it with margins.

For a landscape screenshot, combine a landscape PDF with a responsive image rule:

@page { size: A4 landscape; margin: 12mm; }
@media print {
  .screenshot { max-height: 170mm; width: auto; }
}

Do not set both a fixed width and fixed height on the image unless cropping or distortion is intentional. If the image is taller than the remaining page, let it flow naturally or split the report into sections.

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

5. Prevent clipping, unwanted breaks, and missing colors

Keep the screenshot inside the printable area

The usable width is paper width minus left and right margins. A screenshot wider than that area may be scaled down, overflow, or appear clipped depending on its container. Apply max-width:100% to the image and to any parent that could impose a larger fixed width. Remove large screen-only padding in print media.

Keep a figure together when possible

Use break-inside:avoid (and its older page-break-inside counterpart) on the figure. This is a request, not an absolute guarantee: a figure taller than one page must still be split or moved.

Print backgrounds and exact colors

Puppeteer does not include background graphics unless printBackground:true is set. Chromium can also modify colors for printing. Add this declaration when exact screen colors matter:

html {
  -webkit-print-color-adjust: exact;
  print-color-adjust: exact;
}

Color management still depends on the viewer and printer. Treat this as preserving the browser render, not as a guarantee that every physical printer will reproduce the same color.

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

Hide controls that belong only on screen

Put navigation, buttons, and debugging overlays in elements with a class such as screen-only, then hide them in @media print. Conversely, add a print-only class for captions or legal text that should appear only in the PDF.

6. Make assets and fonts ready before export

A successful page.goto() does not prove that every image has decoded or that web fonts are usable. Wait for the page’s network to become idle, then explicitly wait for document.fonts.ready and each image. The example script resolves failed images so the export completes; in a production pipeline you may instead reject the job when a required image fires error.

For remote images, configure the server to allow the request and ensure the URL is valid from the machine running Chromium. For local files, use an absolute file URL and confirm the process has permission to read both the HTML and image. Embedding a data URL removes a separate network request but increases HTML size and memory use.

7. Common failures and fixes

The PDF has a blank image area

  • Check the image URL in the same environment that launches Chromium.
  • Wait for image load and decoding before calling page.pdf().
  • Inspect the browser console and network responses for authentication, CORS, or 404 errors.

The screenshot is cut off on the right

  • Remove fixed widths from the image or its parent.
  • Use max-width:100%; height:auto.
  • Reduce margins, choose landscape orientation, or use a smaller image display width.

Colors or backgrounds disappeared

  • Set printBackground:true.
  • Use -webkit-print-color-adjust:exact for color fidelity.
  • Verify that the rule is inside the active print or screen media context.

The PDF looks different from the browser

  • Remember that PDF generation uses print media by default.
  • Call page.emulateMediaType('screen') if screen CSS is required.
  • Compare the same viewport, fonts, and loaded assets before changing layout rules.

Text overlaps or the page count changes between runs

  • Wait for fonts; fallback fonts can have different metrics.
  • Avoid timing-dependent JavaScript that changes content after network idle.
  • Use explicit margins and page-break rules around large figures.

A local file works interactively but not in deployment

  • Use a path that exists inside the deployment environment, not only on your workstation.
  • Prefer an application-served asset or a data URL when filesystem layout is uncertain.
  • Check Chromium sandbox and file-permission settings in the runtime.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

8. Performance, reliability, and cost choices

Local Puppeteer gives you control over Chromium version, CSS, network access, and data handling, but you operate browser processes and must manage concurrency, memory, fonts, and failed navigations. Reuse a browser process where appropriate, create isolated pages for jobs, and close pages after export. Set navigation and job timeouts so a stalled site does not consume a worker indefinitely.

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

For repeated exports, cache stable assets and avoid downloading a full page when the screenshot is already local. For large captures, consider a lower image display width or an appropriately compressed source; PDF size is affected by the embedded image dimensions and encoding. Test representative long pages, slow networks, missing assets, and pages with consent dialogs before treating a template as production-ready.

9. Or skip the browser setup

ScreenshotNeo provides a hosted screenshot API and MCP server. A single request captures a URL as PNG, JPEG, WebP, or PDF, so you can obtain the image first and place it in the HTML workflow above without maintaining Chromium. Cookie and consent banners, newsletter popups, and chat widgets are removed before capture. Bot checks, 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.

Use the API documentation for all options: https://screenshotneo.com/docs/.

cURL

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

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

ScreenshotNeo has 63 options, including full-page captures with lazy images loaded, CSS-selector element capture, device presets and custom viewports, dark mode, retina scale, PDF paper and page-range controls, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, selectable-TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, a usage API, and an OpenAPI specification. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

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, and yearly billing provides two months free. Sign up for the free plan to get the 1,000 monthly screenshots without a card.

10. A practical preflight checklist

  • The screenshot URL or file path works in the rendering environment.
  • The image has useful alt text and preserves its aspect ratio.
  • max-width:100%; height:auto prevents overflow.
  • Print margins, paper size, orientation, and CSS @page precedence are intentional.
  • Fonts and images are ready before page.pdf().
  • printBackground:true is enabled when backgrounds matter.
  • You selected print media or screen media deliberately.
  • Long images, page breaks, missing assets, and slow requests have been tested.

Frequently Asked Questions

Can I use a WebP screenshot in a PDF?

Yes. Chromium can decode WebP for an HTML image; verify the deployed browser version and wait for the image to finish decoding before export.

Should I embed the image as a data URL?

Use a data URL when a self-contained HTML document is more important than compact size. Otherwise, a local or hosted asset is usually easier to maintain.

Can one screenshot span multiple PDF pages?

Yes, if it is taller than the printable area, but page-break avoidance cannot keep an oversized figure on one sheet. Consider scaling it, using landscape orientation, or splitting the content intentionally.

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.