引入插件 jsPdf.js 以及 html2canvas.js,具体文件可上github找,实测可行
html2canvas(document.getElementById("downBox")).then(function (canvas) {
var imgData = canvas.toDataURL();
var arrDPI = js_getDPI();//获取显示器dpi
var dpiX = 96;
var dpiY = 96;
if (arrDPI.length > 0) {
dpiX = arrDPI[0];
dpiY = arrDPI[1];
}
var doc = new jsPDF('l', 'in', [(canvas.width + 10) / dpiX, (canvas.height + 10) / dpiY]);
doc.addImage(imgData, 'png', 7/dpiX,5/dpiY);
var pdfName = "12134";
doc.save(pdfName + ".pdf");
});
//获取显示器的dpi
function js_getDPI() {
var arrDPI = new Array();
if (window.screen.deviceXDPI != undefined) {
arrDPI[0] = window.screen.deviceXDPI;
arrDPI[1] = window.screen.deviceYDPI;
}
else {
var tmpNode = document.createElement("DIV");
tmpNode.style.cssText = "width:1in;height:1in;position:absolute;left:0px;top:0px;z-index:99;visibility:hidden";
document.body.appendChild(tmpNode);
arrDPI[0] = parseInt(tmpNode.offsetWidth);
arrDPI[1] = parseInt(tmpNode.offsetHeight);
tmpNode.parentNode.removeChild(tmpNode);
}
return arrDPI;
}