html2pdf.js icon indicating copy to clipboard operation
html2pdf.js copied to clipboard

Background color is not correctly passed to html2canvas

Open milos-popadic opened this issue 3 years ago • 3 comments

I have a need to color the pdf background color. My content does not take full pages and I need to set the color of the remainder of the page to match my contents background.

I made 2 code pens:

html2canvas: https://codepen.io/Beckilicki/pen/eYBKRGP

html2pdf.js: https://codepen.io/Beckilicki/pen/bGBKRRR

On first one when I change the "backgroundColor" property it takes effect, while on the second one it does not. I have looked through similar issues but without much luck.

I have tried:

  • using background property instead of "backgroundColor",
  • setting "allowTaint" property to true
  • setting "removeContainer" property to true
  • combinations of the above

Any help on this issue would be greatly appreciated.

milos-popadic avatar Mar 03 '21 13:03 milos-popadic

Did you find it?

qnxdev avatar Aug 04 '21 12:08 qnxdev

having the same problem. Did you ever figure this out?

markusv avatar Sep 09 '21 08:09 markusv

Also spend few hours to figure this out...

Looks like backgroundColor property which is correctly passed to html2canvas overrides buy background, that comes from container, which html2pdf.js creates when copy dom node for conversion. Simple workaround - is to clone your element before passing it to html2pdf and add style.backgroundColor = '#yourcolor' to it. Something like

example from my react app:

 const handlePdfClick = async (e) => {
    const htmlContent = ref.current.cloneNode(true);
    htmlContent.style.backgroundColor = '#3f2782';
    await html2pdf().set(options).from(htmlContent).save();
  }

AlexanderMoroz avatar Sep 19 '22 19:09 AlexanderMoroz