更新时间:2023-02-16 21:49:58
到目前为止,我想出的***解决方案.
Best possible solution I could come up with till now.
您必须从npm安装以下软件包
You would have to install the below packages from npm
import * as jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
htmltoPDF()
{
// parentdiv is the html element which has to be converted to PDF
html2canvas(document.querySelector("#parentdiv")).then(canvas => {
var pdf = new jsPDF('p', 'pt', [canvas.width, canvas.height]);
var imgData = canvas.toDataURL("image/jpeg", 1.0);
pdf.addImage(imgData,0,0,canvas.width, canvas.height);
pdf.save('converteddoc.pdf');
});
}
更新:
提出另一种解决方案.我无法将其分解为A4大小的页面,但可以制作一个pdf文件.
Came up with another solution. I wasn't able to break it down into A4 size pages, but I was able to make a single pdf file.
包装:
import domtoimage from 'dom-to-image';
import * as jsPDF from 'jspdf';
downloadPDF()
{
var node = document.getElementById('parentdiv');
var img;
var filename;
var newImage;
domtoimage.toPng(node, { bgcolor: '#fff' })
.then(function(dataUrl) {
img = new Image();
img.src = dataUrl;
newImage = img.src;
img.onload = function(){
var pdfWidth = img.width;
var pdfHeight = img.height;
// FileSaver.saveAs(dataUrl, 'my-pdfimage.png'); // Save as Image
var doc;
if(pdfWidth > pdfHeight)
{
doc = new jsPDF('l', 'px', [pdfWidth , pdfHeight]);
}
else
{
doc = new jsPDF('p', 'px', [pdfWidth , pdfHeight]);
}
var width = doc.internal.pageSize.getWidth();
var height = doc.internal.pageSize.getHeight();
doc.addImage(newImage, 'PNG', 10, 10, width, height);
filename = 'mypdf_' + '.pdf';
doc.save(filename);
};
})
.catch(function(error) {
// Error Handling
});
}