1. 在 Angular 项目中安装 html2canvas
和 jspdf
库。您可以使用以下命令在项目中安装这两个库:
npm install html2canvas jspdf --save
在 Angular 应用程序中安装 jsreport-client
和 jsreport-chrome-pdf
库并将其添加到 package.json
文件的依赖项列表中
2. 在 Angular 组件中导入这两个库:
import html2canvas from 'html2canvas';
import { jsPDF } from 'jspdf';
3. 在组件模板中创建要转换为 PDF 的 HTML 元素。
<div id="pdf-content">
<h1>{{ title }}</h1>
<p>{{ content }}</p>
<img src="{{ imageUrl }}" />
</div>
<button (click)="downloadPDF()">Download PDF</button>
4. 在组件中创建一个方法,该方法将使用 html2canvas
将组件的 HTML 内容转换为 Canvas 元素,并将其添加到 jsPDF
实例中,最后将 PDF 文件下载到本地。
import { Component, ElementRef, ViewChild } from '@angular/core';
import html2canvas from 'html2canvas';
import { jsPDF } from 'jspdf';
@Component({
selector: 'app-pdf-generator',
templateUrl: './pdf-generator.component.html',
styleUrls: ['./pdf-generator.component.css']
})
export class PdfGeneratorComponent {
title = 'My PDF Document';
content = 'This is the content of my PDF document.';
imageUrl = 'https://www.example.com/my-image.png';
downloadPDF() {
const element = document.getElementById('pdf-content');
html2canvas(element).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF();
pdf.addImage(imgData, 'PNG', 0, 0);
pdf.save('my-pdf-document.pdf');
});
}
}
在这个方法中,我们首先使用 document.getElementById
获取要转换为 PDF 的 HTML 元素。然后,我们使用 html2canvas
将该元素转换为 Canvas 元素。接下来,我们使用 jsPDF
创建一个新的 PDF 实例,并使用 addImage
将 Canvas 元素添加为 PDF 页面。最后,我们使用 save
将 PDF 保存到本地。
5. 最后,在组件的模板中添加一个按钮,并调用 downloadPDF
方法。
<div id="pdf-content">
<h1>{{ title }}</h1>
<p>{{ content }}</p>
<img src="{{ imageUrl }}" />
</div>
<button (click)="downloadPDF()">Download PDF</button>
点击按钮调用 downloadPDF
方法,并生成并下载 PDF 文件。