ChatGPT解决这个技术问题 Extra ChatGPT

Background color not showing in print preview

I am trying to print a page. In that page I have given a table a background color. When I view the print preview in chrome its not taking on the background color property...

So I tried this property:

-webkit-print-color-adjust: exact; 

but still its not showing the color.

http://jsfiddle.net/TbrtD/

.vendorListHeading {
  background-color: #1a4567;
  color: white;
  -webkit-print-color-adjust: exact; 
}


<div class="bs-docs-example" id="soTable" style="padding-top: 10px;">
  <table class="table" style="margin-bottom: 0px;">
    <thead>
      <tr class="vendorListHeading" style="">
        <th>Date</th>
        <th>PO Number</th>
        <th>Term</th>
        <th>Tax</th>
        <th>Quote Number</th>
        <th>Status</th>
        <th>Account Mgr</th>
        <th>Shipping Method</th>
        <th>Shipping Account</th>
        <th style="width: 184px;">QA</th>
        <th id="referenceSO">Reference</th>
        <th id="referenceSO" style="width: 146px;">End-User Name</th>
        <th id="referenceSO" style="width: 118px;">End-User's PO</th>
        <th id="referenceSO" style="width: 148px;">Tracking Number</th>
      </tr>
    </thead>
    <tbody>
      <tr class="">
        <td>22</td>
        <td>20130000</td>
        <td>Jim B.</td>
        <td>22</td>
        <td>510 xxx yyyy</td>
        <td>zznn@abc.co</td>
        <td>PDF</td>
        <td>12/23/2012</td>
        <td>Approved</td>
        <td>PDF</td>
        <td id="referenceSO">12/23/2012</td>
        <td id="referenceSO">Approved</td>
      </tr>
    </tbody>
  </table>
</div>
It looks like it works properly: jsfiddle.net/tDggR/2 I'm using chrome version 25
gosh! It works even in java8 webview engine

M
Munim Munna

The Chrome CSS property -webkit-print-color-adjust: exact; works appropriately.

However, making sure you have the correct CSS for printing can often be tricky. Several things can be done to avoid the difficulties you are having. First, separate all your print CSS from your screen CSS. This is done via the @media print and @media screen.

Often times just setting up some extra @media print CSS is not enough because you still have all your other CSS included when printing as well. In these cases you just need to be aware of CSS specificity as the print rules don't automatically win against non-print CSS rules.

In your case, the -webkit-print-color-adjust: exact is working. However, your background-color and color definitions are being beaten out by other CSS with higher specificity.

While I do not endorse using !important in nearly any circumstance, the following definitions work properly and expose the problem:

@media print {
    tr.vendorListHeading {
        background-color: #1a4567 !important;
        -webkit-print-color-adjust: exact; 
    }
}

@media print {
    .vendorListHeading th {
        color: white !important;
    }
}

Here is the fiddle (and embedded for ease of print previewing).


When opening the fiddle, I'm getting the Print preview failed. message in Chrome v47.0.2526.106
Mozilla has marked this as non-standard, so the results are inconsistent and shouldn't be used in production sites developer.mozilla.org/en-US/docs/Web/CSS/…
Yes, this works in Chrome. Bootstrap css was overriding it for me using print media. You can also preview and inspect print mode using the Rendering tab at bottom of Chrome Elements inspector. There's an option for Emulate CSS Media in case you want to see the override stack.
Works for me with !important in background
R
Riskbreaker

That CSS property is all you need it works for me...When previewing in Chrome you have the option to see it BW and Color(Color: Options- Color or Black and white) so if you don't have that option, then I suggest to grab this Chrome extension and make your life easier:

https://chrome.google.com/webstore/detail/print-background-colors/gjecpgdgnlanljjdacjdeadjkocnnamk?hl=en

The site you added on fiddle needs this in your media print css (you have it just need to add it...

media print CSS in the body:

@media print {
body {-webkit-print-color-adjust: exact;}
}

UPDATE OK so your issue is bootstrap.css...it has a media print css as well as you do....you remove that and that should give you color....you need to either do your own or stick with bootstraps print css.

When I click print on this I see color.... http://jsfiddle.net/rajkumart08/TbrtD/1/embedded/result/


extension works for all the pages but it does not work for my code why jsfiddle.net/rajkumart08/TbrtD/1/embedded/result defie.co/testing/twitter-bootstrap-558bc52/docs/examples/…
if thats the case make sure your bootstrap has webkit-print-color-adjust: exact; on your body is another way to check...in print media css of course
its not working defie.co/testing/twitter-bootstrap-558bc52/docs/examples/… i gave it in this code
You did not add it in the print media as I stated in your html inner css: yout html line 1154: @media print { body {margin:0; padding:0; line-height: 1.4em; word-spacing:1px; letter-spacing:0.2px; font: 12px Arial, Helvetica,"Lucida Grande", serif; color: #000;}.... you need to add it in there...
saved my day!!!!
T
Travis J

Chrome will not render background-color, or several other styles, when printing if the background graphics setting is turned off.

This has nothing to do with css, @media, or specificity. You can probably hack your way around it, but the easiest way to get chrome to show the background-color and other graphics is to properly check this checkbox under More Settings.

https://i.stack.imgur.com/qc1g6.png


Hey, I've finally got around to making a fiddle jsfiddle.net/qm7shrvf for some reason, I cannot get chrome to render the green or red backgrounds in the print preview (I haven't tried to actually print it though) Thanks! (I did observe that the black background of jsfiddle.net does get rendered based on that chrome setting though)
F
Flea

I just needed to add the !important attribute onto the the background-color tag in order for it to show up, did not need the webkit part:

background-color: #f5f5f5 !important;


That's fine..May i know the reason why the color is not shown without giving important @Flea
Well don't understand why this is happening but it solved my problem :-)
The reason is bootstrap.css, It has a media print css that is taking importance over your css. Following are solutions in this case: - A. override bootstrap media print styles by writing your styles in media print in your css file. - B. give !important to your original styles so that bootstrap media print css cannot override it. In Your case !important have more priority than bootstrap's media print css, That's the reason why !important worked in your case.
It works only when we use style attr example: <td width="35%" style="background-color: #DAEEF3 !important;"> and the webkit is mandatory
Y
Yahya Uddin

Your CSS must be like this:

@media print {
   body {
      -webkit-print-color-adjust: exact;
   }
}

.vendorListHeading th {
   background-color: #1a4567 !important;
   color: white !important;   
}

I have used css in this way but does not work for me
This 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, there is an alternative for Firefox, please try using also color-adjust: exact; for more info visit stackoverflow.com/questions/35625178/…
It works only when we use style attr example: <td width="35%" style="background-color: #DAEEF3 !important;">
Miguel you rock!! only person in this thread to mention Firefox, saving my day
B
BassMHL

FOR THOSE USING BOOTSTRAP.CSS, this is the fix!

I have tried all the solutions and they weren't working... until I discovered that bootstrap.css had a super annoying @media print that resets all your colors, background-colors, shadows, etc...

@media print{*,:after,:before{color:#000!important;text-shadow:none!important;background:0 0!important;-webkit-box-shadow:none!important;box-shadow:none!important}

So either remove this section from bootstrap.css (or bootstrap.min.css)

Or override these values in the css of the page you want to print in your own @media print

@media print {
  body { 
    -webkit-print-color-adjust: exact; 
  }
  .customClass{
     //customCss + !important;
  }
  //more of your custom css
}

P
PADMAJA SONWANE

For IE

If you are using IE then go to print preview ( right click on document -> print preview ), go to settings and there is option "print background color and images", select that option and try.

https://i.stack.imgur.com/rVryx.png


V
Vyacheslav Cotruta

If you are using bootstrap or any other 3rd party CSS, make sure you specify the media screen only on it, so you have the control of the print media type in your own CSS files:


Remember, if you add media="screen" to bootstrap css, then every style from bootstrap will be striped out.
O
Optimaz ID

if you are using Bootstrap.just use this code in your custom css file. Bootstrap removes all your colors in print preview.

@media print{
  .box-text {

    font-size: 27px !important; 
    color: blue !important;
    -webkit-print-color-adjust: exact !important;
  }
}

Adding the important description after my settings helped. I had to have the -webkit-print-color-adjust set at body and then in each of my elements that needed color, I had to declare them important for this to work.
L
Lightness Races in Orbit

Are your sure this is a css issue ? There are some posts on google around this issue: http://productforums.google.com/forum/#!category-topic/chrome/discuss-chrome/eMlLBcKqd2s

It may be related to the print process. On safari, which is webkit also, there is a checkbox to print background images and colors in the printer dialog.


E
Eugen Konkov

Use the following in your @media print style sheet.

h1 {
    background-color:#404040;
    background-image:url("img/404040.png");
    background-repeat:repeat;
    box-shadow: inset 0 0 0 1000px #404040;
    border:30px solid #404040;
    height:0;
    width:100%;
    color:#FFFFFF !important;
    margin:0 -20px;
    line-height:0px;
}

Here are a couple things to note:

background-color is the absolute fallback and is there for posterity mostly.

background-image uses a 1px x 1px pixel of #404040 made into a PNG. If the user has images enabled it may work, if not...

Set the box-shadow, if that doesn't work...

Border = 1/2 your desired height and/or width of box, solid, color. In the example above I wanted a 60px height box.

Zero out the heigh/width depending on what you're controlling in the border attribute.

Font color will default to black unless you use !important

Set line-height to 0 to fix for the box not having physical dimension.

Make and host your own PNGs :-)

If the text in the block needs to wrap, put it in a div and position the div using position:relative; and remove line-height.

See my fiddle for a more detailed demonstration.


T
Taugenichts

There's a style in the bootstrap css files under @media print{*,:after,:before ....} that has color and background styles labeled !important, which remove any background colors on any elements. Kill those two pieces of css and it will work.

Bootstrap is making the executing decision that you should never have any background color in prints, so you have to edit their css or have another !important style that is a higher precedence. Good job bootstrap...


h
hilnius

I used purgatory101's answer but had trouble keeping all colours (icons, backgrounds, text colours etc...), especially that CSS stylesheets cannot be used with libraries which dynamically change DOM element's colours. Therefore here is a script that changes element's styles (background-colour and colour) before printing and clears styles once printing is done. It is useful to avoid writing a lot of CSS in a @media print stylesheet as it works whatever the page structure.

There is a part of the script that is specially made to keep FontAwesome icons color (or any element that uses a :before selector to insert coloured content).

JSFiddle showing the script in action

Compatibility: works in Chrome, I did not test other browsers.

function setColors(selector) {
  var elements = $(selector);
  for (var i = 0; i < elements.length; i++) {
    var eltBackground = $(elements[i]).css('background-color');
    var eltColor = $(elements[i]).css('color');

    var elementStyle = elements[i].style;
    if (eltBackground) {
      elementStyle.oldBackgroundColor = {
        value: elementStyle.backgroundColor,
        importance: elementStyle.getPropertyPriority('background-color'),
      };
      elementStyle.setProperty('background-color', eltBackground, 'important');
    }
    if (eltColor) {
      elementStyle.oldColor = {
        value: elementStyle.color,
        importance: elementStyle.getPropertyPriority('color'),
      };
      elementStyle.setProperty('color', eltColor, 'important');
    }
  }
}

function resetColors(selector) {
  var elements = $(selector);
  for (var i = 0; i < elements.length; i++) {
    var elementStyle = elements[i].style;

    if (elementStyle.oldBackgroundColor) {
      elementStyle.setProperty('background-color', elementStyle.oldBackgroundColor.value, elementStyle.oldBackgroundColor.importance);
      delete elementStyle.oldBackgroundColor;
    } else {
      elementStyle.setProperty('background-color', '', '');
    }
    if (elementStyle.oldColor) {
      elementStyle.setProperty('color', elementStyle.oldColor.value, elementStyle.oldColor.importance);
      delete elementStyle.oldColor;
    } else {
      elementStyle.setProperty('color', '', '');
    }
  }
}

function setIconColors(icons) {
  var css = '';
  $(icons).each(function (k, elt) {
    var selector = $(elt)
      .parents()
      .map(function () { return this.tagName; })
      .get()
      .reverse()
      .concat([this.nodeName])
      .join('>');

    var id = $(elt).attr('id');
    if (id) {
      selector += '#' + id;
    }

    var classNames = $(elt).attr('class');
    if (classNames) {
      selector += '.' + $.trim(classNames).replace(/\s/gi, '.');
    }

    css += selector + ':before { color: ' + $(elt).css('color') + ' !important; }';
  });
  $('head').append('<style id="print-icons-style">' + css + '</style>');
}

function resetIconColors() {
  $('#print-icons-style').remove();
}

And then modify the window.print function to make it set the styles before printing and resetting them after.

window._originalPrint = window.print;
window.print = function() {
  setColors('body *');
  setIconColors('body .fa');
  window._originalPrint();
  setTimeout(function () {
    resetColors('body *');
    resetIconColors();
  }, 100);
}

The part that finds icons paths to create CSS for :before elements is a copy from this SO answer


It works, thanks (note that you will need to remove var from window on your last code snippet)
E
EM-Creations

You can also use the box-shadow property.


M
Mohd. Shaizad

The best solution for this if you are using bootstrap so just do one thing remove @media print {} all code inside this. and enable background graphics from more settings while taking print preview.


Why remove all print CSS while printing?
This is to make color visible for print
w
w.Daya

You can use inline css styles with !important. Eg.

<p style="background:red!important">ABCD</p>

u
user2430846

If you download Bootstrap without the "Print media styles" option, you will not have this problem and do not have to remove the "@media print" code manually in your bootstrap.css file.


B
Bhargav Rao

I double load my external css source file and change the media="screen" to media="print" and all the borders for my table were shown

Try this :

<link rel="stylesheet" media="print" href="bootstrap.css" />

<link rel="stylesheet" media="screen" href="bootstrap.css" />

this could be done with media="all" instead of two link tags