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>

相关推荐
天平2 小时前
油猴脚本创建webworker踩坑记录
前端·javascript·typescript
原则猫3 小时前
前端基础大厦
前端
陈随易4 小时前
编程语言级别的Skill市场,AI Agent 的未来形态
前端·后端·程序员
SoaringHeart5 小时前
Flutter进阶:基于 EasyRefresh 的下拉刷新封装 n_easy_refresh_mixin.dart
前端·flutter
IT_陈寒7 小时前
Vite的热更新突然不香了,排查三小时差点砸键盘
前端·人工智能·后端
子兮曰8 小时前
Agency-Agents 深度解析:400+ AI 专家的"梦之队"如何重塑开发工作流
前端·后端·vibecoding
山河木马8 小时前
渲染管线-计算得到gl_Position(顶点着色器)之后续GPU流程
javascript·webgl·图形学
竹林8188 小时前
用 The Graph 查询链上数据实战:从手搓 RPC 到 Subgraph,我的 NFT 项目数据加载快了 10 倍
前端·javascript
妙码生花9 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十九):点选验证码代码逐行目检
前端·后端·go
Awu12279 小时前
⚡从零开发 Agent CLI(五)实现一个可治理、可扩展的工具系统
前端·人工智能·claude