以角度创建多页PDF

时间:2019-03-01 10:44:19

标签: angular pdf jspdf html2canvas

我尝试生成多页角度的PDF,找到了很多主题,但没有一个对我有真正的帮助。
这就是为什么我想提出一个新问题并分享我的解决方案。
希望它可以帮助某人。

首先,下载jsPDF和html2canvas
npm i jspdf --save
npm我html2canvas --save

然后导入到组件中

pdf.component.ts

import html2canvas from 'html2canvas';
import * as jsPDF from 'jspdf';

/** ... **/

export class PdfComponent {
  items = [{ title: 'first' }, { title: 'second' }] // Content of the pages
  counter: number
  length: number
  pdf: jsPDF

  downloadPDF() {
    this.pdf = new jsPDF('p', 'mm', 'a4') // A4 size page of PDF
    this.length = this.items.length
    this.counter = 0

    this.generatePDF()
  }

  generatePDF() {
    var data = document.getElementById('pdf' + this.counter)

    html2canvas(data, {
      scale: 3 // make better quality ouput
    }).then((canvas) => {
      this.counter++

      // Few necessary setting options
      var imgWidth = 208
      var imgHeight = (canvas.height * imgWidth) / canvas.width

      const contentDataURL = canvas.toDataURL('image/png')
      var position = 0
      this.pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)

      // Control if new page needed, else generate the pdf
      if (this.counter < this.length) {
        this.pdf.addPage()
        this.getLetter()
      } else {
        this.pdf.save('users.pdf') // Generated PDF
        return true
      }
    })
  }
}
<!-- pdf.component.html -->
<div [id]="'pdf'+i" *ngFor="let item of items; index as i">
  <h1>{{ item.title }}</h1>
  <!-- the content of one page here -->
</div>

<button (click)="downloadPDF()">
  generatePDF
</button>

注意:导出到很多文件会破坏浏览器,并为您提供
“ Debuggin连接已关闭,原因:渲染过程消失了。”

在Angular 7.2.1中进行了测试

0 个答案:

没有答案