Converting JSX to downloadable pdf in react
Awais Abbas
Posted on June 25, 2022
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
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;
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/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;
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 ✌️
💖 💪 🙅 🚩
Awais Abbas
Posted on June 25, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.