In this tutorial I will show you how to add custom text to a printed web page using CSS and JavaScript.
We can do this using CSS3 by using Pseudo Elements and Generated Content.
We can do this using JavaScript by using onafterprint and onbeforeprint.
Adding Image to the Printed Web Page using CSS
This is the CSS code to add an extra image to the web page when its printed.
/*adding an image at the end of the printed page*/
body:after{
content:url(http://qtrack.qnimate.com/qtrack.jpg);
}
/*adding an image at the beginning of the printed page*/
body:before{
content:url(http://qtrack.qnimate.com/qtrack.jpg);
}
}
Adding Text to the Printed Web Page using CSS
This is the CSS code to add text to the webpage when its printed
/*adding text at the end of the printed page*/
body:after{
content:"end";
}
/*adding text at the beginning of the printed page*/
body:before{
content:"beginning";
}
}
Adding Content using JavaScript
Here is the code to add content using JavaScript
//add some content
}
function afterPrint() {
//remove the added content
}
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
Conclusion
Both the above methods rely on CSS3 media queries some way. Therefore if user’s browser doesn’t support media query then you are out of luck.
Leave a Reply