angular - 如何让图像在 Angular 的 jspdf 自动表中工作
问题描述
我创建了一个 Angular 项目,并且正在使用 jsPDF autotable 导出一个 HTML 表。该表导出正常,除了我试图将图像也导出到表中。
我正在使用 html2canvas 将 div 元素转换为效果很好的图像。当我运行 ng serve 时,图像出现在 HTML 表格中,但是当我导出为 PDF 时,图像应该是空的表格单元格。
我在这里按照这个实时示例尝试让图像出现在打印的表格中:https ://codepen.io/someatoms/pen/vLYXWB 但我遇到了一些我无法弄清楚的错误。
以下是我的代码的相关部分(一些名称更改为通用名称):
组件.html
<button id="downloadButton" type="button" (click)="downloadPDF()">
Download PDF
</button>
<table id="my-table">
<thead>
<tr>
<th colspan="5">Title</th>
</tr>
<tr>
<th colspan="5">Subtitle</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5" id="my-image">
<!-- This is where the image will be injected -->
</td>
</tr>
</tbody>
<thead>
<tr>
<th>Heading 1</th>
<th>Heading 2</th>
<th>Heading 3</th>
<th>Heading 4</th>
<th>Heading 5</th>
</tr>
</thead>
<tr *ngFor="let thing of things">
<td>{{ thing.one }}</td>
<td>{{ thing.two }}</td>
<td>{{ thing.three }}</td>
<td>{{ thing.four }}°</td>
<td>{{ thing.five }}m</td>
</tr>
</table>
组件.ts
downloadPDF(){
this.convertImage();
let date = new Date();
date.getTime();
let dateString = String(date + '.pdf')
const doc = new jspdf.jsPDF()
autoTable(doc, { html: '#my-table', bodyStyles: {minCellHeight: 15},
didDrawCell: function(data) {
if (data.row.index === 2 && data.cell.section === 'body') {
var td = data.cell.raw;
var img = td.getElementsByTagName('img')[0];
var dim = data.cell.height - data.cell.padding('vertical');
var textPos = data.cell.textPos;
doc.addImage(img.src, textPos.x, textPos.y, dim, dim);
}
}}, )
doc.save(dateString)
};
convertImage() {
html2canvas(document.getElementById("my-div")).then(function (canvas) {
const converted = canvas.toDataURL("image/jpg", 0.9);
var img = document.createElement('img');
img.src = converted;
document.getElementById('my-image').appendChild(img);
});
}
我在“ var img = td.getElementsByTagName('img')[0]; ”中遇到的两个主要问题
- “HTMLTableCellElement | 类型”上不存在属性“getElementsByTagName” 细胞输入'。“字符串”类型上不存在属性“getElementsByTagName”.ts(2339)
另一个是它下面的 2 行,位于“ var textPos = data.cell.textPos; ”
- 类型“Cell”.ts(2339) 上不存在属性“textPos”
我在这里错过了什么,我发布的链接中的实时示例有我没有?
解决方案
推荐阅读
- swift - 为数组扩展选择类型
- python - 如何格式化二维数组以适应输入文件中的 Soduku 板。Python
- python - 在 Django 项目模板中生成音频文件
- twilio - 为什么 Twilio 消息响应中有多个 MessageSID 排列?
- html - 验证正则表达式
- javascript - 与第一个对象进行比较时,如何获取第二个对象数组的所有属性?
- python - Python:将日期格式 YYYY-mm-dd 转换为带有缩写月份的 dd-MON-yyyy
- javascript - 如何使用 V-Model 检查 Vue.js 中的单选按钮?
- django - GenericViews - 并在 URL 中推送模型名称
- image - 尝试从图像的一行中绘制值时在 Matlab 中出错