Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML to PDF convert in react js using jsPDF not working

after executing the below function getting error In function, simple HTML div tags are inserted but still not working

exportPDF function will call when one button will click to generate pdf

Function

const exportPDF = () => {
   let element=(<div style={{display: "flex",flexWrap:"wrap"}}>Sample Text</div>)
   const doc = new jsPDF();
   doc.html(element, {
       callback: function (doc) {
            doc.save('sample.pdf');
         }
     });
}

Error

jspdf.es.min.js:128 Uncaught (in promise) Error: Unknown source type.
    at Promise.<anonymous> (jspdf.es.min.js:128:1)

I'm using npm package of jsPDF ("jspdf": "^2.4.0")

Unable to figure out why doc.html not working in this code

like image 936
Yuvraj Chaudhari Avatar asked Dec 07 '25 10:12

Yuvraj Chaudhari


1 Answers

If you are using reactjs just convert your element to html and then pass it to the jspdf like below

import jsPDF from "jspdf";
import ReactDOMServer from "react-dom/server";

export default function App() {
  const exportPDF = () => {
    let element = (
      <div style={{ display: "flex", flexWrap: "wrap" }}>Sample Text</div>
    );
    const doc = new jsPDF("p", "pt", "letter");
    doc.html(ReactDOMServer.renderToString(element), {
      callback: function (doc) {
        doc.save('sample.pdf');
      }
    });
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={exportPDF}>export</button>
    </div>
  );
}
like image 135
Murali N Avatar answered Dec 08 '25 23:12

Murali N



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!