使用 jsPDF 和 html2Canvas 在 Angular 中创建多页 PDF

问题描述 投票:0回答:1

我有一个 应用程序,左侧有 (3) 个项目的列表以及它们各自的预览

有一个

Generate PDF
按钮,单击该按钮即可下载包含所有 (3) 个预览的 PDF。

我尝试遍历所有预览,当预览列表项时,我将 DOM 收集到

array (service property)
中。当所有项目的遍历完成后,我循环遍历集合
array (service property)
并尝试生成 PDF。

我希望生成一个 PDF,并捕获所有列出的项目预览。 但问题是 生成的 PDF 只有一个空白页,这不是预期的。

我尝试使用 2 种不同的方法来捕获 HTML,但没有成功。

  1. 使用传统的
    document.getElementById()
  2. 使用
    @ViewChild()
    (stackblitz 示例现在包含此实现)

要完成此要求,这里缺少什么?

angular pdf-generation jspdf html2canvas
1个回答
0
投票

有几个问题:

  • 您将 HTML 字符串而不是 HTML 元素发送到
    html2canvas
  • 在图像完成之前保存 PDF
  • 您不添加页面做PDF

修复方法如下:

  • 您需要将 HTML 元素发送到
    html2canvas
    ,而不是字符串:
this.addSnapToPdf(preview);
  • 您需要在每个图像后添加页面到 pdf:
this._pdf.addPage()
  • 最后,图像完成后保存pdf。一种快速而肮脏的方法是通过跟踪循环中的索引来发送
    isLast
    标志:
const isLast = idx + 1 == this._appService.allPreviews.length;
this.addSnapToPdf(preview, isLast);

试试这个:带有代码和注释说明的固定方法:

  generatePdf() {
    this._appService.allPreviews.forEach((preview, idx) => {
      // send the flag indicating to save pdf
      const isLast = idx + 1 == this._appService.allPreviews.length;
      console.log('preview', idx + 1, preview);
      // send html element and last flag
      this.addSnapToPdf(preview, isLast);
    });
  }

  addSnapToPdf(page: HTMLElement, isLast: boolean) {
    html2canvas(page, { scale: 2 }).then((canvas: any) => {
      this._pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
      // if it's last, save, else add new page
      if (isLast) this._pdf.save('AllPreviews.pdf');
      else this._pdf.addPage();
    });
  }

stackblitz 演示


© www.soinside.com 2019 - 2024. All rights reserved.