ivmarcos / react-to-pdf

Generate pdf from react components
MIT License
282 stars 62 forks source link

Conditionally render an element #113

Closed aaronzhongg closed 9 months ago

aaronzhongg commented 9 months ago

Thank you @ivmarcos for creating this library - it's been a pleasure using it without having to write a whole lot of separate code.

I'm trying to conditionally render an element when I'm printing which is otherwise not displayed.

Here's an example for a watermark that I don't want to render on the screen, but want to show in the pdf: https://codesandbox.io/p/sandbox/fervent-brown-2j55ld

Maybe TMI but my use case isn't exactly a watermark, it's a little bit more complex but I hope it represents the problem well!

Thanks

ivmarcos commented 9 months ago

Hey @aaronzhongg I believe you can use the onclone callback to do that.

from the html2canvas docs: https://html2canvas.hertzen.com/configuration

Callback function which is called when the Document has been cloned for rendering, can be used to modify the contents that will be rendered without affecting the original source documen

See also: https://github.com/niklasvh/html2canvas/issues/701#issuecomment-149355710

import { Options } from 'react-to-pdf'
...
const options: Options = {
    overrides: {
      canvas: {
        onclone: (document) => {
          document.getElementById("elementId")!.classList.toggle('visible')
        },
      },
    },
  };
aaronzhongg commented 9 months ago

Thanks @ivmarcos that works well!