'Span Background Color set with javascript not printed

I have the following code that sets a legend for a graph built with Morris Js:

grafico1.options.data.forEach(function(label, i) {
  var legendItem = $('<span></span></br>').text( label['label'] + " ( " +label['value'] + " )" ).prepend('<br><span>&nbsp;</span>');
  legendItem.find('span')
    .css('background-color', grafico1.options.colors[i])
    .css('width', '20px')
    .css('display', 'inline-block')
    .css('margin-right', '15px')
    .css('float','left');
  $('#legend').append(legendItem).css('text-align','left').css('font-size','15px')
});

The graph is the following:

Graph on the web page before printing

But when I want to print the graphs all the background colors of the <span> elements they disappear like in this picture:

Legend without colors on printing

I've already tried to include body { -webkit-print-color-adjust: exact; } in my css and to set Background Colors on printing but nothing seems to work. It's not just a Chrome problem, I've tried with many other browsers. I appreciate your help. Thank you very much.



Solution 1:[1]

The problem is that i use bootstrap as external css. They have a background: transparent on the @media print{} part of the css. Just remove that line and the problem is solved!

Solution 2:[2]

For those (like me) stumbling upon this thread because they can't get their span background color to print in Firefox.

What worked for me was setting the following css in my span class:

print-color-adjust: exact;

You'll need to add

-webkit-print-color-adjust: exact;

for Chrome

Solution 3:[3]

If performance is a priority, you can also do it the long, manual way:

function runlengthdecode(vals::Vector{T}, reps::Vector{<:Integer}) where T
  length(vals) == length(reps) || throw(ArgumentError("Same number of values and counts expected"))

  result = Vector{T}(undef, sum(reps))
  resind = 1
  for (valind, numrep) in enumerate(reps)
    for i in 1:numrep
      @inbounds result[resind] = vals[valind]
      resind += 1
    end
  end

  result
end

This runs about 12 times faster than the vcat/fill based method for the given data, likely because of avoiding creating all the intermediate filled vectors.

You can also instead use fill! on the preallocated result's @views, by replacing the loop in above code with:

  for (val, numrep) in zip(vals, reps)
    fill!(@view(result[resind:resind + numrep - 1]), val)
    resind += numrep
  end

which has comparable performance.

Solution 4:[4]

Also, for completeness, a comprehension can be quite handy for this. And it's faster than fill and vcat.

julia> [x[i] for i=1:length(x) for j=1:y[i]]
11-element Vector{Int64}:
 1
 1
 1
 2
 2
 3
 4
 4
 5
 5
 5

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexandru Duma
Solution 2 Raph
Solution 3 Sundar R
Solution 4 AboAmmar