当我运行该应用程序并单击该按钮时,PDF
看起来是空的。
我在console.log()
处寻找,画布上什么也没显示。
import { Component, OnInit } from '@angular/core';
import * as jspdf from 'jspdf';
import html2canvas from 'html2canvas';
generatePDF(){
html2canvas(document.getElementById('albaran')).then(canvas => {
// Few necessary setting options
var imgWidth = 208;
var pageHeight = 295;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
const contentDataURL = canvas.toDataURL('image/png')
let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF
var position = 0;
pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)
pdf.save('MYPdf.pdf'); // Generated PDF
});
}
}
答案 0 :(得分:0)
单击按钮后,从DOM加载元素时将花费一些时间,因此使用setTimeout即可。
import * as html2canvas from 'html2canvas';
import * as jspdf from 'jspdf';
generatePDF() {
setTimeout(() => {
const data = document.getElementById('printdiv');
html2canvas(data).then(canvas => {
// Few necessary setting options
const imgWidth = 208;
const pageHeight = 295;
const imgHeight = canvas.height * imgWidth / canvas.width;
let heightLeft = imgHeight;
const contentDataURL = canvas.toDataURL('image/png');
const pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF
let position = 0;
pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
// pdf.text(190, 294, '1');
let count = 1;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
pdf.addPage();
pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);
// pdf.text(150, 10, 'this test meaasage');
count++;
// pdf.text(190, 294, count.toString());
heightLeft -= pageHeight;
}
const date = this.datePipe.transform(new Date(), 'dd/MM/yy');
const text = 'Created At :' + date;
pdf.setTextColor(163, 163, 163);
pdf.text(10, 290, text);
// pdf.text(190, 294, count.toString());
const currentuser = this.localstorgeservice.getCurrentUser();
const url = 'URL:' + this.document.location.href;
pdf.text(10, 280, url.toString());
pdf.text(150, 290, currentuser.userid);
pdf.save(this.bankingchannelname + '.pdf'); // Generated PDF
});
}, 700);
}
答案 1 :(得分:0)
最后,我找到了解决方案。我使用jsPDF和dom-to-image库。 https://www.npmjs.com/package/jspdf
https://www.npmjs.com/package/dom-to-image
import * as jsPDF from 'jspdf';
import domtoimage from 'dom-to-image';
exportPdf(){
const div = document.getElementById('pdf');
const options = { background: 'white', height: 845, width: 595 };
domtoimage.toPng(div, options).then((dataUrl) => {
//Initialize JSPDF
const doc = new jsPDF('p', 'mm', 'a4');
//Add image Url to PDF
doc.addImage(dataUrl, 'PNG', 0, 0, 210, 340);
doc.save('pdfDocument.pdf');
}
}
答案 2 :(得分:0)
在这里,
$(document).click(function () {
domtoimage.toPng(document.body)
.then(function (blob) {
var pdf = new jsPDF('p', 'mm', 'a4');
pdf.addImage(blob,'PNG', 0, 0, 210, 225);
pdf.save("test.pdf");
that.options.api.optionsChanged();
});
});