Created
June 22, 2015 21:02
-
-
Save joseym/05d7e2b3a80e4473338e to your computer and use it in GitHub Desktop.
I needed a way to print a section of the page without any redirects or extra rendering
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* usage: `<button print="#elementId">Print Me Foo!</button>` | |
**/ | |
angular.module('ngApp', []).directive('print', function ($location, $timeout) { | |
return { | |
restrict: 'A', | |
link: function(scope, element, attrs) { | |
/** | |
* Kill the default click event and fire the iframe print | |
*/ | |
element.bind('click', function(evt){ | |
evt.preventDefault(); | |
PrintWithIframe($(attrs.print).html()); | |
}); | |
/** | |
* Creates a temporary and hidden iframe, which then fires the native `print` api. | |
* @param {string} data Body to be printed | |
*/ | |
function PrintWithIframe(data){ | |
/** | |
* Only allow for one iframe at a time, might need to make this targetting a bit more clever as | |
* I've sometimes hit the print button and been slapped in the face with inaction. | |
*/ | |
if ($('iframe#printf').size() == 0) { | |
// an iFrame is added to the html content, then your div's contents are added to it and the iFrame's content is printed | |
$('html').append('<iframe id="printf" name="printf" style="width: 100%;"></iframe>'); | |
// Add the necesarry stylesheet. | |
var styles = $('html').find('link[rel="stylesheet"]').filter(function(i, sheet){ | |
return sheet.href.match(/main.css/); | |
}).clone()[0]; | |
var mywindow = window.frames["printf"]; | |
mywindow.document.write('<html><head>' | |
+ styles.outerHTML | |
+ '<title></title><style>@page { margin: 0.5in }</style>' // Your styles here, I needed the margins set up like this | |
+ '</head><body><div id="printBody">' | |
+ data | |
+ '</div></body></html>'); | |
// When the iframe is prepped fire off the print | |
$(mywindow.document).ready(function(){ | |
mywindow.print(); | |
// Kill the iframe after 2 seconds, it should have initiated the print majesty | |
setTimeout(function(){ | |
$('iframe#printf').remove(); | |
}, | |
2000); | |
}); | |
} | |
return true; | |
} | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment