【发布时间】:2021-06-09 12:00:39
【问题描述】:
我目前正在使用 jspdf 和 AutoTable plugin 创建 pdf 文件。
我的计划是创建一个这样的表: 我将图像作为本地 url,我正在尝试使用新图像将它们添加到 pdf 中,并将它们作为 .src 添加到图像中。 当我直接用图像运行 jspdf.addImage 函数时,图像正确显示。
但我正在努力让正确的缩放比例起作用。所以我想使用图像的宽度和高度属性,但要让它工作,你需要等待图像加载。
我尝试使用 onload 函数,但它通常会停止渲染表格,因为它会跳过该函数并在图像加载之前继续下一个表格。
如果您对如何使这样的事情起作用有任何建议,我们将不胜感激。这些图像都有不同的分辨率,需要按比例缩小以适合表格。我将在下面粘贴我的工作代码(但没有高度和宽度缩放)。
doc.autoTable({
head: [{comments: 'Photos'}],
body: body,
styles: {
lineColor: [0, 0, 0],
lineWidth: 0.4,
},
headStyles: {
fillColor: [191, 191, 191],
textColor: [0, 0, 0],
},
didDrawCell: function (data) {
if (data.section === 'body') {
console.log(data);
const image = new Image();
// image.onload = function() {
// console.log(this);
// const width = this.width;
// const height = this.height;
// console.log({width, height})
// doc.addImage(
// this,
// 'JPEG',
// data.cell.x + 5,
// data.cell.y + 2,
// )
// }
image.src = QuestionPhotos.link(photosObject[data.cell.raw])
doc.addImage(
image,
'JPEG',
data.cell.x + 5,
data.cell.y + 2,
)
}
}
这段代码中被注释掉的部分是我在加载图像后添加图像的另一次尝试,但这使得图像根本没有出现在 pdf 中。
【问题讨论】:
-
您是否尝试在 willDrawCell 或 didParseCell 挂钩中添加图像?
标签: image pdf jspdf jspdf-autotable