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>
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):
Size | Width × Height | Description |
---|---|---|
A3 | 297 × 420 | Large posters/charts |
A4 | 210 × 297 | Standard letterhead |
A5 | 148 × 210 | Books/booklets |
B4 | 250 × 353 | Japanese Standard |
B5 | 176 × 250 | Japanese Pamphlet |
Letter | 216 × 279 | US Letter |
Legal | 216 × 356 | US Legal Document |
Ledger | 432 × 279 | US 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>
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 */
}
}
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;
}
}
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>
JS execution timing is influenced by the waitUntil parameter. For complex interactions, use waitUntil: manual to ensure full rendering.