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>

相关推荐
程序员黑豆1 小时前
Java类型推断完全指南:从var到菱形运算符,掌握使用限制与最佳实践
java·前端·ai编程
To_OC2 小时前
踩了个 TS 的坑之后,我终于把 type 和 interface 掰明白了
前端·react.js·typescript
GreenTea2 小时前
深度解读 Anthropic 多智能体报告:更强的模型 ≠ 更好的协调
前端·后端·算法
浮生望2 小时前
前端API工程化:用 Mock 数据与 Axios 配置实现独立于后端的并行开发
前端
万少3 小时前
给 DeepSeek Harness 装个"应用商店":一条命令,595 个插件随你逛
前端·javascript·后端
波波0073 小时前
C# 15 重磅新特性: 带标签 break 与 continue:重新定义嵌套循环控制流
服务器·前端·c#
Brown.alexis4 小时前
es6知识点1-自备使用
前端·ecmascript·es6
小爬的老粉丝5 小时前
JavaScript 纯前端预览 WPS:先识别容器,再路由解析器
前端·javascript·wps
计算机魔术师5 小时前
新兴多智能体系统的模式与问题
前端
用户059540174466 小时前
AI Agent 上下文污染踩坑实录:用 pytest + Redis 揪出 3 类记忆串号 bug,排查 6 小时
前端·css