安装依赖
pnpm i html2canvas
pnpm i jspdf
实践代码
<template>
<div class="box" ref="boxRef">
<h1>啊是多久啊武力打击啊物理</h1>
<h2>带来的家务劳动</h2>
<h3>lsfjseflisejf</h3>
daldawdawjdliawjd
</div>
<button @click="btn('pdf')">按钮</button>
</template>
<script setup lang="ts">
import {jsPDF} from 'jspdf';
import html2canvas from 'html2canvas';
import {ref} from 'vue';
let boxRef = ref().value;
/**
* type 类型
* png:下载png图片
* pdf:下载pdf图片
*/
const btn = async (type)=>{
const width = boxRef.offsetWidth;
const height = boxRef.offsetHeight;
let canvas = await html2canvas(boxRef, {
scale: 1,
width,
height,
backgroundColor: null,
useCORS: true,
})
let imgUrl = null;
switch (type){
case 'png':
imgUrl = canvas.toDataURL(`image/png`);
let link = document.createElement("a");
link.style.display = "none";
link.href = imgUrl;
link.setAttribute("download", '测试.png'); // 文件名
document.body.appendChild(link);
link.click();
document.body.removeChild(link); // 下载完成移除元素
window.URL.revokeObjectURL(imgUrl); // 释放掉blob对象
break;
case 'pdf':
imgUrl = canvas.toDataURL('image/png');
/**
* 参数1(规模):p为横向、l为纵向
* 参数2(单位):默认为pt
* 参数3(纸张大小):默认为A4纸大小
*/
const doc = new jsPDF();
doc.addImage(imgUrl, 'png', 10, 10);
doc.save(`测试.pdf`);
break;
}
}
</script>
<style>
.box{
border: 1px solid;
width: 500px;
}
</style>