Home > Mobile >  jspdf is not making pdf of right size
jspdf is not making pdf of right size

Time:12-24

I am making a resume builder app in react-js. I am at the stage where when users clicks on download button the resume should be downloaded as pdf. For this purpose i am using js-pdf, but the problem is that when i click on download button the pdf generated by js-pdf is not right. Its like zoomed or the font size is too big i don't know what is the problem.

I have given the width 210mm and height 297mm to the html element who need to be converted into pdf. And below is my code to generate and download pdf

function handleDownload() {
    const doc = new jsPDF('p', 'mm', [297, 210]);
    const content = pdfRef.current
    doc.html(content, {
      callback: function (doc) {
        doc.save('newFile');
      }
    });
  }

and this is my jsx element which i want to be downloaded as pdf

<main id="classic" ref={pdfRef} className='mx-auto bg-white shadow w-[210mm] h-[297mm]'>
  <button onClick={handleDownload} className="bg-mainBlack text-white px-4 py-2 text-xs">download</button>
  {/* Rest inner elements */}
</main>

tihs is how the resume looks like in browser (please ignore the styling i have'nt styled it yet)

snapshot of browser render

this is the picture of how js-pdf make its pdf

preview of pdf

I want the pdf to be the correct size

CodePudding user response:

This can be implemented using htmltocanvas library.

async function handleDownload() {
    const contentCanvas = await html2canvas(document.getElementById("content"));
    const image = contentCanvas.toDataURL("image/png");
    var doc = new jsPDF();
    doc.addImage(image, "png", 0, 0);
    doc.save("resumse.pdf");
  }

Code Sandbox : https://codesandbox.io/s/elated-joana-veix3x?file=/src/App.js:184-452

  • Related