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.

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

Style the original HTML divs with ordinary CSS, then give their containing element to html2pdf.js. The library does not provide a separate PDF styling language: it clones the DOM, renders it through html2canvas, and writes the result with jsPDF. Use explicit dimensions, colors, spacing and typography in the source markup, then control pagination with CSS break-* rules or html2pdf.js pagebreak options.

How html2pdf.js turns a styled div into a PDF

The export pipeline explains most surprises:

  1. html2pdf.js clones the element you pass to from().
  2. html2canvas paints that clone as a canvas.
  3. jsPDF places the rendered output on PDF pages.

Consequently, style the source element and its descendants before calling save(). A rule that only affects your application shell, a hidden element, or a viewport-dependent position may not appear in the clone. The live browser view is not the final authority; inspect the generated PDF.

Start with a predictable export container

Give the exported root a deliberate box model. Explicit values reduce differences between the live page and the canvas render.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<div id="invoice">
  <section class="card avoid-break">
    <h2>Invoice</h2>
    <p class="muted">Content styled with ordinary CSS.</p>
  </section>
  <div class="page-two"></div>
  <section class="card">Second-page content</section>
</div>
#invoice {
  box-sizing: border-box;
  width: 100%;
  background: #fff;
  color: #222;
  font-family: Arial, sans-serif;
  font-size: 14px;
  line-height: 1.45;
}
#invoice *,
#invoice *::before,
#invoice *::after {
  box-sizing: inherit;
}
.card {
  padding: 16px;
  border: 1px solid #d8d8d8;
  border-radius: 8px;
  background: #fff;
}
.muted { color: #666; }
.avoid-break {
  break-inside: avoid;
  page-break-inside: avoid;
}
.page-two {
  break-before: page;
  page-break-before: always;
  height: 0;
}

Keep the capture root visible while it renders. Set backgrounds on the root and important children instead of relying on a body background that may not be included.

Control page breaks at the right level

Use modern CSS first, then add html2pdf.js selectors when you need export-specific control.

Goal CSS rule html2pdf.js option Best use
Start an element on a new page break-before: page (legacy fallback: page-break-before: always) before: '.selector' New chapters, receipts or appendices
End a section on the current page break-after: page (legacy fallback: page-break-after: always) after: '.selector' Force the next section forward
Keep a block together break-inside: avoid (legacy fallback: page-break-inside: avoid) avoid: '.selector' Cards, callouts and short tables
Prefer keeping everything together Not a single CSS declaration mode: 'avoid-all' Short documents where whitespace is acceptable
Insert a legacy break element Use an empty marker html2pdf__page-break class Older markup or existing templates

Most CSS break-before, break-after and break-inside rules are respected. A break can still move when the protected element is taller than the printable page; no pagination mode can keep an oversized block on one page.

Complete JavaScript export

This example combines CSS and selector-based rules. Include html2pdf.js in your page using the version and loading method your application already uses, then run:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const element = document.getElementById('invoice');

html2pdf().set({
  margin: 0.5,
  filename: 'invoice.pdf',
  image: { type: 'jpeg', quality: 0.95 },
  html2canvas: {
    scale: 2,
    useCORS: true,
    backgroundColor: '#ffffff'
  },
  jsPDF: {
    unit: 'in',
    format: 'letter',
    orientation: 'portrait'
  },
  pagebreak: {
    mode: ['css', 'legacy'],
    before: '.page-two',
    avoid: ['.avoid-break']
  }
}).from(element).save();

margin uses the jsPDF unit selected in jsPDF.unit. In this example it is inches. Change format to the paper size your audience needs, and use orientation: 'landscape' for wide tables. A larger html2canvas scale generally produces sharper text and images but consumes more memory and takes longer.

Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Styling patterns that survive rendering

Use explicit dimensions and spacing

Set widths, padding, borders, colors and font sizes on the export root and important descendants. Avoid layouts that depend on a changing viewport width. If the PDF is clipped, reduce the root width or choose a matching jsPDF format and margin; do not expect an oversized CSS box to be automatically scaled exactly as your browser displays it.

Keep cards and small tables intact

Apply both the modern and legacy declarations to reusable classes. Put avoid-break on the whole card, not on each paragraph. For a long table, protect only rows or groups that can realistically fit on a page; protecting a table taller than a page creates awkward whitespace or still requires a split.

Make images and fonts available before export

Wait until images have loaded, use stable dimensions, and check the actual PDF for missing fonts or images. Cross-origin assets may require appropriate CORS headers; useCORS: true tells html2canvas to attempt CORS loading but cannot grant permission that the server does not provide. For critical documents, use same-origin assets or a server configuration you control.

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

Prefer export-specific classes over application hacks

Keep PDF rules in a class or stylesheet scoped to the export root. This lets you hide navigation, change colors for print, or simplify a responsive layout without changing the on-screen page. The clone process has known CSS-cloning limitations, so simpler, explicit rules are often more reliable than deeply inherited or dynamically positioned styles.

Choosing a pagination strategy

Fine-grained CSS and selectors

Use mode: ['css', 'legacy'] with semantic classes when individual sections need different behavior. This is the most maintainable option for invoices, reports and multi-section documents.

Broad avoid-all

html2pdf().set({
  pagebreak: { mode: 'avoid-all' },
  jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
}).from(document.getElementById('report')).save();

This asks the paginator to keep elements together broadly. It is convenient for short content, but can create large blank areas and cannot keep content that physically exceeds a page.

Legacy marker

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

The legacy class inserts a break after that marker’s position. Keep it for existing templates; new code is usually clearer with break-before or an explicit pagebreak.before selector.

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

Debugging a PDF that looks different

Symptom Likely cause Fix
Colors or background missing Background is inherited from outside the cloned root or is transparent. Set background and color explicitly on the root and key children; set html2canvas.backgroundColor.
Content is cut off horizontally CSS width is wider than the selected paper and margins. Use an explicit export width, reduce margins, switch to landscape, or select a larger format.
A card splits despite avoid The card is taller than the printable area, or the selector does not match the cloned element. Verify the class, remove excessive padding, or split the content into smaller protected blocks.
Forced break is ignored The rule is outside the selected mode or the selector does not match. Use mode: ['css', 'legacy'], add the legacy declaration, and test the selector in the original DOM.
Images are blank They were not loaded or the origin blocks canvas access. Wait for img.complete, provide CORS headers, or serve the asset from the same origin.
Text or layout differs from the browser DOM cloning and canvas rendering do not reproduce every CSS behavior. Replace viewport-dependent positioning with explicit dimensions and inspect the exported PDF, not only the live page.
Browser tab runs out of memory Very large pages, high scale, or many large images. Lower scale, export sections separately, resize source images, and remove unnecessary content.

Performance, reliability and document-size trade-offs

  • Resolution: Increasing html2canvas.scale improves sharpness but increases canvas pixels, memory use and render time.
  • Page length: A single very tall element is more demanding than several page-sized sections. Split long reports at logical boundaries.
  • Images: Large source images inflate memory even when displayed small. Resize them before insertion.
  • Determinism: Freeze dynamic data, wait for fonts and images, and avoid animations while exporting.
  • Validation: Test narrow and wide content, empty states, long names, missing images and the final page. Pagination changes with real content.

html2pdf.js runs entirely in the browser, so the user’s device supplies the rendering time and memory. It is appropriate when the document must reflect client-side state; a server-side PDF pipeline may be preferable for large batches or strict archival reproducibility.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your requirement is a clean screenshot of a URL rather than a client-generated PDF with custom div pagination, ScreenshotNeo provides a one-request capture API. It can also return PDF output, but it does not replace html2pdf.js CSS rules when you need to style your own in-browser document.

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

See the ScreenshotNeo documentation for request options. Equivalent clients are:

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}`);
  • Cookie banners, newsletter popups and chat widgets are removed before the shot.
  • Bot checks, blank pages, failed loads and timeouts are not billed; response headers identify the page verdict and billing status.
  • An MCP server lets AI agents use take_screenshot, get_page_info and capture_pdf.
  • The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.

Create a free ScreenshotNeo account to try it without entering a card.

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.

Final checklist before shipping

  • Export the intended root element, not the entire application shell.
  • Set explicit root width, background, colors, typography and spacing.
  • Use break-inside: avoid only for blocks that fit on one page.
  • Combine mode: ['css', 'legacy'] with selector rules when precise breaks matter.
  • Wait for images and fonts, then inspect the generated PDF at every page boundary.
  • Test long, empty and failure-state content at the target paper size.

Frequently Asked Questions

Can html2pdf.js style a div after it has been converted?

No. Style the source DOM before calling from(); the library then clones and renders that styled content.

Which unit should I use for margins?

Use the same unit configured in jsPDF.unit. For example, a unit of in makes margin: 0.5 a half-inch margin.

What happens if an element is taller than one PDF page?

It cannot be kept intact on a single page. Reduce its content or split it into smaller sections that can fit.

Does ScreenshotNeo replace html2pdf.js?

No. ScreenshotNeo is useful for clean URL screenshots or API-generated captures; html2pdf.js remains the browser-side choice when your own div CSS and pagination rules must control the PDF.

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

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.