简体   繁体   中英

How to create a PDF file from my page in the React based project?

I tried make this PDF file with html2canvas and jspdf :

const input = document.getElementById('pdfTest')!;
html2canvas(input)
      .then((canvas) => {
           const imgData = canvas.toDataURL('image/png');
           const pdf = new jsPDF();
          * pdf.addImage(imgData, 'PNG', 0, 0);
           pdf.save("download.pdf");
      });

But in the * line I got this error:

Unhandled Rejection (Error): Supplied Data is not a valid base64-String jsPDF.convertStringToImageData 

Thanks a lot.

Use following method (you can change font size/style):

printDet = (e) => {
        html2canvas(document.querySelector("#pdfTest")).then(canvas => {

            const imgData = canvas.toDataURL('image/png');
            const pdf = new jsPDF();

            pdf.setFontSize(20)
            pdf.setFontStyle("bold")
            pdf.addImage(imgData, 'JPEG', 0, 0, 210, 200, 'alias');

            pdf.save('download.pdf');

        });

    }

Don't forget to import:

import html2canvas from 'html2canvas';

import jsPDF from 'jspdf';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM