一、需求:在手机端/pc端实现一个表格页面(缴费单/体检报告单等)的导出功能,便于用户在本地浏览打印。
二、实现:之前在pc端做过预览打印的功能,使用的是print.js之类的方法让当前页面直接唤起打印机的打印预览功能,但是手机端这种方式不太友好,所以采用如下方式实现:
1.将要打印的页面转换成图片( 用到的组件 html2canvas );
2.然后将图片导出成PDF( 用到的组件 jspdf )。
- 安装依赖:
npm install --save html2canvas // 页面转图片
npm install jspdf --save // 图片转pdf
- 在utils文件夹创建一个pdf.js文件,实现页面转图片导出成A4纸大小的pdf文件;
import html2canvas from "html2canvas";
import jsPDF from "jspdf";/*** 导出pdf * @param {*} page 要打印的区域* @param {*} name 下载导出的名字*/
export const downloadPDF = (page, name) => {html2canvas(page).then(function (canvas) {canvas2PDF(canvas, name);});
};//图片转pdf
const canvas2PDF = (canvas, name) => {let contentWidth = canvas.width;let contentHeight = canvas.height;//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高let imgWidth = 595.28;let imgHeight = (592.28 / contentWidth) * contentHeight;// 第一个参数: l:横向 p:纵向// 第二个参数:测量单位("pt","mm", "cm", "m", "in" or "px")let pdf = new jsPDF("p", "pt");pdf.addImage(canvas.toDataURL("image/jpeg", 1.0),"JPEG",0,0,imgWidth,imgHeight);pdf.save(name + "报告单.pdf");
};
- 在要打印的页面触发这个下载导出的方法;
<template><div class="referralDetail"><van-nav-bartitle="报告单"left-arrowclass="blue-bar"@click-left="toBack"></van-nav-bar><!-- ref="print" 设置要打印的区域 --><div class="drawerBody" id="print" ref="print"><h1 class="formTitle">{{ infoObj.fromHospitalName || "" }}报告单</h1><span class="zzCode">报告编码:{{ infoObj.twrCode }}</span><div class="formContent"><div v-for="item in titleArr" :key="item.label" class="contentItem"><div class="itemTitle"><span>{{ item.label }}</span></div><div class="itemContent"><span>{{ infoObj[item.value] }}</span></div></div></div></div><van-tabbar class="content-tabbar"><div class="content-tabbar-block"><van-buttonsize="normal"color="#3378E0"@click="handleExport(infoObj.fromHospitalName)">导出</van-button></div></van-tabbar></div>
</template>
<script>
import { downloadPDF } from "@/utils/pdf.js"; // 工具方法,导出操作
export default {name: "referralDetail",data() {return {infoObj: {},titleArr: [{ value: "xxx", label: "患者姓名"},{ value: "xxx", label: "身份证号"},{ value: "xxx", label: "性别"},{ value: "xxx", label: "联系方式"},{ value: "xxx", label: "转入机构"},{ value: "xxx", label: "转诊类型"},{ value: "xxx", label: "审批医生"},{ value: "xxx", label: "接收科室"},{ value: "xxx", label: "转出机构"},{ value: "xxx", label: "转出科室"},{ value: "xxx", label: "转出医生"},{ value: "xxx", label: "申请日期"},{ value: "xxx", label: "转诊状态"},{ value: "xxx", label: "医保类型"},{ value: "xxx", label: "主要诊断"},{ value: "xxx", label: "病情等级"}],};},created() {if (this.$route.query) {this.infoObj = this.$route.query.infoData;}},methods: {// 导出handleExport(name) {//调用打印方法(打印区域,导出名称)downloadPDF(this.$refs.print, name);},// 倒退toBack() {this.$router.go(-1);},},
};
</script><style lang="less" scoped></style>
- 界面效果如下:
- 点击导出按钮得到的pc端查看效果如下: