vue中将html导出成pdf
vue 中将页面 html 内容导出成 pdf 文件格式,使用 html2canvas 、jspdf 。
首先使用 html2canvas 将内容转换为图片,之后写入 pdf 。
1、引用
第一个.将页面html转换成图片 npm install --save html2canvas 第二个.将图片生成pdf npm install jspdf --save
2、创建 exportToPdf.js ,放入导出方法
// exportToPdf.js
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
export function exportToPDF(fileName,elementId) {
// 根据元素ID获取要导出的元素
const element = document.getElementById(elementId);
if (!element) {
console.error('无法找到指定的元素');
return;
}
// 使用 html2canvas 将元素转换为 canvas
html2canvas(element).then(canvas => {
// 创建一个新的 jsPDF 实例
const pdf = new jsPDF('p', 'mm', 'a4');
// 将 canvas 转换为图片并添加到 PDF
const imgProps = canvas.toDataURL('image/png');
const imgPropsArr = imgProps.split(','), mimeType = imgPropsArr[0].match(/:(.*?);/)[1];
const img = new Image();
img.onload = function() {
// 获取图片的宽高
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (img.height * pdfWidth) / img.width;
// 添加图片到 PDF
pdf.addImage(imgProps, mimeType, 0, 0, pdfWidth, pdfHeight);
// 保存 PDF
pdf.save(fileName);
//预览
/* // 生成PDF的Blob对象
const pdfBlob = pdf.output('blob');
// 创建一个指向Blob对象的URL
const pdfUrl = URL.createObjectURL(pdfBlob);
// 打开新窗口预览PDF
const win = window.open();
win.document.write(`
<html>
<head>
<title>PDF Preview</title>
</head>
<body>
<embed src="${pdfUrl}" type="application/pdf" width="100%" height="100%">
</body>
</html>
`);*/
// 你可以选择在预览后释放URL,但这会关闭预览(如果浏览器支持)
//URL.revokeObjectURL(pdfUrl);
};
img.src = imgProps;
}).catch(error => {
console.error('导出PDF时发生错误:', error);
});
}
3、vue中
<template>
<div style="text-align: center">
<div>
<div>
<button type="button" @click="pdfBtn">导出PDF</button>
</div>
<div id="pdfDom" >
<div>内容</div>
</div>
</div>
</div>
</template>
<script>
// 导入exportToPDF函数
import { exportToPDF } from '@/utils/feature/exportToPdf';
export default {
name: "exportpdf",
data(){
return{
htmlTitle:'页面导出PDF文件名',
}
},
methods:{
pdfBtn(){
exportToPDF(this.htmlTitle,'pdfDom');
},
}
}
</script>
<style scoped>
</style>
浙公网安备 33010602011771号