粗略实现导出,细节后续再补充。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./js/html2canvas.js"></script>
<script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>
</head>
<body>
<div id="root">
<h3>名片</h3>
<div class="person">
<img style="width: 600px; height: 400px;"
src="https://img0.baidu.com/it/u=3976250177,3245140550&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=675" alt="">
</div>
</div>
<button id="downloadImg">点击</button>
</body>
<script >
const {jsPDF} = jspdf
let dom = document.getElementById("downloadImg");
dom.onclick = function () {
// 实现保存为图片的第一步:html转为canvas
html2canvas(document.getElementById("root"), {
useCORS: true,
scale: window.devicePixelRatio,
height: 600,
width: 800,
// backgroundColor: null
}).then(function (canvas) {
const contentWidth = canvas.width;
const contentHeight = canvas.height;
let dataImg = canvas.toDataURL();
console.log('content',contentWidth,contentHeight);
//方向默认竖直,尺寸ponits,横向l
//格式a4[595.28,841.89], 单位pt
var doc = new jsPDF('p', 'mm', [210,297])
doc.addImage(dataImg, 'PNG', 10, 10, 210, 297);
doc.save('a4.pdf');
});
}
</script>
</html>