How to set image to fit width of the page using jsPDF?

后端 未结 11 2243
醉话见心
醉话见心 2020-12-04 21:37

Is there any way to solve this? I tried to set width and height in mm. How can I set it to full-width?

11条回答
  •  孤街浪徒
    2020-12-04 22:03

    This is how I've achieved in Reactjs.

    Main problem were ratio and scale If you do a quick window.devicePixelRatio, it's default value is 2 which was causing the half image issue.

    const printDocument = () => {
      const input = document.getElementById('divToPrint');
      const divHeight = input.clientHeight
      const divWidth = input.clientWidth
      const ratio = divHeight / divWidth;
    
      html2canvas(input, { scale: '1' }).then((canvas) => {
        const imgData = canvas.toDataURL('image/jpeg');
        const pdfDOC = new JSPDF("l", "mm", "a0"); //  use a4 for smaller page
    
        const width = pdfDOC.internal.pageSize.getWidth();
        let height = pdfDOC.internal.pageSize.getHeight();
        height = ratio * width;
    
        pdfDOC.addImage(imgData, 'JPEG', 0, 0, width - 20, height - 10);
        pdfDOC.save('summary.pdf');   //Download the rendered PDF.
      })
    }
    

提交回复
热议问题