vue3生成pdf

vue3生成pdf # 安装稳定版本 npm install html2canvas1.4.1 jspdf1.5.3divdiv refcontentRef classcertificate-contentdiv classtitle标题/divdiv内容/div/divdiv classbottom-btnbutton clickdownLoadPDF生成PDF/button/divdivscript langts setupimport {ref,reactive,PropType,watch,defineProps,defineEmits,onMounted,computed,} from vue;const contentRef ref();const loading ref(false);import html2canvas from html2canvas;import jsPDF from jspdf;const downLoadPDF async () {if (!contentRef.value) {console.log(contentRef.value 为空);return;}loading.value true;try {//1. 将DOM节点转换为Canvas图像const canvas await html2canvas(contentRef.value, {scale: 2, //提高分辨率让PDF更清晰backgroundColor: #fff,logging: false,useCORS: true, //如果内容中有图片需要开启跨域支持});const imgData canvas.toDataURL(image/png);//2. 创建 PDF 文档A4纸尺寸纵向const pdf new jsPDF({orientation: portrait,unit: mm,format: a4,});//3.计算图像在PDF中的尺寸const pdfWidth pdf.internal.pageSize.getWidth(); // A4 宽度约 210mmconst pdfHeight pdf.internal.pageSize.getHeight(); // A4 高度约297mmconst imgWidth pdfWidth;const imgHeight (canvas.height * imgWidth) / canvas.width;//4. 将图像添加到 PDF 中pdf.addImage(imgData, PNG, 0, 0, imgWidth, imgHeight, undefined, FAST);//5. 保存PDF,pdf.save(XXX.pdf);} catch (err) {console.log(生成PDF失败, err);} finally {loading.value false;}};/scriptstyle scoped.certificate-content {padding: 80px;font-family: SimSun, 宋体, serif;font-size: 16px;white-space:pre-wrap;white-space:pre-line;}.title{text-align: center;margin-bottom: 100px;font-size:30px;}.bottom-btn{text-align: right;}/style