Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to download React component as PDF with High Resolution? #3009

Open
olivermen opened this issue Dec 19, 2022 · 1 comment
Open

How to download React component as PDF with High Resolution? #3009

olivermen opened this issue Dec 19, 2022 · 1 comment

Comments

@olivermen
Copy link

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.

https://stackoverflow.com/questions/44989119/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>
@olivermen
Copy link
Author

olivermen commented Dec 20, 2022

I found a solution. I should control the size of canvas using scale.

   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");
    });

I wish this help you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant