Convert any HTML or React Component to PDF and Save It In Browser in 2023

I found it very, very annoying to figure out how to make a PDF out of a page using html2canvas, jsPDF, and React in 2023. Hope that this article can help whoever is struggling with the generated PDF being cut off, blurry, or whatever issues are going on with this.

All the articles I found on StackOverflow reference using jsPDF and html2canvas are all from 5+ years ago, using the old deprecated API. This dev.to article I found from 2021 is also already out of date.

In this article, I'm using html2canvas 1.4.1 and jsPDF 2.5.1.

  const onClick = async () => {
     const parent = document.getElementById("parent");
      if (!parent) return;
      const canvas = await html2canvas(parent);
      const imgData = canvas
        .toDataURL("image/jpeg")
        .replace("image/jpeg", "image/octet-stream");
      const pdf = new jsPDF("portrait", "px", "a4");
      pdf.addImage(imgData, "JPEG", 10, 10, 0, 0);
      pdf.save(`generated.pdf`);
  };

Alot of very, very old articles use the deprecated jsPDF addImage that only accepts 4 inputs: imageData, format, x, and y. The latest version of jsPDF requires 2 more parameters: height and width.

I tried many ways to get this to work and found that some folks had success following this SO Answer.

I tried this but my generated PDF kept getting cut off. I set the height and width to zero which I think makes it essentially act as "auto" for jsPDF. This worked for mobile + desktop screenshots of the same component, which was a huge sigh of relief after 2 days of toiling.

Subscribe to winnie's homebase

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe