Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to forcefully print background image in HTML?

Tags:

html

css

image

I need to print report page that has couple of background images on it. But only these images are not printable. These images are logos actually for graph and hence very important in report.

I have another option that I can crop them and include in page as tag but this is last option. Hence before that I would like to know if there is any way to forcefully print these images? Can anybody help me out?

like image 507
Shrikant Avatar asked Jun 28 '12 10:06

Shrikant


People also ask

How can I force browsers to print background images in CSS?

The -webkit-print-color-adjust property is a non-standard CSS extension that can be used to force printing of background colors and images in browsers based on the WebKit engine. This forces browsers to use background colors when user prints a web page even if they have Print Options Background Graphics turned off.


2 Answers

By default, a browser will ignore background css rules when printing a page, and you can't overcome this using css.

The user will need to change their browser settings.

Therefore, any image which you need to print should be rendered as an inline image rather than a css background. You can use css to display the inline image only for print though. Something like this.

HTML

<div class"graph-image graph-7">
  <img src="graph-7.jpg" alt="Graph Description" />
</div>

CSS

.graph-7{background: url(../img/graphs/graph-7.jpg) no-repeat;}
.graph-image img{display: none;}

@media print{
  .graph-image img{display:inline;}
}

Using this code, or similar code, means the image is used once in html and once in css. The html version is hidden using css, and for print it displays as normal. This is a hack, but it will do what you want it to do. It will print the image.

Having said that, what you're doing is terribly bad practice. Nothing which conveys meaningful information to the user should be conveyed using css alone. Not only is it semantically incorrect, but it makes the graph less useful to users. An inline image is much better, and if you can, that's what you should use.

like image 93
daveyfaherty Avatar answered Oct 02 '22 13:10

daveyfaherty


it is working in google chrome when you add !important attribute to background image make sure you add attribute first and try again, you can do it like tha

.class-name {
    background: url('your-image.png') !important;
}

also you can use these useful printing roll and put it at the end of css file

@media print {
* {
    -webkit-print-color-adjust: exact !important; /*Chrome, Safari */
    color-adjust: exact !important;  /*Firefox*/
  }
}
like image 28
Hady El-Hady Avatar answered Oct 02 '22 13:10

Hady El-Hady