Vue前端HTML保存为PDF常用方式有两种。
- 使用html2Canvas和JsPDF库,转化为图片后保存PDF。
- 调用浏览器window.print(),然后手动保存为PDF。
第一种
优点
- 没有预览点击即可保存
- 不需要手动配置保存
- 可选取部分Dom保存
缺点
- 较不清晰
- 需要先转化为图片
- 没有提前预览
- 不适合保存过长分页内容
- 依赖html2Canvas和JsPDF库
第二种
优点
- 可以提前预览
- 适合保存过长分页内容比较合适
- 直接由浏览器API保存,内容清晰
- 开发便利快速。
缺点
- 第一次需要在预览框手动配置参数
- 需要手动点击保存
- 会有Print预览弹窗
- 不可选取部分Dome,只能保存当前整页面。
第一种:使用html2Canvas和JsPDF库,转化为图片后保存PDF。
- 安装html2canvas库
npm install html2canvas
- 安装jspdf库
npm install jspdf
- 编写保存函数 文件位置:
src/utils/htmlToPdf.js
/**
path: src/utils/htmlToPdf.js
name: 导出页面为PDF格式
**/
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
const htmlToPdf = {
getPdf(title) {
html2Canvas(document.querySelector('#pdfDom'), {
allowTaint: true,
}).then(canvas=>{
//内容的宽度
let contentWidth = canvas.width;
//内容高度
let contentHeight = canvas.height;
//一页pdf显示html页面生成的canvas高度,a4纸的尺寸[595.28,841.89];
let pageHeight = contentWidth / 592.28 * 841.89;
//未生成pdf的html页面高度
let leftHeight = contentHeight;
//页面偏移
let position = 0;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
let imgWidth = 595.28;
let imgHeight = 592.28 / contentWidth * contentHeight;
//canvas转图片数据
let pageData = canvas.toDataURL('image/jpeg', 1.0);
//新建JsPDF对象
let PDF = new JsPDF('', 'pt', 'a4');
//判断是否分页
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
leftHeight -= pageHeight;
position -= 841.89;
if (leftHeight > 0) {
PDF.addPage()
}
}
}
//保存文件
PDF.save(title + '.pdf')
})
}
};
export default htmlToPdf;
复制代码
- 使用函数,文件位置
src/views/PdfPage1.vue
<template>
<div id="PdfPage1">
<button type="button" class="btn btn-primary" @click="pdfBtn">导出PDF</button>
<div id="pdfDom" style="padding:10px;background-color:#fff;">
<img alt="Vue logo" src="@/assets/logo.png">
<h1>Welcome to Your Vue.js App</h1>
<p v-for="(item,index) in 5" :key="index">{{item}}Welcome to Your Vue.js App</p>
</div>
</div>
</template>
<script>
import htmlToPdf from '@/utils/htmlToPdf'
export default {
name: "PdfPage",
data(){
return{
htmlTitle:'页面导出PDF文件名',
}
},
methods:{
pdfBtn(){
htmlToPdf.getPdf(this.htmlTitle);
}
}
}
</script>
<style scoped>
</style>
复制代码
第二种:调用浏览器window.print(),然后手动保存为PDF。
- 代码位置:
src/views/PdfPage2.vue
<template>
<div id="PdfPage2">
<div class="no-print">
<button type="button" class="btn btn-primary" @click="pdfBtn">导出PDF</button>
</div>
<div id="pdfDom" style="padding:10px;background-color:#fff;">
<img alt="Vue logo" src="@/assets/logo.png">
<h1>Welcome to Your Vue.js App</h1>
<p v-for="(item,index) in 5" :key="index">{{item}}Welcome to Your Vue.js App</p>
</div>
</div>
</template>
<script>
export default {
name: "PdfPage2",
methods:{
pdfBtn(){
window.print();
}
}
}
</script>
<style scoped>
/*保存时的样式*/
/*
了解更多可 百度CSS print样式
*/
@media print{
.no-print{
display: none;
}
}
/*打印页配置*/
@page{
margin:60px 10px;
}
</style>
复制代码
作者:天小天