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

后端 未结 11 2226
醉话见心
醉话见心 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:09

    Solution for all screen sizes and dynamic orientation:

    import html2canvas from 'html2canvas'
    import jsPDF from 'jspdf'
    
    export default async function downloadComponentInPDF(Component: HTMLElement) {
      await html2canvas(Component).then((canvas) => {
        const componentWidth = Component.offsetWidth
        const componentHeight = Component.offsetHeight
    
        const orientation = componentWidth >= componentHeight ? 'l' : 'p'
    
        const imgData = canvas.toDataURL('image/png')
        const pdf = new jsPDF({
        orientation,
        unit: 'px'
      })
    
        pdf.internal.pageSize.width = componentWidth
        pdf.internal.pageSize.height = componentHeight
    
        pdf.addImage(imgData, 'PNG', 0, 0, componentWidth, componentHeight)
        pdf.save('download.pdf')
      })
    }
    

提交回复
热议问题