Search code examples
reactjsreact-to-print

react to print not printing background color


Hi I am using a library react-to-print to print my react component into a pdf form.

here is the code below

export default function Index() {

  const handlePrint = useReactToPrint({
    content: () => componentRef.current,
    copyStyles: true,
    pageStyle: print,
  });
     

  return (
    <>
      <button onClick={handlePrint}>print</button>
      <div ref={componentRef}>
        <Header
          title="Seguro de Carro - Comparar Resultados"         
        />
      
        <HomeComparePackage packages={comparePack} />
        <HomeCompareMobile packages={comparePack} />
      </div>
    </>
  );
}

The issue is it was printing footer in my pdf too, so what i did was add the configuration for it

  const print = `
  @media print {
    footer {
      display: none;
    }

  }
`;

 const handlePrint = useReactToPrint({
    content: () => componentRef.current,
    copyStyles: true,
    pageStyle: print,
  });

As soon as i changed the configuration to the above one, it started ignoring my css colors in the component? Is there a way i could preserve my css colors while setting footer to display null ?


Solution

  • Try to add body { -webkit-print-color-adjust: exact; }

    const handlePrint = useReactToPrint({
        content: () => componentRef.current,
        copyStyles: true,
        pageStyle: `
          @media print {
            @page { margin: 0; }
          }
          body {
            -webkit-print-color-adjust: exact;
          }
        `,
      });
    

    In the default printer, you can see the background graphics checkbox

    enter image description here

    Demo