Creating printer-friendly page-breaks using CSS

Category: Software and Systems Engineering
Author: Sean O'Donnell
Mon, Oct. 17th, 2011 @ 15:13:12 (MDT)

If you work with HTML and/or CSS, then you are probably aware that you can use custom CSS stylesheets for various media devices outside of the desktop web browser, such as mobile phones and printing devices.

I recently had to create an Analytic Report which required custom programming specifically for controlling the output to a printer. Mainly, to control page-breaks as I would in normal desktop publishing programs such as Microsoft Word.

The solution was rather simple, and quite effective: custom CSS classes and a few HTML tricks, and the problem was solved.

<link rel="stylesheet" href="print.css" type="text/css" media="print" />

The HTML "<link>" tag provides the 'media' attribute, which can allow you to define your media target, such as "print" or "screen" (default).

print.css

This is the stylesheet that will be used by printing devices.

body {
    background-color: white;
    color: black;
    font-size: small;
    font-family: sans-serif, helvetica, tahoma, arial;
}

.page-break  { 
    display:block; 
    page-break-before:always; 
}

The 'page-break' class (above) will allow you to embed page breaks as if you were using Microsoft Word.

screen.css

This is the stylesheet is will be displayed by default to web browsers and computer screens.

body {
    background-color: white;
    color: black;
    font-size: small;
    font-family: sans-serif, helvetica, tahoma, arial;
}

example.html

This HTML file is an example of how to separate content into multiple pages when printed, using the stylesheets above.

<html>
<head>
 <title>CSS Print vs. Screen Example</title>

 <link rel="stylesheet" href="screen.css" type="text/css" media="screen" />

 <link rel="stylesheet" href="print.css" type="text/css" media="print" />

</head>

<body>

<h1>Sean's CSS Print vs. Screen Example</h1>
<h2>Page 1</h2>
<p>This would be the cover page. Add your style accordingly.</p>

<div class="page-break"></div>
<h2>Page 2</h2>
<p>Page 2 Example</p>

<div class="page-break"></div>
<h2>Page 3</h2>
<p>Page 3 Example</p>

</body>
</html>

When sent to a printer, the output of this HTML page would be separated into 3 individual pages, rather than just 1 page.

You can also use a global stylesheet, which would be displayed by both 'print' and 'screen' devices, simply by not defining a 'media' attribute in your HTML "<link>" tag.

<link rel="stylesheet" href="global.css" type="text/css" />

Copyleft (<) 1998-2019 www.seanodonnell.com