Print only lightbox or modal window content

Print only lightbox or modal window content

This was a real kick in the Jimmy.

On a recent project I had a requirement to print contents of a modal window. Solution:

  1. When the user clicks a print button add an iframe to the end of the body tag.
  2. Hide it by moving it off the view port.
  3. Get the modal contents and load them into the iframe.
  4. Finally tell the browser to print the iframe.

Easier said than done. Here is my final code hope this helps someone else not lose an entire Sunday. I started working from this code http://www.bennadel.com/blog/1591-ask-ben-print-part-of-a-web-page-with-jquery.htm so props to the Ben for writing and posting it. Note if you want to use this you will have change some of the jQuery selectors to suite your project.

/* @brief Prints modal contents
 * @author lorenzogangi@gmail.com
 */
 
"printModal": function(){
 
    //make a iframe and hide it
    var tempFrame = $("<iframe id="printFrame" name="printFrame" width="300" height="150">")
    tempFrame.css( {
        "width": "1px",
	"height": "1px",
	"position": "absolute",
	"left": "-100000px"	
    } );
 
    //attach the iframe to the end of the body so we can hide the body content for IE. I hate IE
    $body = $("body");
    var ieStyle = $("<style class="ie"> body *{ display: none; } body #printFrame{ display: block !important; } </style>");
    $body.append(tempFrame).append(iestyle);
 
    //get the print styles, these are my custom print styles you could use a string here I chose to put them in a template file
    var printStyle = new  EJS({url: 'templates/mealModalPrintStyles.ejs'}).render({});
 
   //get the modal window content
    var $content = this.element.find(".buildAMeal__meal-info").clone();
    $content.find(".buildAMeal__modal-ingredient-edit-button, .btn-group").remove();
    $content.prepend("
 
 
<h1>YOUR MEAL" );
   printDocument.write( "<html>" );
   printDocument.write( "<body>" );
   printDocument.write( "<head>" );
   printDocument.write( "<title>" );
   printDocument.write( document.title );
   printDocument.write( "</title>" );
   printDocument.write( printStyle );
   printDocument.write( "</head>" );
   printDocument.write( $content.html() );
   printDocument.write( "</body>" );
   printDocument.write( "</html>" );
   printDocument.close();
 
   //focus the iframe and print it 
   printFrame.focus();
   printFrame.print();
 
   //cleanup print style and print iframe 
   ieStyle.remove(); 	
   setTimeout( function(){ tempFrame.remove(); },(60 * 1000));
 
}// end printModal
This entry was posted in Javascript, Uncategorized. Bookmark the permalink.