直接上代码直接用:
下载插件
cnpm i jspdf --save
cnpm i html2canvas --save
1.新建一个htmlToPdf.js
getPdf(a,b,c,fn) //a: id绑定得dom — b:下载得文件命 c:/1 下载 2上传 fn 回调函数 前2个参数必传
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default{
install (Vue, options) {
Vue.prototype.getPdf = function (dom,title,type=1,fn) { //1 下载 2上传 fn 回调函数
var c = document.createElement("canvas")
var scale=2.5;
var opts = {
scale: scale,
useCORS: true,//允许跨域图片
allowTaint: true,//允许跨域图片
logging: true,
//canvas: c,
width: document.querySelector(dom).offsetWidth,
height: document.querySelector(dom).offsetHeight ,
dpi: window.devicePixelRatio * scale
};
c.width = document.querySelector(dom).offsetWidth * scale
c.height = document.querySelector(dom).offsetHeight * scale
c.getContext("2d").scale(scale, scale);
html2Canvas(document.querySelector(dom),opts).then(function (canvas) {
// 关闭抗锯齿
c.mozImageSmoothingEnabled=false;
c.webkitImageSmoothingEnabled=false;
c.msImageSmoothingEnabled=false;
c.ImageSmoothingEnabled=false;
let contentWidth = canvas.width
let contentHeight = canvas.height
let pageHeight = contentWidth / 592.28 * 841.89
let leftHeight = contentHeight
let position = 0
let imgWidth = 595.28
let imgHeight = 592.28 / contentWidth * contentHeight
let pageData = canvas.toDataURL('image/jpeg', 0.7)
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()
}
}
}
if(type==1){ //判断直接下载
PDF.save(title + '.pdf')
}else{ //转成文件活base64上传
var buffer = PDF.output("datauristring");
var myfile = dataURLtoFile(buffer, title)
var formdata = new FormData()
formdata.append('file', myfile)
console.log(myfile)
fn(formdata) //回调函数
}
//将base64转换为文件对象
function dataURLtoFile(dataurl, filename) {
console.log(filename)
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);
}
//转换成file对象
return new File([u8arr], filename, {type:mime});
//转换成成blob对象
//return new Blob([u8arr],{type:mime});
}
}
)
}
}
}
2.main.js
import htmlToPdf from '@/commond/htmlToPdf'
Vue.use(htmlToPdf)
3.使用
id自定义得
调用 上传服务器得 this.getPdf(’#pdf’,“name”,2,function(formdata){ —上传ajax— })
直接下载 this.getPdf(’#pdf’,“name”,1)