900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > vue2.0将页面html导出为pdf格式文档

vue2.0将页面html导出为pdf格式文档

时间:2019-02-07 16:44:52

相关推荐

vue2.0将页面html导出为pdf格式文档

npm i html2canvasnpm i jspdf创建一个js文件

// 页面导出为pdf格式 //title表示为下载的标题,html表示document.querySelector('#myPrintHtml')import html2Canvas from 'html2canvas'import JsPDF from 'jspdf'const htmlPdf = {getPdf(title, html) {html2Canvas(html, {allowTaint: false,taintTest: false,logging: false,useCORS: true,dpi: window.devicePixelRatio * 4, // 将分辨率提高到特定的DPI 提高四倍scale: 4, // 按比例增加分辨率}).then((canvas) => {const pdf = new JsPDF('p', 'mm', 'a4') // A4纸,纵向const ctx = canvas.getContext('2d')const a4w = 190const a4h = 200 // A4大小,210mm x 297mm,四边各保留10mm的边距,显示区域190x277const imgHeight = Math.floor((a4h * canvas.width) / a4w) // 按A4显示比例换算一页图像的像素高度let renderedHeight = 0while (renderedHeight < canvas.height) {const 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边距renderedHeight += imgHeightif (renderedHeight < canvas.height) {pdf.addPage() // 如果后面还有内容,添加一个空页}// delete page;}// 保存文件pdf.save(`${title}.pdf`)})},}export default htmlPdf

页面在调用这个方法就可以了

<template><div class="main"><div>1af4sa4fa</div><div>dsasafsa4fs</div><van-image width="100" height="100" src="/vant/cat.jpeg" /></div></template><script>import htmlPdf from '@/utils/htmlPdf'export default {methods: {handelFun() {htmlPdf.getPdf('导出pdf', document.querySelector('.main'))},},}</script>

不走下载,转为base64传给后端

/* eslint-disable no-param-reassign */// 页面导出为pdf格式 //title表示为下载的标题,html表示document.querySelector('#myPrintHtml')// 参考地址 /configurationimport html2Canvas from 'html2canvas'import JsPDF from 'jspdf'const htmlPdf = {getPdf(title, html) {return new Promise((resolve) => {html2Canvas(html, {allowTaint: false,taintTest: false,logging: false,useCORS: true,windowWidth: '1000px',dpi: window.devicePixelRatio * 3, // 将分辨率提高到特定的DPI 提高四倍scale: 2, // 按比例增加分辨率}).then((canvas) => {console.log(canvas)const pdf = new JsPDF('p', 'mm', 'a4') // A4纸,纵向const ctx = canvas.getContext('2d')console.log(ctx, 'ctx')const a4w = 190const a4h = 286 // A4大小,210mm x 297mm,四边各保留10mm的边距,显示区域190x277const imgHeight = Math.floor((a4h * canvas.width) / a4w) // 按A4显示比例换算一页图像的像素高度let renderedHeight = 0while (renderedHeight < canvas.height) {const 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边距renderedHeight += imgHeightif (renderedHeight < canvas.height) {pdf.addPage() // 如果后面还有内容,添加一个空页}// delete page;}// 保存文件// pdf.save(`${title}.pdf`)// 获取 base64const pdfData = pdf.output('datauristring')resolve(pdfData)})})},}export default htmlPdf

<template><div class="main"><div>1af4sa4fa</div><div>dsasafsa4fs</div><van-image width="100" height="100" src="/vant/cat.jpeg" /></div></template><script>import htmlPdf from '@/utils/htmlPdf'export default {methods: {handelFun() {htmlPdf.getPdf('导出pdf', document.querySelector('.main')).then((res) => {console.log('base64', res)})},},}</script>

一个标签代表一个pdf页面,for循环

handelFun() {const arr = [document.querySelector('.qwe'),document.querySelector('.qwer'),document.querySelector('.qwert'),]// 自定义加载图标this.$toast.loading({message: '加载中...',forbidClick: true,loadingType: 'spinner',})htmlPdf.getPdf('导出pdf', arr).then((res) => {const str = base64toFilePdf(res, '委托书')this.arr.push(str)// console.log(str)}).then(() => {const formDatas = new FormData()formDatas.append('file', this.arr[0])formDatas.append('needInfo', 1)formDatas.append('fileName', this.arr[0].name.split('.')[0])formDatas.append('fileType', this.arr[0].name.split('.')[1])formDatas.append('bucketName', 'content_bucket')formDatas.append('token', 'a::A09AA21B1A2F42F7B2C3581339B0563C')myUploadFile(formDatas)// eslint-disable-next-line no-shadow.then((ress) => {const data = JSON.parse(ress.data.data).urlthis.upload(data)console.log(data)}).catch((error) => {this.$toast(error)})})},

js文件

/* eslint-disable no-param-reassign */// 页面导出为pdf格式 //title表示为下载的标题,html表示document.querySelector('#myPrintHtml')// 参考地址 /configurationimport html2Canvas from 'html2canvas'import JsPDF from 'jspdf'const htmlPdf = {getPdf(title, html) {// eslint-disable-next-line no-async-promise-executorreturn new Promise(async (resolve) => {const pdf = new JsPDF('p', 'mm', 'a4') // A4纸,纵向for (let i = 0; i < html.length; i++) {const canvas = await html2Canvas(html[i], {allowTaint: false,taintTest: false,logging: false,useCORS: true,windowWidth: '1000px',dpi: window.devicePixelRatio * 3, // 将分辨率提高到特定的DPI 提高四倍scale: 2, // 按比例增加分辨率})const ctx = canvas.getContext('2d')const a4w = 190const a4h = 286 // A4大小,210mm x 297mm,四边各保留10mm的边距,显示区域190x277const imgHeight = Math.floor((a4h * canvas.width) / a4w) // 按A4显示比例换算一页图像的像素高度let renderedHeight = 0while (renderedHeight < canvas.height) {const 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边距renderedHeight += imgHeight// if (renderedHeight < canvas.height) {// pdf.addPage() // 如果后面还有内容,添加一个空页// }// delete page;}// 保存文件if (i + 1 === html.length) {console.log(title)// pdf.save(`${title}.pdf`)const pdfData = pdf.output('datauristring')resolve(pdfData)} else {pdf.addPage()}// 获取 base64// const pdfData = pdf.output('datauristring')// resolve(pdfData)}})},}export default htmlPdf

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。