Thursday, 22 November 2012

"Print this page" functionality using jQuery - opening a print-friendly page

Certain pages on my current project have either a 'Print', or both
'Print' and 'Email' icons.

The implementation in the old system works like this:

- user clicks on Print icon, triggering a javascript request
- request includes the portlet Id and content Id as a parameter,
opening a new page
- the new page reads in the parameters and reloads the same contents
as the first page
- user can preview page and then print

I've reimplemented it using only jQuery, to make it as simple and
reusable as possible, and works like this:

- printable elements of the page either have a class or are enclosed
in a div with the class "printable"
- user clicks on Print icon, triggering a Javascript function which:
- loads a new page with print-friendly template, but with no content of its own
- on the new page, upon loading, Javascript runs to extract the
content with class "printable" from the parent window
- this content is then inserted into new page
- user can preview page and then print

The basic code is:

(add this to print page)

<script type='text/javascript'>
function printClick() {'print_template.html');

function getPrintContent (printSelector) {
// .clone() is required otherwise the content seems to be moved from
opening page to new page
var selections = $(printSelector).clone();
return selections;

$(function() {
// modify this to whatever we need to select the "Print" link.
$("li.print a").click(printClick);

(and on print page -- extract content from opener)

<script type='text/javascript'>
$(function() {
$('#main-content-wrapper').html( window.opener.getPrintContent('.printemail') );

I am inclined to replace the use of "printable" class and just enclose
all the print elements in one div and just get the contents from that
div. This is mainly due to having all our content managed in a CMS,
and if the producer does not include the "printable" class, then the
element won't get included on the print page.

No comments: