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>

相关推荐
@不误正业11 小时前
2026-05-16-多Agent协作框架深度实战-从ReAct到Plan-and-Execute全架构演进
前端·react.js·架构
我命由我1234511 小时前
PHP - PHP 简易 Web 服务器、基础接口开发
服务器·开发语言·前端·php·intellij-idea·idea·intellij idea
Reload.11 小时前
CZ航司,shopping JS逆向 acw_sc__v2
开发语言·javascript·python·网络爬虫·ecmascript
咖喱o11 小时前
IPv6
服务器·前端·网络
海上彼尚11 小时前
Nodejs也能写Agent - 6.基础篇 - Agent
前端·人工智能·后端·node.js
2501_9400417411 小时前
纯前端实战:5个高复杂度业务与交互场景
前端
renke336411 小时前
写给前端的 CANN-torchtitan-npu:昇腾PyTorch Titan适配到底是啥?
前端·人工智能·pytorch·cann
lihaozecq11 小时前
Agent 开发的 skills 机制设计 - 渐进式披露
前端·agent·ai编程
安妮的小熊呢11 小时前
CRMEB标准版v6.0: 商城DIY装修新升级,PS级自由设计!
运维·javascript·平面·信息可视化·小程序·开源软件