Skip to content

Instantly share code, notes, and snippets.

@teknosains
Created January 29, 2018 02:40
Show Gist options
  • Select an option

  • Save teknosains/538c9aaf0d3d22f04d4f7284587c482c to your computer and use it in GitHub Desktop.

Select an option

Save teknosains/538c9aaf0d3d22f04d4f7284587c482c to your computer and use it in GitHub Desktop.
Solving printing issue (with css styling) in Chrome and Firefox with Javascript
<div class="content">
<div style="background:#ddd">
<table style="height:200px"></table>
</div>
....
....
</div>
<script>
//add !important rule to every style found in each element
//so the browser print render the color/style also
var el = $('.content *');
if (el.length) {
el.each(function(item) {
var _this = $(this);
var attr = _this.attr('style');
var style = '';
if (typeof attr !== typeof undefined && attr !== false) {
if (attr.split(';').length) {
attr.split(';').forEach(function(item) {
if (item.trim() != '') {
style += item.trim() + '!important;-webkit-print-color-adjust: exact!important;';
}
});
_this.attr('style', style);
}
}
});
}
</script>
@teknosains
Copy link
Copy Markdown
Author

teknosains commented Jan 29, 2018

I was having a serious issue with printing (with css styling) in Chrome and Firefox. I need to have the Styling also printed/applied in printing Preview and the print result. I've tried some workrounds sugessted like adding -webkit-print-color-adjust: exact!important; etc, but still it didnt work in my case

Until i figured out that the Style need to have !important attribute. When working with WYSWYG Editor, you generally would have inline-styles css applied to the element and this could be a problem for printing. So I need to add !important to every css style attribute found in every element.

That's how I solved it using jQuery

Solving printing issue (with css styling) in Chrome and Firefox with Javascript

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment