package.json中添加依赖
调用方:
import htmlToPdf from '../../../utils/file/htmlToPdf.js'// 下载方法,pdfDownloadDpi为onClickDownLoad() {htmlToPdf.getPdf('标题1', 'jsfgyzcpgxmShow', this.pdfDownloadDpi)}
htmlToPdf.js
// 页面导出为pdf格式
import html2Canvas from 'html2canvas'
import jsPDF from 'jspdf'const htmlToPdf = {getPdf(title, url, dpi, fn) {var divId = ''if (url === 'gyzcpgxmShow') {divId = '#pdfDom'}if (url === 'jsfgyzcpgxmShow') {divId = '#pdfDom2'}if (url === 'stockRelation') {divId = '#stockRelationBody'}html2Canvas(document.querySelector(divId), {allowTaint: false,taintTest: false,logging: false,useCORS: true,dpi: window.devicePixelRatio * dpi, // 将分辨率提高到特定的DPI 提高四倍 【1: 0.4M左右, 2: 1000K 左右, 3: 2.1M , 4:3M 左右】scale: dpi // 按比例增加分辨率}).then(canvas => {// eslint-disable-next-line new-capvar pdf = new jsPDF('l', 'mm', 'a3') // A3纸,横向// var pdf = new jsPDF('p', 'mm', 'a4') // A4纸,纵向var ctx = canvas.getContext('2d')// var a4w = 190; var a4h = 277 // A4大小,210mm x 297mm,四边各保留10mm的边距,显示区域190x277// var a4w = 259; var a4h = 400var a4w = 286; var a4h = 420 // A3大小,279mm x 420mm,四边各保留10mm的边距,显示区域259x400// var imgHeight = Math.floor(a4h * canvas.width / a4w) // 按A4显示比例换算一页图像的像素高度[这个计算方式应该是纵向]var imgHeight = Math.floor(a4w * canvas.width / a4h) // 按A4显示比例换算一页图像的像素高度[这个是横向打印的计算方法]var renderedHeight = 0while (renderedHeight < canvas.height) {var page = document.createElement('canvas')page.width = canvas.widthpage.height = Math.min(imgHeight, canvas.height - renderedHeight)// 可能内容不足一页// 用getImageData剪裁指定区域,并画到前面创建的canvas对象中page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0)// pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width)) // 添加图像到页面,保留10mm边距 [a4使用]pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 10, a4w * 1.414, Math.min(a4h, a4w * page.height / page.width) * 1.414) // 添加图像到页面,保留10mm边距[a3使用1.414换算比例]renderedHeight += imgHeightif (renderedHeight < canvas.height) {pdf.addPage()// 如果后面还有内容,添加一个空页}// delete page;}// 保存文件pdf.save(title + '.pdf')}).catch(res => { console.log(res) }).finally(() => {if (fn) {fn()}})}
}export default htmlToPdf