Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
CSS print

How to Add a Border Around HTML-Generated PDF Pages

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.

Use a print-only, fixed-position frame instead of putting a border on a normal flowing container. Define the paper size and breathing room with @page, reset browser margins, then draw the frame with a fixed pseudo-element. Chromium-based Playwright and Puppeteer workflows generally paint that frame on every printed page, but you should inspect output from the exact browser version you deploy.

The reliable pattern: print geometry plus a fixed frame

A border on body or on a wrapper such as .document belongs to the normal flow. When the wrapper becomes several physical pages, its border is one continuous box: it may appear only at the beginning and end, or its sides may be clipped at a page break. A repeating page border needs to be attached to the printed page rather than to flowing content.

The following CSS establishes A4 pages, leaves a 12 mm margin around the content area, and paints a one-pixel frame on every printed page:

@media print {
  @page {
    size: A4;
    margin: 12mm;
  }

  html,
  body {
    margin: 0;
    padding: 0;
  }

  .pdf-page-frame::before {
    content: "";
    position: fixed;
    inset: 0;
    border: 1px solid #222;
    box-sizing: border-box;
    pointer-events: none;
  }
}

Wrap all printable content in <div class="pdf-page-frame">…</div>. The pseudo-element is fixed to the page viewport, so Chromium print layout can repaint it for each physical page. This is an implementation pattern, not a promise made by every HTML-to-PDF engine; verify page repetition, clipping, and color in your production engine and version.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Epson EcoTank ET-2800 Wireless Color All-in-One Supertank Printer - Black
  • INNOVATIVE CARTRIDGE-FREE PRINTING — No more dealing with lots of tiny ink cartridges; With this wireless document and photo printer each ink bottle set is equivalent to about 90 individual cartridges²
  • LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; When you choose this combination printer, scanner and copier you can print up to 4,500 pages black/7,500 color³
  • COLOR PRINTING — Up to 2 years of ink in the box4 (and with every replacement ink set) for fewer out-of-ink frustrations
  • ZERO CARTRIDGE WASTE — By using an Epson EcoTank printer you can help reduce the amount of cartridge waste ending up in landfills
  • HOME PRINTER DESIGNED FOR RELIABILITY — The Epson EcoTank ET-2800 All-in-One Supertank Color Printer creates vivid, detailed prints and documents thanks to Micro Piezo Heat-Free Technology; Fire off 10 ISO pages per minute1 to easily finish large jobs

A complete HTML document

This self-contained example includes enough content to create multiple pages. The screen stylesheet is deliberately separate from the print stylesheet, so the frame does not appear while someone views the page in a normal browser tab.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Quarterly report</title>
  <style>
    body {
      font-family: system-ui, sans-serif;
      color: #222;
      line-height: 1.45;
    }

    .report {
      max-width: 760px;
      margin: 0 auto;
    }

    h1, h2 { break-after: avoid; }
    table { width: 100%; border-collapse: collapse; }
    th, td { border: 1px solid #bbb; padding: 6px; }

    @media print {
      @page {
        size: A4;
        margin: 12mm;
      }

      html, body {
        margin: 0;
        padding: 0;
      }

      .pdf-page-frame::before {
        content: "";
        position: fixed;
        inset: 0;
        border: 1px solid #222;
        box-sizing: border-box;
        pointer-events: none;
      }

      .report { max-width: none; }
      .no-print { display: none !important; }
    }
  </style>
</head>
<body>
  <div class="pdf-page-frame">
    <main class="report">
      <h1>Quarterly report</h1>
      <p>Your flowing report content goes here.</p>
      <!-- Add enough sections, tables, or paragraphs to span pages. -->
    </main>
  </div>
</body>
</html>

Generate the PDF with Playwright

Playwright’s page.pdf() uses the print CSS media type. Set printBackground: true when the frame or other design depends on painted backgrounds, and set preferCSSPageSize: true when the @page rule should control paper size.

import { chromium } from 'playwright';

const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('http://localhost:3000/report.html', { waitUntil: 'networkidle' });
await page.pdf({
  path: 'report.pdf',
  format: 'A4',
  printBackground: true,
  preferCSSPageSize: true,
  margin: { top: '0', right: '0', bottom: '0', left: '0' }
});
await browser.close();

The zero API margins prevent a second margin from being added outside the CSS geometry. If you instead want the API to decide the paper size and margins, remove preferCSSPageSize and configure those values in the call; do not mix two unrelated margin systems accidentally.

Generate the same PDF with Puppeteer

Puppeteer’s Page.pdf() also renders with print CSS by default and exposes the same core controls:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('http://localhost:3000/report.html', { waitUntil: 'networkidle0' });
  await page.pdf({
    path: 'report.pdf',
    format: 'A4',
    printBackground: true,
    preferCSSPageSize: true,
    margin: { top: '0', right: '0', bottom: '0', left: '0' }
  });
  await browser.close();
})();

Use one geometry owner. If @page says A4 with 12 mm margins while the API supplies a different paper size or nonzero margins, the frame can move toward the edge or content can be pushed unexpectedly.

Control the page box, printable area, and frame position

Choose a paper size and orientation

The size descriptor in @page can be a named size such as A4, or an explicit size such as 210mm 297mm. For landscape output, use size: A4 landscape. Keep the API’s format or width/height consistent unless CSS is explicitly preferred.

Rank #2
Sale
Epson EcoTank Photo ET-8550 Wireless Wide-Format All-in-One Tank Printer
  • CARTRIDGE-FREE PRINTING — Print lab-quality photos, graphics and creative projects; Get vibrant colors and sharp text with Epson's high-accuracy printhead and Claria ET Premium 6-color inks
  • INK BOTTLES — Save on photos1 and creative projects with affordable in-house printing; All-in-one printer allows you to print 4" x 6" photos for about 4 cents each vs. 40 cents with traditional ink cartridges1
  • LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; Printer, scanner and copier lets you print up to 6,200 color pages³
  • PRINT FOR LONGER — Up to 2 years of ink in the box² (and with every replacement ink set) for fewer out-of-ink frustrations with this wireless printer
  • ZERO CARTRIDGE WASTE — Epson EcoTank printer helps reduce the amount of cartridge waste ending up in landfills; Cartridge-free printer uses high-yield ink bottles; Each replacement ink bottle set is equivalent to about 100 individual ink cartridges⁴

Understand what the margin means

CSS paged media defines a page box and a margin area around the page area. The 12 mm margin in the example reserves room between the content layout and the physical edge. The fixed frame uses inset: 0, so its stroke is placed at the edge of the page viewport while content remains inside the reserved margin. If your renderer clips fixed content at the page boundary, increase the reserved margin and test again.

Adjust stroke and color

Change 1px solid #222 to the required width, style, or color. A very thick stroke consumes more edge space; a light gray stroke is less intrusive on office printers. Keep box-sizing: border-box so the border is included inside the pseudo-element’s dimensions.

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

Keep content away from the frame

The frame does not create layout space because it is fixed and has pointer-events: none. The @page margin is what protects headings, tables, and images from touching it. Inspect all four edges, including pages containing unusually wide tables or full-bleed images.

Page breaks, tables, and long documents

Prevent awkward heading breaks

Rules such as break-after: avoid (or the older page-break-after: avoid) help keep a heading with the following paragraph. They do not guarantee that a very large element will fit on one page.

Handle tables deliberately

A table can split across pages. Use repeating table headers where your browser version supports them, and avoid placing a table inside a wrapper whose fixed height forces clipping. Check the first and last rows on every page; the frame itself should remain independent of the table’s flow.

Do not use a fixed-height “page” wrapper for flowing content

A wrapper with a screen-sized height and a normal border often clips or creates an extra blank page when content grows. Let the document flow naturally and reserve page geometry with @page.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
HP Smart Tank 5000 Wireless All-in-One Ink Tank Printer, Scanner, Copier with 2 Years of Ink Included, Best-for-Home, Cartridge-Free, Refillable and AI-Enabled. (5D1B6A)
  • SET IT UP ONCE AND PRINT WITH CONFIDENCE. No complicated maintenance. Just easy, reliable printing you can count on.
  • INK FOR YEARS. NOT MONTHS. Up to 2 years of ink included. Get thousands of pages of cartridge-free printing. More pages, less hassle
  • KEEPS PRINTING WELL AFTER COMPETITORS HAVE QUIT. No complex maintenance. Sharper text, richer colors.[2] Only with HP Smart Tank
  • PREMIUM SUPPORT - Strong technical expertise to solve issues faster
  • THE LAST PRINTER YOU'LL EVER NEED. Enjoy years of refillable, cartridge-free printing.

Backgrounds and transparency

Browser PDF generation may omit background colors and images unless printBackground: true is enabled. The border is a border stroke rather than a background fill, but enabling the option keeps the visual treatment consistent when the design also uses colored panels or a background image.

Diagnose a missing, clipped, or single-page border

  1. Border appears only once: confirm the rule is inside @media print and that the frame pseudo-element is position: fixed, not absolute or part of normal flow.
  2. Border is absent in the PDF: verify the generated document includes the pdf-page-frame wrapper, then check that your selector is not overridden by a more specific print rule. Reload the page after changing CSS before generating again.
  3. Border is clipped at the edge: remove default html and body margins, keep the frame at inset: 0, and reserve a positive @page margin. If clipping persists, test a slightly larger margin and inspect the renderer’s page-box behavior.
  4. Content touches or crosses the line: increase the @page margin. Do not add arbitrary padding to every paragraph; that changes the document’s internal rhythm rather than the page geometry.
  5. Colors or panels disappear: enable printBackground: true in the PDF call and check whether the page is being rendered with print media.
  6. Output size is wrong: decide whether CSS or the API owns paper size. With CSS ownership, use preferCSSPageSize: true and avoid conflicting API margins. With API ownership, remove or align the conflicting @page dimensions.
  7. Only the production server fails: compare the browser engine and version, loaded fonts, viewport, and wait condition with local generation. A late-loading font or image can change page breaks even when the border CSS is unchanged.
  8. Different pages behave differently: inspect pages containing long tables, replaced elements, floats, or explicit break rules. Fixed-frame painting is separate from flow pagination, but engine changes can affect both.

Make output reproducible in production

  • Pin the Playwright or Puppeteer browser version used by your build or container.
  • Wait for the document’s real readiness condition, such as network idle plus a specific application-loaded selector, before calling pdf().
  • Use deterministic fonts and load them before capture; fallback metrics can move a paragraph to the next page.
  • Keep CSS and API paper-size settings in one documented place.
  • Store representative PDFs in visual regression tests: a one-page document, a multi-page document, a table split, and content close to each edge.
  • Open the resulting PDF with a viewer that shows page boundaries and zoom to 100% before changing the stroke width or margins.

Or skip the browser setup

ScreenshotNeo provides a website screenshot API and MCP server for developers. A single request can capture a publicly reachable HTML report without maintaining Playwright or Puppeteer. Its cleanup step accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; 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. The MCP server exposes take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

For the HTTP example and parameter reference, see the ScreenshotNeo documentation:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com/report.html -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://example.com/report.html"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com/report.html' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

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

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

FAQ

Will the frame work in every HTML-to-PDF engine?

No. The fixed pseudo-element pattern is intended for Chromium-based print rendering. Engines with different paged-media implementations can paint fixed elements differently, so validate the exact engine and version that produces your PDFs.

Can I put different text or a logo in the frame?

Yes. Add generated content or another fixed child inside the frame, but test overlap with page margins and confirm that the element repeats and remains legible on every page.

How can I make a border on only selected pages?

A single fixed frame naturally repeats on all pages. Selective pages require page-specific markup or engine features beyond this basic pattern; test the resulting page breaks rather than assuming a normal-flow class will map to physical pages.

Rank #4
NDYIN Portable Printers Wireless for Travel, N80 Bluetooth Thermal Printer
  • Wireless Bluetooth Printer: Portable thermal printer compatible with iPhone, Android phones, iPad and tablet computers via Bluetooth. For smartphones, please download the "Nada Print" App. You can also connect to laptops and computers for printing using a USB-C cable. (Note: Laptops and computers can only be connected via USB and require the installation of a driver first. Bluetooth connection is not supported.)
  • No-ink printing: Only supports US Letter and A4 size thermal paper.(Doesn't support regular paper) The no-ink portable thermal printer uses direct thermal technology, requiring no ink, toner or ribbons, making it environmentally friendly, cost-effective and time-saving. The thermal printer package comes with a roll of US Letter thermal printing paper. Note: When installing the paper, remember to switch the paper size switch on APP
  • Clear Print: NDYIN N80 portable thermal printer adopts high-definition printing technology, with a 203DPI resolution to provide you with clear printing results. This mobile printer is compatible with roll paper, folded paper and tattoo transfer paper, supporting printing from your mobile phone PDF, Word, pictures and web pages anytime and anywhere. It is recommended to use our NDYIN thermal paper to achieve good printing quality
  • Portable wireless printer for travel: The thermal printer is equipped with a built-in 1500mAh rechargeable battery, which can print 160 sheets of 8.5" x 11" thermal paper after being fully charged. It weighs only 1.5 pounds and is compact in size. This ink-free portable printer can be easily carried in a backpack or briefcase! It is perfect for business travel, cars, small offices, construction sites, schools and homes. You can print documents, contracts, invoices and boarding passes anytime and anywhere
  • The N80 thermal printer has a wide range of uses. The package includes the N80 printer, a roll of US Letter paper(7m/roll), a user manual, a guide card, a type-C soft cable and a type C adapter. Note: The charging adapter is not included. Special thermal paper is required for use; ordinary paper cannot be used. This ink-free portable thermal printer is suitable for various scenarios such as home, school, travel, office, and outdoor, meeting the printing needs of different groups of people. This tattoo template printer is also compatible with tattoo transfer paper, making it an ideal choice for tattoo art

Why does a border look thicker in some PDF viewers?

Viewer zoom, device-pixel scaling, and anti-aliasing can change the on-screen appearance of a one-pixel stroke. Judge the printed or exported result at its intended scale and keep the CSS width explicit.

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

Frequently Asked Questions

Will the frame work in every HTML-to-PDF engine?

No. The fixed pseudo-element pattern is intended for Chromium-based print rendering. Engines with different paged-media implementations can paint fixed elements differently, so validate the exact engine and version that produces your PDFs.

Can I put different text or a logo in the frame?

Yes. Add generated content or another fixed child inside the frame, but test overlap with page margins and confirm that the element repeats and remains legible on every page.

How can I make a border on only selected pages?

A single fixed frame naturally repeats on all pages. Selective pages require page-specific markup or engine features beyond this basic pattern; test the resulting page breaks rather than assuming a normal-flow class will map to physical pages.

Why does a border look thicker in some PDF viewers?

Viewer zoom, device-pixel scaling, and anti-aliasing can change the on-screen appearance of a one-pixel stroke. Judge the printed or exported result at its intended scale and keep the CSS width explicit.

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

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.

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
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver 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.