gpt4 book ai didi

angular - 以 Angular 创建多页PDF

转载 作者:行者123 更新时间:2023-12-05 07:25:17 25 4
gpt4 key购买 nike

如何在angular中生成多个PDF页面

最佳答案

首先,下载jsPDF和html2canvas
npm i jspdf --保存
npm i html2canvas --保存

然后导入到组件中

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>

注意:导出太多文件会破坏浏览器并给你一个
“调试连接已关闭,原因:渲染进程消失。”

在 Angular 7.2.1 中测试

关于angular - 以 Angular 创建多页PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54942979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com