Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download React Component as PDF with High Resolution?

I have been building a bottle label making application using React. People are able to create customized labels as they want. I have already add the functionality to let the users download the results in the form of a PDF.

Generating a PDF file from React Components

I implemented download React component to PDF by reference above link. html2canvas & jsPDF. Btw there's a quality issue. If I zoom in the downloaded PDF file, the quality is not good. (React component size is 380px * 380px).

Instead of it, if I zoomin(500%) the chrome browser and then download PDF, the quality is very good even zoom in on PDF reader(Foxit Reader or Chrome PDF Viewer). Maybe the PDF resolution that downloaded using the html2canvas & jsPDF seems like according on component size.

So I have to ask customers to download PDF after they zoomin the browser(500%) if they want PDF with high resolution? lol. That's not. I read the several articles about downloading PDF but not find solution yet.

Is there any method to implement above function as code?

As reference, this is my code which download pdf using html2canvas & jsPDF.

const printRef = React.useRef<HTMLDivElement>(null);

...

const handleDownloadPdf = async () => {
  const element: any = printRef.current;
  const canvas = await html2canvas(element);
  const data = canvas.toDataURL("image/png");
  
  const pdf = new jsPDF("portrait", "px", [380, 380]);

  const pdfWidth = pdf.internal.pageSize.getWidth();
  const pdfHeight = pdf.internal.pageSize.getHeight();

  pdf.addImage(data, "PNG", 0, 0, pdfWidth, pdfHeight);
  pdf.save("label.pdf");
};

...

<div ref={printRef} style={{ height: "380px" }}>
    <Label/>
</div>
like image 461
Whimsy Cat Avatar asked Nov 02 '25 07:11

Whimsy Cat


1 Answers

I found another solution. I should control the size of canvas.

   html2canvas(element, {
      scale: 5,
    }).then(function (canvas) {
      var data = canvas.toDataURL("image/png");
      pdf.addImage(data, "PNG", 0, 0, pdfWidth, pdfHeight);
      pdf.save("label.pdf");
    });
like image 68
Whimsy Cat Avatar answered Nov 04 '25 21:11

Whimsy Cat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!