需要 html2pdf.js
npm install html2pdf.js 下完后看下版本,我用的0.9.3。其他版本好像不太好用
vue2
<template>
<div>
<h2> PDF 示例</h2>
<form ref="content2" class="content2">
<div>
<label for="name">111:</label>
<input type="text" v-model="formData.name" id="name" required />
</div>
123
<div>
7789
<label for="message">222:</label>
<textarea v-model="formData.message" id="message" required></textarea>
</div>
</form>
<el-button @click="generatePDF2()">2</el-button>
</div>
</template>
<script>
import jsPDF from 'jspdf';
import 'jspdf-autotable';
import html2pdf from 'html2pdf.js'
export default {
data() {
return {
formData: {
name: '',
email: '',
message: ''
},
pdfData: null // 用于存储 PDF 数据的 URL
};
},
methods: {
generatePDF2() {
const element = document.querySelector('.content2'); // 获取要转换的元素
const options = {
margin: [10, 10, 10, 10], // 页面边距
filename: '合格证.pdf',
image: { type: 'png', quality: 1 }, // 高质量 PNG
html2canvas: { scale: 3,
allowTaint: true, // 允许跨域图片
useCORS: true // 使用 CORS
}, // 提高分辨率
jsPDF: { unit: 'mm', format: 'a4', orientation: 'landscape' } // A4 尺寸 横向
};
html2pdf().from(element).set(options).save();
}
};
</script>
<style>
.pdf-preview {
margin-top: 20px;
border: 1px solid #ccc;
padding: 10px;
}
</style>
vue3
<template>
<a-modal :visible="false" width="1200px">
<div class="imm">
<button @click="generatePDF2">生成 PDF</button>
<div ref="content2" class="content2" >
<!-- <p>这里是 PDF 的内容</p>-->
<div class="box">
<h1> {{ detailInfo.certificateName }} </h1>
<div style="display: flex;font-size: 20px;margin: 40px 0px">
<div style="font-weight: 600">{{ detailInfo.studentName }}</div>
<div>( 学号: {{ detailInfo.studentJobNumber }} )</div>
</div>
</div>
</div>
</div>
</a-modal>
</template>
<script setup lang="ts">
import html2pdf from 'html2pdf.js'
import {ref,defineExpose} from "vue";
const generatePDF2 = async () => {
const element = document.querySelector('.content2'); // 获取要转换的元素
const options = {
margin: [10, 10, 10, 10], // 页面边距
filename: '合格证.pdf',
image: { type: 'png', quality: 1 }, // 高质量 PNG
html2canvas: { scale: 3,
allowTaint: true, // 允许跨域图片
useCORS: true // 使用 CORS
}, // 提高分辨率
jsPDF: { unit: 'mm', format: 'a4', orientation: 'landscape' } // A4 尺寸 横向
};
html2pdf().from(element).set(options).save();
};
// generatePDF()
// 如果要暴露方法给父组件调用,需要使用 defineExpose
defineExpose({ generatePDF2 });
</script>
<style scoped lang="less">
.content2{
height: 500px;
background-size: 100% 100%;
width: 1040px;
height: 710px;
}
.box{
padding: 140px;
h1{
text-align: center;
}
}
</style>