如何将Angular:HTML转换为PDF
我正在使用Angular,我想将表格从html转换为pdf,这是我在component.ts中的代码:如何将Angular:HTML转换为PDF,angular,typescript,jspdf,html-to-pdf,Angular,Typescript,Jspdf,Html To Pdf,我正在使用Angular,我想将表格从html转换为pdf,这是我在component.ts中的代码: downloadPDF() { const doc = new jsPDF(); const specialElememtHandlers = { '#editor'(element, renderer) { return true; } }; doc.fromHTML(this.content.nati
downloadPDF() {
const doc = new jsPDF();
const specialElememtHandlers = {
'#editor'(element, renderer) {
return true;
}
};
doc.fromHTML(this.content.nativeElement.innerHTML, 15, 15, {
width: 190,
elementHandlers: specialElememtHandlers
});
doc.save('test.pdf');
}
我的html代码是:
<button (click)="downloadPDF()">Save as PDF</button>
另存为PDF
实际上我可以下载pdf,但它是完全白色的。您可以使用“PrintJS”库将html模板转换为pdf。
首先安装此软件包 npm安装jspdf 并安装html2canvas软件包 npm安装html2canvas 使用Import语句将其导入到我们的组件中
import * as jspdf from 'jspdf';
import html2canvas from 'html2canvas';
在TS代码中:
import { Component, OnInit, ElementRef ,ViewChild} from '@angular/core';
import * as jspdf from 'jspdf';
import html2canvas from 'html2canvas';
@Component({
selector: 'app-htmltopdf',
templateUrl: './htmltopdf.component.html',
styleUrls: ['./htmltopdf.component.css']
})
export class HtmltopdfComponent{
public captureScreen()
{
var data = document.getElementById('contentToConvert'); //Id of the table
html2canvas(data).then(canvas => {
// Few necessary setting options
let imgWidth = 208;
let pageHeight = 295;
let imgHeight = canvas.height * imgWidth / canvas.width;
let heightLeft = imgHeight;
const contentDataURL = canvas.toDataURL('image/png')
let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF
let position = 0;
pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)
pdf.save('MYPdf.pdf'); // Generated PDF
});
}
}
听说是
希望这将有助于首先安装此软件包
npm安装jspdf
npm安装html2canvas@1.0.0-alpha.12//使用此html2canvas版本。
使用Import语句(app.component.ts)将其导入到我们的组件中
从“jspdf”导入*为jspdf;
从“html2canvas”导入html2canvas;
添加app.component.html
你好,世界!
制作pdf
添加app.component.ts
Screen()
{
var data=document.getElementById('content');
html2canvas(数据)。然后(画布=>{
//几乎没有必要的设置选项
var imgWidth=208;
var pageHeight=295;
var imgHeight=canvas.height*imgWidth/canvas.width;
var heightLeft=imgHeight;
const contentDataURL=canvas.toDataURL('image/png')
让pdf=newJSPDF('p','mm','a4');//a4大小的pdf页面
var位置=0;
addImage(contentDataURL,'PNG',0,位置,imgWidth,imgHeight)
pdf.save('MYPdf.pdf');//生成的pdf
});
}
您可以更新您的表格吗?它是动态的还是静态的?如果它是一个大小可变的div,它可能会重复吗?@UlisesCT您仍然面临这个问题吗?谢谢。你知道如何发送文档而不是下载吗?