1.首先创建js文件exportPdf.js,且需要安装html2canvas和jspdf两个插件;
然后将在你需要导出的页面中执行方法,
this.getPdf("html", "报表");
下面是导出的主要代码;我在网上查找了大量的代码才写出了这个,其他的代码都是很浅显,虽然也可以导出,但是一旦数据量过大,页面较长导出的pdf文件便会白屏;此文件解决了此问题,但是因为导出的pdf做了分页,而pdf又是由图片转换而来,所以分页中会有截断的问题,暂未解决,希望大家可以指点。
/ 导出pdf文档 /
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";
export default {
install(Vue, options) {
Vue.prototype.getPdf = function (id, title) {
const loading = Vue.prototype.$loading({
fullscreen: true,
lock: true,
text: 'Loading',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
});
let shareContent = document.getElementById(id),
width = shareContent.clientWidth,
height = shareContent.clientHeight,
canvas = document.createElement("canvas"),
scale = 1;
canvas.width = width * scale;
canvas.height = height * scale;
canvas.style.width = shareContent.clientWidth * scale + "px";
canvas.style.height = shareContent.clientHeight * scale + "px";
canvas.getContext("2d").scale(scale, scale);
let opts = {
scale: scale,
canvas: canvas,
logging: false,
width: width,
height: height,
useCORS: true,
html2Canvas(shareContent, opts).then(() => {
var contentWidth = canvas.width;
var contentHeight = canvas.height;
var pageHeight = (contentWidth / 592.28) * 841.89;
var leftHeight = contentHeight;
var position = 0;
var imgWidth = 595.28;
var imgHeight = (592.28 / contentWidth) * contentHeight;
var pageData = canvas.toDataURL("image/jpeg", 1.0);
var 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");
loading.close();
this.$router.go(-1)
});
注意:打印的时候,父级或者父级之上的元素的css设置不能有transform,否则在火狐浏览器中,打印出来的pdf会有偏移。