Skip to main content

Page

bkhtmltopdf adheres to standard HTML/CSS specifications, allowing you to freely write HTML code to define page layouts. The core functionality is controlled via CSS @page rules to manage print output (such as page size and orientation). Below is a detailed guide with examples.

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hi, bkhtmltopdf!</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>

Run Online

Size​

bkhtmltopdf supports multiple standard page sizes. Specify them using CSS @media print and @page rules: Several standard page sizes are available:

Predefined Sizes​

Below are common standard sizes (in mm):

SizeWidth × HeightDescription
A3297 × 420Large posters/charts
A4210 × 297Standard letterhead
A5148 × 210Books/booklets
B4250 × 353Japanese Standard
B5176 × 250Japanese Pamphlet
Letter216 × 279US Letter
Legal216 × 356US Legal Document
Ledger432 × 279US Ledger

Example: Setting A5 Size​

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hi, bkhtmltopdf!</title>
<style>
@media print {
@page {
size: A5;
}
}
</style>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>

Run Online

Units​

If predefined sizes don't meet your needs, you can manually specify width and height. Supported units include:

  • mm
  • cm
  • in
  • px (pixels, based on 72 DPI)
@media print {
@page {
size: 210mm 297mm; /* A4 */
}
}
tip

Pixel units are suitable for screen adaptation but convert to physical units during printing. Use mm or cm for guaranteed precision.

Page Orientation (Landscape/Portrait)​

The default orientation is portrait. To switch to landscape, add the landscape keyword within @page.

@media print {
@page {
size: A5 landscape;
}
}

Run Online

Custom Orientation Notes​

When using custom sizes not predefined, manually swap width and height:

@media print {
@page {
size: 210mm 297mm; /* A4 portrait */
/* size: 297mm 210mm; /* A4 landscape (commented example) */
}
}

JavaScript​

bkhtmltopdf fully supports JavaScript, including inline scripts and externally loaded scripts. JS is executed during rendering to dynamically generate content. You can use script tags or include external script files.

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hi, bkhtmltopdf!</title>
<script src="https://cdn.jsdelivr.net/gh/jquery/jquery/dist/jquery.min.js"></script>
</head>
<body>
<h1>Hello World!</h1>
<p id="dynamic">Loading...</p>
<script>
document.getElementById('dynamic').innerHTML = 'Hello from JavaScript!';
</script>
</body>
</html>

Run Online

tip

JS execution timing is influenced by the waitUntil parameter. For complex interactions, use waitUntil: manual to ensure full rendering.