Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export React Page to PDF

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.

like image 466
Victoria Le Avatar asked Oct 19 '25 23:10

Victoria Le


2 Answers

Have you tried react-pdf or react-to-pdf these 2 might work for you if you aren't using next.js

like image 184
Michael Essiet Avatar answered Oct 21 '25 20:10

Michael Essiet


I also faced same issue, now resolved by using @progress/kendo-react-pdf

visit https://www.telerik.com/kendo-react-ui/components/pdfprocessing/ for examples

sample code

import { PDFExport } from "@progress/kendo-react-pdf";
const ref: any = React.createRef();
...

<button onClick={() => {
            if (ref.current) {
              ref.current.save();
            }
          }}
>
  Export PDF
</button>
<div id="container">
    <PDFExport paperSize="A4" margin="0.5cm" ref={ref}>
        <div id="htmldata" >sample data</div>
    </PDFExport>
</div>

If you don't want to display contents of htmldata you can add below css

#container {
 width: 0px;
  height: 0px;
  overflow: hidden;
}
like image 29
Ramkumar G Avatar answered Oct 21 '25 20:10

Ramkumar G