首页 > 解决方案 > 如何让图像在 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]; ”中遇到的两个主要问题

另一个是它下面的 2 行,位于“ var textPos = data.cell.textPos;

我在这里错过了什么,我发布的链接中的实时示例有我没有?

标签: angulartypescriptjspdfhtml2canvasjspdf-autotable

解决方案


推荐阅读