一、安装
npm install --save jspdf
npm install --save html2canvas
二、代码部分
HTML
<div id="pdfbox">
pdf内容, html
</div>
<button class="btn btn-cyan" (click)="ExportPDF()">
<i class="fa fa-plus-circle"></i>
<span>导出</span>
</button>
TS
import { Component } from '@angular/core';
import jspdf from "jspdf";
import html2canvas from "html2canvas";
@Component({
selector: 'app-canvas-pdf',
templateUrl: './canvas-pdf.component.html',
styleUrls: ['./canvas-pdf.component.less']
})
export class CanvasPdfComponent {
element: any;
pdfTitle: string = '你想要的保存pdf文件的名字';
ExportPDF() {
this.element = document.getElementById("pdfbox");
html2canvas(this.element, {
logging: false,
}).then((canvas) => {
let pdf: any = new jspdf("p", "mm", "a4");
let ctx: any = canvas.getContext("2d");
let a4w: number = 190;
let a4h: number = 260;
let imgHeight: number = Math.floor((a4h * canvas.width) / a4w);
let renderedHeight: number = 0;
while (renderedHeight < canvas.height) {
let page: any = document.createElement("canvas");
page.width = canvas.width;
page.height = Math.min(imgHeight, canvas.height - renderedHeight);
let a: any = page.getContext("2d");
a.putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0);
pdf.addImage(page.toDataURL("image/jpeg", 1.0), "JPEG", 10, 10, a4w, Math.min(a4h, (a4w * page.height) / page.width));
renderedHeight += imgHeight;
if (renderedHeight < canvas.height) {
pdf.addPage();
}
}
pdf.save(`${this.pdfTitle}.pdf`);
});
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/2f4336abca7447168565e8485e4ecade.png)