0
votes

I'd like to be able to export React Page to PDF file(s). So far, I've tried jsPDF and html2canvas to capture the page as an image and save it as a pdf. Sample code:

const input = document.getElementById('exportToPDF')
    window.scrollTo(0,0)
    html2canvas(input)
      .then((canvas) => {
        document.body.appendChild(canvas)
        const imgData = canvas.toDataURL('image/png')
        const pdf = new jsPDF()
        pdf.addImage(imgData, 'PNG', 0, 0)
        pdf.save("test.pdf")
      });

and 'exportToPDF' example:

<div id="exportToPDF">...</div>

I ran into problems with the canvas got cut off when the page content is too large/long. How can I get it to break into multiple pages when needed? It appears as it's limited to one page only.

What I have tried: set window width and height to html2canvas but it didn't help.

Update: I'm open to try other ways to export React page to PDF file(s) and not having to use html2canvas that are free.

1
Can you show the source that's causing the problem? Thanks.ggorlen
html2canvas makes an image - you almost certainly don't want an image in a PDF if it has text in itAndy Ray
@AndyRay You're correct. I'm open to suggestions?Victoria Le
we had same issue to some extent jspdf-yworks (now jspdf v2.0) solved. However we decided to use a server side convertor by sending rendered DOM html back to server for conversion using xhtml2pdf in python+flask. It was literally 6 lines of code and offers a much more flexible solution. One downside - styles and images need to be inline - which is not difficult.Bhuvan

1 Answers

0
votes

Have you tried react-pdf[https://react-pdf.org/] or react-to-pdf[https://www.npmjs.com/package/react-to-pdf] these 2 might work for you if you aren't using next.js