PDF generate karne ke liye React JS me mostly 2 packages use hote hain:

  • jspdf
  • html2canvas
npm install jspdf html2canvas

Generate PDF from HTML Div:

import React from "react";
import jsPDF from "jspdf";
import html2canvas from "html2canvas";

function App() {

  const downloadPDF = () => {

    const input =
      document.getElementById("pdf-content");

    html2canvas(input).then((canvas) => {

      const imgData =
        canvas.toDataURL("image/png");

      const pdf = new jsPDF();

      const imgWidth = 190;

      const pageHeight = 295;

      const imgHeight =
        (canvas.height * imgWidth) /
        canvas.width;

      let heightLeft = imgHeight;

      let position = 0;

      pdf.addImage(
        imgData,
        "PNG",
        10,
        position,
        imgWidth,
        imgHeight
      );

      heightLeft -= pageHeight;

      while (heightLeft >= 0) {

        position = heightLeft - imgHeight;

        pdf.addPage();

        pdf.addImage(
          imgData,
          "PNG",
          10,
          position,
          imgWidth,
          imgHeight
        );

        heightLeft -= pageHeight;
      }

      pdf.save("react.pdf");

    });

  };

  return (

    <div>

      <div id="pdf-content">

        <h1>React PDF</h1>

        <p>
          This content will be downloaded
          as PDF.
        </p>

      </div>

      <button onClick={downloadPDF}>
        Download PDF
      </button>

    </div>
  );
}

export default App;

Important Package for PDF Generate: