Warning: mysqli_connect(): (HY000/1040): Too many connections in /var/www/webnuz/inc/base_connector.php on line 2 Failed to connect to MySQL: Too many connections Warning: mysqli_query() expects parameter 1 to be mysqli, boolean given in /var/www/webnuz/inc/func_sysvars.php on line 5 Converting JSX to downloadable pdf in react - by Dev To
Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 25, 2022 08:45 am GMT

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-examplecd jsx-to-pdf-examplenpm install html2pdf.js 

App.js

import html2pdf from 'html2pdf.js';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;

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';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;

Final Demo
demo


Bonus (Fix Warnings)

You might 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


Original Link: https://dev.to/kazmi066/converting-jsx-to-downloadable-pdf-in-react-20bh

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To