An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
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.
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;
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To