2

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.

Victoria Le
  • 860
  • 6
  • 15
  • Can you show the source that's causing the problem? Thanks. – ggorlen May 18 '21 at 21:33
  • 1
    `html2canvas` makes an image - you almost certainly don't want an image in a PDF if it has text in it – Andy Ray May 18 '21 at 21:34
  • https://stackoverflow.com/questions/40349075/html2canvas-image-is-getting-cut – gandharv garg May 18 '21 at 21:37
  • @AndyRay You're correct. I'm open to suggestions? – Victoria Le May 18 '21 at 21:40
  • 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 May 19 '21 at 02:14

2 Answers2

3

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

Jay Shukla
  • 454
  • 4
  • 13
1

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;
}
Ramkumar G
  • 415
  • 1
  • 8