How to print or save a div’s content as PDF

Printing or saving a webpage as PDF can usually be done via the browsers printing functionality. To define the printing layout and styling you can use a print.css or some styles in a print media query. But what about printing only the contents of a specific element on a webpage? By using the print.css oder media query method you’d have to hide all other elements on a website, so there must be an easier option, right? One way to accomplish this, is a simple JavaScript function:

function printElement(elem, title) {
 
  var popup = window.open('', 'PRINT', 'height=600,width=900');

  popup.document.write('<html><head><title>' + title  + '</title><style>body {font-family: Arial;}</style>');
  popup.document.write('</head><body >');
  popup.document.write(document.getElementById(elem).innerHTML);
  popup.document.write('</body></html>');

  popup.document.close(); 
  popup.focus(); 

  popup.print();
  popup.close();

  return true;
}

This function opens a new popup with the content of a given element and automatically starts the browsers printing functionality. One of the functions parameter is the ID of the element you want to print, the other one is the title of the new popup which is also the filename of the PDF. You can also add some styles to the popup, like I did by setting the font family.

Leave a Comment

Your email address will not be published. Required fields are marked *