vue3生成pdf

复制代码
# 安装稳定版本
npm install html2canvas@1.4.1 jspdf@1.5.3

<div>

<div ref="contentRef" class="certificate-content">

<div class="title">标题</div>

<div>内容</div>

</div>

<div class="bottom-btn">

<button @click="downLoadPDF">生成PDF</button>

</div>

<div>

<script lang="ts" setup>

import {

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 宽度约 210mm

const pdfHeight = pdf.internal.pageSize.getHeight(); // A4 高度约297mm

const 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;

}

};

</script>

<style 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>

相关推荐
子兮曰3 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰3 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万3 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝3 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
A黄俊辉A3 天前
uniapp webview中实现 app和内嵌的H5双向通信
vue.js·json
三十而立洋3 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁3 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
李少兄3 天前
JavaScript 隐式全局变量解析
javascript
honkun63 天前
vue 表格组件 vxe-table 配置 ajax 请求自动加载数据与表单查询
vue.js·vxe-table
kybs19913 天前
全球灾害数据分析可视化 毕业设计-附源码66794
vue.js·spring boot·mysql·安全·django·c#·asp.net