- 要用到2个组件
第一个.将页面html转换成图片
npm install --save html2canvas
第二个.将图片生成pdf
npm install jspdf --save
- 定义全局函数..创建一个htmlToPdf.js文件在指定位置,并且处理成文件流以便上传至后台服务器
import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';
function dataURLtoBlob (dataurl) {
var arr = dataurl.split(',');
var mime = arr[0].match(/:(.*?);/)[1];
var bstr = atob(arr[1]);
var n = bstr.length;
var u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {
type: mime
});
}
function blobToFile (theBlob, fileName) {
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
}
export default {
install (Vue, options) {
Vue.prototype.getPdfForHtml = function (domValue, filename) {
return html2Canvas(document.querySelector(domValue), {
allowTaint: true
}).then(function (canvas) {
const contentWidth = canvas.width;
const contentHeight = canvas.height;
const pageHeight = (contentWidth / 592.28) * 841.89;
let leftHeight = contentHeight;
let position = 0;
const imgWidth = 595.28;
const imgHeight = (592.28 / contentWidth) * contentHeight;
const pageData = canvas.toDataURL('image/jpeg', 1.0);
const 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();
}
}
}
var buffer = PDF.output('datauristring');
const blob = dataURLtoBlob(buffer);
var file = blobToFile(blob, filename);
return file
});
};
}
};
- 在main.js中使用我们定义的函数文件
import htmlToPdf from '@/utils/htmlToPdf'
Vue.use(htmlToPdf)
- 要下载pdf或获取文件流,直接调用getPdfForHtml('#id')即可