Blog

Print CSS Cheatsheet: HTML & CSS Tips for Better PDFs

Creating print-ready documents is essential when exporting HTML to PDF. This print CSS cheatsheet will help you apply the right styles for clean, professional, and well-structured print layouts. Below are CSS print tips, including @media print examples and common page-break CSS examples.



1. Use Page Breaks

By default, web browsers determine where content breaks across pages whenever a document is printed or exported as a PDF. This behavior often leads to awkward situations where text paragraphs, images, or tables are split halfway between pages. While this might not be a big deal for casual documents, in professional layouts such as invoices, contracts, eBooks, or reports, poorly placed page breaks can make your document look unpolished and confusing to readers.

To solve this problem, CSS provides properties like page-break-before, page-break-after, and page-break-inside. These allow you to explicitly control where a new page begins, where a page should end, and whether an element can be broken across two pages. The most commonly used one is page-break-before, which forces the following element to always start on a new page. This gives you complete control over the structure of your PDF layout and helps you create documents that look more like professionally typeset material.

HTML Input

PDF Output

The generated PDF will be displayed here.


In this example, the invoice header is always kept on the first page. The list of products starts on a completely new page, and finally, the notes section also begins on its own page. This kind of control is especially important when dealing with financial records, where information must not be split across pages for clarity and legal reasons.

Why Page Breaks Matter

Imagine you are generating a PDF contract. Without page break rules, the signature section might appear half on one page and half on the next. This not only looks unprofessional but also makes the document harder to sign or review. Similarly, in an academic report, a long table might be cut into two, separating column headers from their data rows. Readers then need to flip back and forth, which can be frustrating. Proper use of page breaks eliminates such problems by allowing you to declare where important sections must start.

Common Use Cases

  • Invoices and Bills: Start the product list, payment summary, and notes on new pages for clarity.
  • Reports and Whitepapers: Begin each chapter or section on a fresh page for a book-like flow.
  • Certificates: Prevent certificates from being split when batch-printing PDFs for multiple people.
  • Legal Documents: Ensure signature blocks always stay together and are not cut across pages.
  • Resumes/Portfolios: Keep project descriptions or tables intact without breaking across pages.

Alternative Properties

While page-break-before is widely used, it is often combined with other related properties for finer control:

  • page-break-after: always; – Forces a page break immediately after the element.
  • page-break-inside: avoid; – Prevents splitting the element across pages (useful for tables or images).
  • break-before, break-after, and break-inside – Newer CSS standards that replace the older page-break-* rules but work similarly in modern browsers.

Browser and Library Support

It’s important to note that page-break behavior can vary depending on the rendering engine. For example, Chrome and Chromium-based browsers (including headless Chrome with Puppeteer) support page-break-before quite well. Firefox also provides good support, though subtle differences exist. If you are using dedicated HTML-to-PDF libraries like wkhtmltopdf, PrinceXML, or WeasyPrint, they typically implement page-break rules more consistently. Always test your output across multiple engines if your document must be pixel-perfect.

Practical Example with Chapters

<div class="chapter">
  <h1>Chapter 1: Introduction</h1>
  <p>This is the introduction to the book...</p>
</div>

<div class="page-break"></div>

<div class="chapter">
  <h1>Chapter 2: Background</h1>
  <p>This section explains the background...</p>
</div>

In this case, each chapter of a book or report is guaranteed to start on a new page. Without these rules, browsers might cram multiple chapters on the same page, making the PDF harder to read and reducing its professional appeal.

Best Practices

  • Always test the final PDF by exporting from different browsers.
  • Avoid excessive page breaks – only use them for logical divisions (chapters, sections, signatures).
  • Combine with @media print styles to hide unnecessary elements like navigation or buttons before export.
  • For long tables, combine page-break-inside: avoid with repeated table headers for readability.
  • Use semantic structure (headings, sections) so that page breaks feel natural, not forced.

In summary, page breaks are not just a minor formatting tweak; they are a powerful way to transform an ordinary exported PDF into a clean, professional document. Whether you are designing invoices, preparing research papers, or publishing an eBook, controlling where the content breaks is essential to readability, professionalism, and overall user experience. By mastering page-break-before and its related properties, you can take full control over your PDF layouts and avoid the frustration of awkward, automatically generated breaks.


2. Custom Fonts for Branding

Custom fonts are essential for maintaining brand consistency across all your documents. Whether you're creating invoices, reports, or marketing materials, using your brand's typography creates a professional, unified appearance that reinforces your identity. With CustomJS, you can easily embed custom fonts in your PDFs without worrying about compatibility issues.

CustomJS is built on an optimized Chrome Headless engine specifically configured to handle custom fonts reliably. Unlike standard browser-based PDF exports that often fail to embed fonts properly, CustomJS automatically detects and embeds both Google Fonts and self-hosted fonts, ensuring your PDFs look exactly as designed.

How CustomJS Handles Custom Fonts

CustomJS is built on Chrome Headless technology but with critical optimizations for font handling:

  • Automatic font detection and embedding — No manual configuration needed
  • Google Fonts support — Just use @import and CustomJS handles the rest
  • Self-hosted fonts — Works with @font-face declarations using URLs or base64
  • Smart font loading — Waits for fonts to fully load before rendering the PDF
  • WOFF, WOFF2, TTF, and OTF support — All modern font formats work seamlessly

Example 1: Google Fonts with CustomJS

The easiest way to use custom fonts is with Google Fonts. Simply import them in your CSS, and CustomJS will embed them automatically:

HTML Input

PDF Output

The generated PDF will be displayed here.


This example uses Google Fonts (Roboto and Playfair Display) with proper fallbacks. When you generate the PDF using CustomJS, both fonts are automatically embedded, maintaining your design perfectly. The font-display: block parameter ensures fonts are fully loaded before rendering.

Example 2: Brand Fonts for Corporate Documents

If your company has custom brand fonts (often purchased from foundries or designed internally), you can host them yourself and use @font-face:

HTML Input

PDF Output

The generated PDF will be displayed here.


This invoice example demonstrates how a custom brand font creates a cohesive, professional look. CustomJS automatically detects and embeds the font files, ensuring every PDF matches your brand guidelines exactly.

Example 3: Multiple Font Weights for Complex Documents

Professional documents often need various font weights (light, regular, bold, black) for proper typographic hierarchy:

HTML Input

PDF Output

The generated PDF will be displayed here.


This report demonstrates using multiple weights of the same font family. CustomJS handles all font variants seamlessly, giving you complete typographic control in your PDFs.

Why CustomJS Works Better for Custom Fonts

  • No manual font loading delays: CustomJS automatically waits for fonts to load
  • No CORS issues: Our infrastructure handles cross-origin font requests properly
  • Automatic subsetting: Reduces PDF file size by embedding only used characters
  • Fallback handling: Gracefully handles font loading failures without breaking your PDF
  • Consistent rendering: Same output every time, regardless of client environment

Best Practices When Using Custom Fonts

/* âś… RECOMMENDED: Google Fonts with display=block */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=block');

/* âś… RECOMMENDED: Self-hosted fonts with ABSOLUTE URLs */
@font-face {
  font-family: 'BrandFont';
  /* âś… Use absolute URLs - relative paths like /fonts/... won't work */
  src: url('https://yourdomain.com/fonts/brand-regular.woff2') format('woff2');
  font-weight: 400;
  font-display: block;
}

/* ❌ AVOID: Relative paths don't work with CustomJS */
@font-face {
  font-family: 'BrandFont';
  src: url('/fonts/brand.woff2') format('woff2'); /* This will fail! */
}

/* âś… ALWAYS include fallback chain */
body {
  font-family: 'Inter', 'BrandFont', -apple-system, system-ui, sans-serif;
}

/* âś… Specify font weights explicitly */
h1 { font-weight: 700; }
h2 { font-weight: 600; }
p { font-weight: 400; }

Important: CustomJS requires absolute URLs (starting with https://) for self-hosted fonts. Relative paths like /fonts/custom.woff2 will not work. Either use a CDN, Google Fonts, or host your fonts on a publicly accessible URL.

Font Sizes and Readability

Beyond choosing the right typeface, you must also use print-appropriate sizes. What looks fine on a screen at 14px may be too small or too large on paper. For PDFs:

  • Body text: 10pt–12pt (depending on typeface).
  • Headings: 14pt–18pt for hierarchy and clarity.
  • Captions/footnotes: 8pt–9pt, but ensure they remain legible.

Typography Best Practices for Print PDFs

  • Use a maximum of two or three fonts in a document (e.g., one for body, one for headings, one monospace for code).
  • Maintain consistent line spacing (line-height) for a clean, balanced look.
  • Justify text only when necessary; left-aligned text is generally more readable in digital and printed formats.
  • Avoid using light or ultra-thin font weights, which may disappear when printed.
  • Check contrast: ensure font color against background is dark enough for readability.

Example: Report Styling

body {
  font-family: Georgia, serif;
  font-size: 12pt;
  line-height: 1.6;
  color: #333;
}

h1, h2, h3 {
  font-family: Arial, sans-serif;
  font-weight: bold;
  color: #111;
}

code, pre {
  font-family: "Courier New", monospace;
  font-size: 10pt;
  background: #f5f5f5;
  padding: 4px;
}

This setup ensures that body paragraphs are elegant and book-like (using Georgia), headings stand out with a clean sans-serif (Arial), and code snippets align perfectly with monospace.

Testing Fonts Before Finalizing

Always generate test PDFs and open them on different devices and printers. What looks perfect on your development machine might render differently on macOS, Windows, or Linux. Printers, too, can sometimes substitute fonts without warning. Testing early ensures your chosen fonts hold up in real-world scenarios.

In conclusion, while fonts might seem like a small detail, they are a foundation of professional PDF design. Choosing print-friendly fonts ensures consistency, readability, and credibility in your documents. Whether you’re producing business invoices, research papers, or product catalogs, always prioritize clarity and compatibility over flashy design choices. By relying on trusted system fonts and following best practices, you can create PDFs that look polished and are guaranteed to render correctly everywhere.


3. Hide Unnecessary Elements

When exporting a webpage to PDF, not everything visible on the screen should appear in the printed document. Elements such as navigation menus, buttons, advertisements, sidebars, or even interactive widgets may serve a purpose on the web, but they can clutter and distract in a print context. A professional-looking PDF should focus on the main content while removing unnecessary extras. The best way to achieve this is by using @media print styles in CSS. This allows you to keep those elements for on-screen users, while hiding or modifying them during print or PDF export.

HTML Input

PDF Output

The generated PDF will be displayed here.


In this example, the "Download PDF" button is useful when someone is browsing the page online, but it becomes irrelevant (and visually distracting) once the document is saved as a PDF. Thanks to @media print, the button automatically disappears in the print version, leaving only the meaningful invoice content.

Why Hiding Elements Matters

If you’ve ever printed a webpage without customization, you’ve probably noticed clutter—navigation bars at the top, side menus on the left, cookie banners, or even ads getting in the way of the actual content. This makes the PDF look messy, wastes space, and can even cause important sections of the document to break across pages. By hiding elements that are irrelevant to print, you produce a cleaner, more professional document that focuses only on the core information.

Common Elements to Hide

  • Navigation bars: Useful for web browsing but unnecessary in a PDF report.
  • Buttons and links: "Download," "Share," or "Submit" buttons don’t belong in print.
  • Advertisements: Print documents should never include banner ads or popups.
  • Interactive widgets: Chat boxes, sliders, or carousels don’t translate to PDF.
  • Sidebars: Secondary content or recommendations should often be hidden to keep focus on the main material.
  • Footers with navigation: While legal or contact info may be useful, website footers with menus can be removed.

More Advanced Print Rules

@media print {
  /* Hide unnecessary UI */
  nav, footer, .sidebar, .ad-banner, .btn {
    display: none !important;
  }

  /* Make text more readable */
  body {
    font-size: 12pt;
    line-height: 1.6;
    color: #000; /* Ensure good contrast */
  }

  /* Adjust background colors for print */
  .highlight {
    background: #eee; 
    color: #000;
  }

  /* Force full-width tables in PDF */
  table {
    width: 100% !important;
    border-collapse: collapse;
  }
}

This example shows how you can both hide unnecessary elements and optimize visible elements at the same time. The nav, footer, and ads are removed, while the text and tables are reformatted for better readability in print.

Use Cases in Real Projects

  • Invoices: Hide “Download,” “Pay Now,” and navigation links so the PDF looks like a formal billing statement.
  • Reports: Remove company dashboards, filters, or interactive widgets while keeping charts and tables.
  • Certificates: Eliminate all navigation and UI so only the certificate design and recipient’s name appear.
  • Legal Documents: Hide disclaimers, cookie banners, or top bars that could distract from the content.
  • eBooks: Remove related links or ads that make sense on the web but disrupt flow in a print/PDF format.

Conditional Visibility with Classes

@media screen {
  .print-only { display: none; }
}

@media print {
  .no-print { display: none !important; }
  .print-only { display: block; }
}
<div>
  <nav class="no-print"> ...navigation... </nav>

  <h1>Quarterly Report</h1>
  <p>Main report content goes here.</p>

  <footer class="print-only">
    Confidential – For Internal Use Only
  </footer>
</div>

In this setup, the navigation bar is visible on the web but hidden when printing. The “Confidential” footer is invisible online but automatically appears in the PDF. This is extremely useful when you need to add watermarks, disclaimers, or page notes specifically for printed/exported versions.

Best Practices

  • Use @media print rules to hide ads, buttons, and UI clutter.
  • Never hide core content—only remove what is irrelevant to print.
  • Use .print-only classes for elements that should appear exclusively in PDFs.
  • Ensure legibility by adjusting font sizes, line heights, and colors for print.
  • Test multiple browsers (Chrome, Firefox, Edge) since print styles may render differently.

In short, print-optimized PDFs should be free of distractions. By carefully hiding unnecessary elements while preserving the core message, you ensure that your exported documents look professional, concise, and reader-friendly. This small step greatly improves the usability of your PDFs, making them feel like intentionally designed print products rather than raw exports of a website.


4. Define Consistent Margins

When printing or exporting to PDF, one of the most overlooked details is page margins. On the web, content flows freely within the browser window, and users can scroll infinitely. But when you move to print or PDF formats, the page has strict physical boundaries — usually based on paper sizes such as A4 or Letter. If you don’t define margins explicitly, browsers will apply their own defaults, which may lead to inconsistent spacing, clipped content near the edges, or documents that feel cramped and unprofessional.

To solve this, CSS provides the @page rule. This lets you set standardized margins across every page of the printed document or exported PDF. Not only does it improve readability, but it also ensures your document has a polished, intentional look.

<style>
  @page { 
    margin: 1in; 
  }
</style>

<div>
  <h2>Report with Margins</h2>
  <p>This content will print with consistent 1-inch margins around every page.</p>
</div>

In this example, all printed pages will have a 1-inch margin on every side. This prevents text or tables from running too close to the page edges and ensures that no important content gets cut off by a printer’s non-printable area.

Why Margins Matter

  • Printer safety: Many printers cannot print edge-to-edge. Without margins, text or graphics may be cut off.
  • Readability: White space around the content gives the eye breathing room, improving readability and comprehension.
  • Professional look: Reports, contracts, and invoices look more polished with uniform margins.
  • Binding: If documents are stapled or bound, extra margin space prevents text from being hidden in the fold.
  • Consistency: Standardized margins make multipage PDFs look unified rather than uneven or misaligned.

Customizing Margins with @page

The @page rule is flexible — you can define margins for all pages or target specific ones (like the first page or left/right pages in a booklet). Here are some examples:

/* Standard margins on all pages */
@page {
  margin: 1in;
}

/* Different margin for the first pge */
@page :first {
  margin: 2in; /* extra space for cover page */
}

/* Different margins for left and right pages (useful for books) */
@page :left {
  margin-left: 1.5in;
  margin-right: 1in;
}

@page :right {
  margin-left: 1in;
  margin-right: 1.5in;
}

These rules allow you to create professional layouts for reports, eBooks, or bound documents where left and right pages need mirrored margins.

Use Cases

  • Invoices: A standard 1-inch margin ensures the client’s printer won’t trim payment details.
  • Reports: Adding wider top margins on the first page can leave room for a title or cover design.
  • eBooks: Alternating left/right margins create professional layouts for printing as booklets.
  • Legal documents: Consistent margins ensure compliance with formatting standards in many jurisdictions.
  • Presentations: Handout PDFs benefit from extra margins so notes can be written in the whitespace.

Best Practices

  • Stick to 1 inch (2.54 cm) as a safe margin for most business documents.
  • For booklets, use mirrored left/right margins to account for binding space.
  • For cover pages or title pages, add extra top margins for visual balance.
  • Avoid margins that are too narrow (under 0.5 in) unless you know the printer supports borderless printing.
  • Combine @page margins with padding on inner elements for layered whitespace control.

Advanced Example: Report Layout

HTML Input

PDF Output

The generated PDF will be displayed here.


In this setup, the cover page has extra space at the top for the report title, while subsequent pages use normal margins. Each chapter starts on a new page, giving the document a polished, print-ready structure.

Key Takeaway

Margins define the breathing room of your document. By explicitly setting them with @page, you avoid unpredictable browser defaults, prevent content clipping, and produce PDFs that feel professional and well-structured. Whether you’re creating invoices, academic papers, or books, consistent margins are the foundation of a high-quality print layout.


5. Responsive Layout

On the web, users view your content on a variety of devices: desktops, tablets, and mobile phones. Likewise, when exporting to PDF, the page may not have the same proportions as a browser window. A rigid, fixed layout can cause columns to overlap or tables to break awkwardly when scaled down. By designing with responsive layouts — using Flexbox or CSS Grid — you ensure that your content adapts smoothly both on screen and in print/PDF format.

Responsiveness in print means that your multi-column designs, sidebars, and tables automatically adjust to the width of the paper, ensuring that nothing gets cut off and everything remains readable. This approach also reduces the need to manually create separate layouts for digital and print.

HTML Input

PDF Output

The generated PDF will be displayed here.


In this example, the layout uses Flexbox for side-by-side columns on screen. But when exporting to PDF (via @media print), the columns stack vertically, ensuring that text remains legible and avoids being squeezed into narrow spaces. Borders are also removed in print for a cleaner, professional look.

Why Responsive Layouts Matter in PDFs

  • Readability: Prevents text from being squished into tight columns when printed on smaller page sizes.
  • Flexibility: Works across different paper formats (A4, Letter, Legal) without breaking the design.
  • Consistency: Ensures a unified look whether viewed on a large monitor, mobile phone, or in a printed report.
  • Professionalism: Clean, well-spaced layouts look intentional and polished in business documents.

Using CSS Grid for Complex Layouts

/* On-screen grid with two columns */
.layout {
  display: grid;
  grid-template-columns: 2fr 1fr; /* main content + sidebar */
  gap: 20px;
}

/* Print-friendly adjustment */
@media print {
  .layout {
    grid-template-columns: 1fr; /* stack all content */
  }
}
<div class="layout">
  <div class="main">
    <h2>Main Report Content</h2>
    <p>Detailed analysis, charts, and explanations.</p>
  </div>
  <div class="sidebar">
    <h3>Key Highlights</h3>
    <ul>
      <li>Revenue growth: +15%</li>
      <li>Customer base: +8%</li>
    </ul>
  </div>
</div>

On screen, the content and sidebar appear side by side. In print, the sidebar flows below the main content, preventing awkward spacing and ensuring the PDF maintains a logical reading order.

Use Cases

  • Business Reports: Side-by-side comparisons can collapse into stacked layouts for smaller paper sizes.
  • Invoices: Itemized tables can reformat for legibility in print.
  • Certificates: Decorative sidebars or seals can reposition below main content in print mode.
  • eBooks: Two-column layouts become single-column for smoother reading on printed pages.
  • Dashboards: Charts and widgets can reorganize for clarity in exported PDFs.

Best Practices

  • Always use flex-wrap or grid-template-columns to prevent overflow in print.
  • Define @media print rules to adjust layouts specifically for PDFs.
  • Avoid fixed pixel widths — use percentages or fr units for flexibility.
  • Stack columns vertically in print for readability, especially when text-heavy.
  • Test layouts on different browsers and page sizes to ensure consistency.

Advanced Example: Two-Column Report

<style>
  .report-layout {
    display: flex;
    gap: 20px;
  }
  .report-layout .col {
    flex: 1;
    padding: 15px;
    border: 1px solid #ddd;
  }

  @media print {
    .report-layout {
      flex-direction: column; /* stack for PDF */
    }
    .report-layout .col {
      border: none; /* cleaner look */
      padding: 10px 0;
    }
  }
</style>

<div class="report-layout">
  <div class="col">
    <h2>Financial Overview</h2>
    <p>Revenue, expenses, and net profit for the quarter.</p>
  </div>
  <div class="col">
    <h2>Key Metrics</h2>
    <ul>
      <li>Gross Margin: 45%</li>
      <li>Operating Expenses: $2.1M</li>
    </ul>
  </div>
</div>

On screen, both columns appear side by side for quick comparison. In print, the content stacks vertically, ensuring that no data feels cramped or gets pushed to the page edges.

Key Takeaway

Responsive layouts are not just for mobile devices — they are equally important for print and PDF exports. By leveraging Flexbox or CSS Grid with thoughtful @media print adjustments, you ensure that your documents look good everywhere: on screen, on paper, and in exported digital formats. This adaptability makes your PDFs professional, user-friendly, and future-proof.

Related Articles

Continue reading on similar topics

HTML to PDF API: CustomJS vs Alternatives
·Comparison

HTML to PDF API: CustomJS vs Alternatives

Compare HTML to PDF conversion APIs for price, speed, and JavaScript support. CustomJS offers 600 free PDFs/month and easy Make.com integration.

pdfhtml-to-pdf