CSS Print
The main method for creating printable PDFs using web technologies is to utilize the browser's print functionality, preferably on Chromium or Chrome.
CSS allows you to create stylesheets specific to the screen and print media. With the media print
feature, you can have a different design and even different content for the print output compared to the screen.
How CSS Print Works
@media print {
/* Your print-specific CSS here */
}
Defining Page Format
@media print {
@page { size: A4; }
/* or */
@page { size: 21cm 29.7cm; }
}
Setting Margins
/* Set margins */
@page { margin: 2cm; }
/* Set left page margins */
@page :left { margin: 1cm; }
/* Set right page margins */
@page :right { margin: 1cm; }
/* Set margins on the first page, you can also target a specific page */
@page :first { margin: 1cm 2cm; }
Note that if you want to print with a background color, the margins will be left blank.
Page Breaks
The three CSS properties page-break-before
, page-break-after
, and page-break-inside
allow you to control where page breaks occur or should be avoided.
page-break-before
: Controls a page break before an HTML element.page-break-after
: Controls a page break after an HTML element.page-break-inside
: Prevents an HTML element from being split across multiple pages (e.g., images).
/* These properties can take the following values: */
page-break-after: auto | always | avoid;
page-break-before: auto | always | avoid;
page-break-inside: auto | avoid;
auto
is the default value, always
adds a page break every time, and avoid
prevents a page break. For example:
h1, h2, h3, h4, h5, h6 {
page-break-after: avoid;
}
img {
page-break-inside: avoid;
}
Different Content for Web and Print
You can hide certain elements on the web and display them in the print version, and vice versa.
@media screen {
h1 {
display: none;
}
}
@media print {
img {
display: none;
}
}