首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用jsPDF设置适合页面宽度的图像?

如何使用jsPDF设置适合页面宽度的图像?
EN

Stack Overflow用户
提问于 2016-04-07 17:32:29
回答 13查看 168.7K关注 0票数 52

有什么办法可以解决这个问题吗?我尝试以毫米为单位设置宽度和高度。如何将其设置为全宽?

EN

Stack Overflow用户

发布于 2021-01-17 22:07:07

我的解决方案是检查需要应用什么比例(高度或宽度),这取决于pdf方向和图像大小。注意:如果不需要边距,请将边距设置为0。

代码语言:javascript
运行
复制
   const imgData = canvas.toDataURL("image/jpeg");

   const pdf = new jsPDF({
       orientation: "portrait", // landscape or portrait
       unit: "mm",
       format: "a4",
   });
   const imgProps = pdf.getImageProperties(imgData);
   const margin = 0.1;

   const pdfWidth = pdf.internal.pageSize.width * (1 - margin);
   const pdfHeight = pdf.internal.pageSize.height * (1 - margin);

   const x = pdf.internal.pageSize.width * (margin / 2);
   const y = pdf.internal.pageSize.height * (margin / 2);

   const widthRatio = pdfWidth / imgProps.width;
   const heightRatio = pdfHeight / imgProps.height;
   const ratio = Math.min(widthRatio, heightRatio);
   
   const w = imgProps.width * ratio;
   const h = imgProps.height * ratio;

   pdf.addImage(imgData, "JPEG", x, y, w, h);
票数 2
EN
查看全部 13 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36472094

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档