折腾半天,找到两种。
1.通过html2canvas和jspdf生成pdf
因为通过canvas做中介,所以缺点是很慢。
const htmlString=`
<div>
<div>
123
</div>
</div>
`;
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(htmlString, 'text/html');
const iframe= document.createElement("iframe");
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(htmlDoc.body.outerHTML);
iframe.contentWindow.document.close();
html2canvas(iframe.contentWindow.document.body).then(function(canvas) {
const pdf = new jsPDF(undefined, 'pt', 'a4');
pdf.addImage(canvas.toDataURL('image/jpeg'), 'JPEG', 0, 0, pdf.internal.pageSize.width, canvas.height * pdf.internal.pageSize.width / canvas.width);
pdf.save('example.pdf');
document.body.removeChild(iframe)
});
2.通过浏览器的print方法
推荐用这种方式。
function htmlToPdf(htmlString) {
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
var doc = iframe.contentWindow.document;
doc.body.innerHTML=htmlString
var win = iframe.contentWindow;
win.print();
document.body.removeChild(iframe)
}
const htmlString=`
<div>
<div>
123
</div>
</div>
`;
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(htmlString, 'text/html');
const htmlString=htmlDoc.body.innerHTML
htmlToPdf(htmlString)