Margin
bkhtmltopdf supports page margin configuration via CSS @page
rules, using margin-*
properties to define top, right,
bottom, and left margins. These margins affect the PDF's print layout, but note that they occupy space within the
content area.
基本用法
Specify @page
rules within @media print
media queries:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Margin Example</title>
<style>
@media print {
@page {
size: A5 landscape;
margin-top: 2rem;
margin-right: 2rem;
margin-bottom: 2rem;
margin-left: 2rem;
}
}
</style>
</head>
<body>
<h1>Hello World!</h1>
<p>Content will be affected by margins.</p>
</body>
</html>
Units supported include mm, cm, in, px, em, and rem (based on root font size). Relative units (such as rem) are recommended to adapt to different page sizes.
Margin Effect Explanation
Page margins carve out blank areas within the @page
region, preventing <body>
content from filling the entire page.
The following example illustrates the impact of margins.
As shown in the figure above, the content area is compressed by margins. In actual development, it is recommended to
prioritize using the padding
property of html
and body
over @page
margins because:
padding
does not occupy page space but expands the content container.- It integrates more easily with CSS frameworks.
- It prevents unexpected clipping during printing.
Recommended Alternative: Using Padding
/* In @media print */
body {
padding: 2rem; /* Equivalent to 2rem margin */
}
/* Or targeting html */
html {
padding: 1in 2cm; /* Top/Bottom 1in, Left/Right 2cm */
}