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

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

    If you want a dynamic sized image to automatically fill the page as much as possible and still keep the image width/height-ratio, you could do as follows:

    let width = doc.internal.pageSize.getWidth()
    let height = doc.internal.pageSize.getHeight()
    
    let widthRatio = width / canvas.width
    let heightRatio = height / canvas.height
    
    let ratio = widthRatio > heightRatio ? heightRatio : widthRatio
    
    doc.addImage(
      canvas.toDataURL('image/jpeg', 1.0),
      'JPEG',
      0,
      0,
      canvas.width * ratio,
      canvas.height * ratio,
    )
    

提交回复
热议问题