当前位置: 代码迷 >> 综合 >> jspdf html转pdf
  详细解决方案

jspdf html转pdf

热度:32   发布时间:2023-12-29 20:04:56.0

直接上代码直接用:

下载插件
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 * scalec.height = document.querySelector(dom).offsetHeight * scalec.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.widthlet contentHeight = canvas.heightlet pageHeight = contentWidth / 592.28 * 841.89let leftHeight = contentHeightlet position = 0let imgWidth = 595.28let imgHeight = 592.28 / contentWidth * contentHeightlet 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 -= pageHeightposition -= 841.89if (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)

  相关解决方案