diegomura / react-pdf

📄 Create PDF files using React
https://react-pdf.org
MIT License
14.22k stars 1.11k forks source link

Display the contents of a specific div in a PDF #2697

Open rabbitdevv opened 1 month ago

rabbitdevv commented 1 month ago

I use the react-pdf plugin, and I like the structured way the document is organized. But there is a issue. I have a specific div, and this div has a large child structure. I want to be able to specify the content of that div by specifying a selector or via useRef().

Here is the code:

const testEl = useRef();

const MyDoc = () => (
  <Document>
    <Page>
      <View>
        Here I want to display the content of the div with class "test" or by ref "testEl".
        <Tag ref={testEl} or selector={document.querySelector('.test')} />
      </View>
    </Page>
  </Document>
)

return (
  <>
    <div ref={testEl} className="test"><...large structure...></div>
    <PDFDownloadLink document={<MyDoc />} fileName="print-test.pdf">
      {({ loading }) => (loading ? "Loading document..." : "Download now!")}
    </PDFDownloadLink>
  </>
)

Can you tell me how I can do this using react-pdf? I just want to display the tag I need in a pdf document. If this is not possible, it would be a very useful feature in this plugin.

pietroanello commented 1 month ago

Hi, I don't think there's a library solution to this, but maybe you can try using html2Img to do it.

async function getDataUri(el = document.getElementById("#yourId")) {
  if (!el) return ''

  const uri = await htmlToImage.toPng(el, {
    canvasWidth: el.getBoundingClientRect().width * 2,
    canvasHeight: el.getBoundingClientRect().height * 2,
  })

  return uri
}

Then just play with your div / pdf Image dimensions, and eventually cut your div into multiple divs if the entire one exceed the page.

pietroanello commented 1 month ago

Of course the "other" way to do it is to recreate your entire div structure with react-pdf components

rabbitdevv commented 1 month ago

Hi, I don't think there's a library solution to this, but maybe you can try using html2Img to do it.

async function getDataUri(el = document.getElementById("#yourId")) {
  if (!el) return ''

  const uri = await htmlToImage.toPng(el, {
    canvasWidth: el.getBoundingClientRect().width * 2,
    canvasHeight: el.getBoundingClientRect().height * 2,
  })

  return uri
}

Then just play with your div / pdf Image dimensions, and eventually cut your div into multiple divs if the entire one exceed the page.

Thanks for the reply. I'm already using this plugin htmltoimage, but it's very strange that react-pdf doesn't have this feature. It would be very useful for many developers.