HTML2Canvas does not render full div, only what is visible on screen?

前端 未结 10 1867
甜味超标
甜味超标 2020-12-13 04:02

I\'m trying to use HTML2Canvas to render the contents of a div. Here is the code:

var htmlSource = $(\'#potenzial-page\')[0];

$(\'#btn\').on(\"click\", fun         


        
10条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 04:22

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

提交回复
热议问题