import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'const getPdf = async (dom, title) => {await new Promise((resolve, reject) => {try {// 避免模糊,放大倍数,倍数可调整const el = document.getElementById(dom) || document.querySelector(dom)var c = document.createElement('canvas')var opts = {scale: 3,canvas: c,allowTaint: false,logging: true,useCORS: true,width: window.getComputedStyle(el).width.replace('px', '') * 1,height: window.getComputedStyle(el).height.replace('px', '') * 1}c.width = window.getComputedStyle(el).width.replace('px', '') * 3c.height = window.getComputedStyle(el).height.replace('px', '') * 3c.getContext('2d').scale(1, 1)html2Canvas(el, opts).then(async canvas => {const contentWidth = canvas.widthconst contentHeight = canvas.heightconst pageHeight = (contentWidth / 592.28) * 841.89let leftHeight = contentHeightlet position = 0const imgWidth = 595.28const imgHeight = (592.28 / contentWidth) * contentHeightconst pageData = await canvas.toDataURL('image/jpeg', 1.0)const PDF = await new JsPDF('', 'pt', 'a4')if (leftHeight < pageHeight) {await PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)} else {while (leftHeight > 0) {await PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)leftHeight -= pageHeightposition -= 841.89if (leftHeight > 0) {await PDF.addPage()}}}await PDF.save(title + '.pdf')resolve()})} catch (error) {reject(error)}})
}
export default getPdf
1.封装一下方法,
allowTaint: false,
logging: true,
useCORS: true,//跨域加载图片
2.配置你的图片url域名
比如你的图片服务器地址是https://www.cehnxgy.com/4654a56d4asd.png
devServer: {disableHostCheck: true,// open: true,port: 8081,overlay: {errors: true,warnings: true},proxy: {'/platform': {target: 'https://test.cehnxgy.com', //接口域名地址changeOrigin: true},'': {target: 'https://www.cehnxgy.com',//图片服务器域名地址(灵活配置,如果图片地址与接口域名地址一致就不用)changeOrigin: true}}}