DEV Community

Cover image for Converting JSX to downloadable pdf in react
Awais Abbas
Awais Abbas

Posted on • Updated on

Converting JSX to downloadable pdf in react

A simple demonstration to convert JSX to PDF in react with the help of Html2pdf.js library.

Create React Project and install packages

npx create-react-app jsx-to-pdf-example
cd jsx-to-pdf-example
npm install html2pdf.js 
Enter fullscreen mode Exit fullscreen mode

App.js

import html2pdf from 'html2pdf.js/dist/html2pdf.min';
import './App.css';

function App() {
  const pdfJSX = () => {
    return (
      <>
        <h1>JSX to PDF Convert Example</h1>
        <h2>Hello React</h2> 
      </>
    )
  }

  const printHandler = () => {
    const printElement = pdfJSX();
    console.log(printElement);

    html2pdf().from(printElement).save();
  }

  return (
    <div className="App">
      <button onClick={printHandler}>Print</button>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

After clicking on print button here, you will notice that nothing is happening. Here is what console log would show you in dev tools of the browser.

DevTools output

So basically html2pdf.js package is expecting simple HTML and nothing is happening.

Lets convert JSX to HTML first using ReactDOMServer and then pass that to html2pdf function.

App.js

import ReactDOMServer from 'react-dom/server';
import html2pdf from 'html2pdf.js/dist/html2pdf.min';
import './App.css';

function App() {
  const pdfJSX = () => {
    return (
      <>
        <h1>JSX to PDF Convert Example</h1>
        <h2>Hello React</h2> 
      </>
    )
  }

  const printHandler = () => {
    const printElement = ReactDOMServer.renderToString(pdfJSX());
    // const printElement = pdfJSX();

    html2pdf().from(printElement).save();
  }

  return (
    <div className="App">
      <button onClick={printHandler}>Print</button>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Final Demo
demo


Bonus (Fix Warnings)

If you notice that there are some warnings on the terminal regarding the package and to fix them, I only found this solution.

  • Create .env.development file inside root directory (outside /src)
  • Add this line to the file: GENERATE_SOURCEMAP=false and warnings would be gone.


Library Reference:
https://www.npmjs.com/package/html2pdf.js/v/0.9.0
Peace ✌️

Top comments (0)