How to create PDFs from React components [client side solution]

Base photo by Lauren Richmond on Unsplash

Generating a pdf on the client side is a 3 step process :

  • Convert the DOM into svg
  • Convert the svg into png
  • Convert the png into pdf
Converting html to svg
const input = document.getElementById('divIdToPrint');html2canvas(input)
.then((canvas) => {
const imgData = canvas.toDataURL('image/png');
})
;
html2canvas(input)
.then((canvas) => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF();
pdf.addImage(imgData, 'PNG', 0, 0);
pdf.save("download.pdf");

});
;
Stackblitz ide with working code and components; https://stackblitz.com/edit/react-4798tj

If you liked this article and want to stay updated, follow me on: Medium, Github or Twitter

Ta

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Shivek Khurana

Shivek Khurana

1.1K Followers

🏋🏻‍♂️ Founder — Building Meta Blocks — The NFT evolution protocol | 🔫 Talks about 📜 code, 🏛 crypto, 🕸 web3 and 🪖 ed-tech | 👼🏼 Angel Investor | W