jspdfhtml转pdf
直接上代码直接⽤:
下载插件
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) {
Pdf = function (dom,title,type=1,fn) { //1 下载 2上传 fn 回调函数
var c = ateElement("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
html2Canvas(document.querySelector(dom),opts).then(function (canvas) {
// 关闭抗锯齿
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 = DataURL('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){ //判断直接下载
if(type==1){ //判断直接下载
PDF.save(title + '.pdf')
}else{ //转成⽂件活base64上传
html代码转链接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⾃定义得
调⽤ 上传服务器得 Pdf(’#pdf’,“name”,2,function(formdata){ —上传ajax— })直接下载 Pdf(’#pdf’,“name”,1)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论