欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue純前端實(shí)現(xiàn)將頁面導(dǎo)出為pdf和word文件

 更新時(shí)間:2024年01月23日 08:22:35   作者:xxf  
這篇文章主要為大家詳細(xì)介紹了vue如何通過純前端實(shí)現(xiàn)將頁面導(dǎo)出為pdf和word文件,文中的示例代碼講解詳細(xì),有需要的小伙伴可以參考一下

適用業(yè)務(wù)需求:將當(dāng)前頁面顯示內(nèi)容導(dǎo)出pdf或者word文件

實(shí)現(xiàn)思路:先將顯示內(nèi)容轉(zhuǎn)成圖片base64地址,再生成相應(yīng)文件

注意:顯示內(nèi)容直接轉(zhuǎn)圖片慎用::before、::after這些css,svg圖標(biāo),不然可能出現(xiàn)生成的圖片樣式丟失問題,如果確實(shí)需要顯示svg圖標(biāo)的話目前做法是轉(zhuǎn)成png顯示,如有更好方法,歡迎補(bǔ)充

導(dǎo)出pdf方式:

1.安裝相應(yīng)插件

npm i html2canvas jspdf -S

2.相應(yīng)頁面引入插件

import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'

3.相應(yīng)頁面下載代碼實(shí)現(xiàn)

html2Canvas(document.querySelector('#pdfDom'), {
  allowTaint: true
}).then(function (canvas) {
  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 = canvas.toDataURL('image/jpeg', 1.0)
  let PDF = new JsPDF('p', '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()
      }
    }
  }
  PDF.save('導(dǎo)出文件名.pdf')
})

導(dǎo)出word方式:

(1) 安裝相應(yīng)插件

npm i html2canvas docxtemplater pizzip jszip-utils jszip file-saver angular-expressions image-size docxtemplater-image-module-free -S

(2) 新建exportFile.js,存儲(chǔ)位置自定義,本例放在utils/exportFile.js,代碼如下

import PizZip from 'pizzip'
import Docxtemplater from 'docxtemplater'
import JSZipUtils from 'jszip-utils'
import { saveAs } from 'file-saver'

/**
 * 將base64格式的數(shù)據(jù)轉(zhuǎn)為ArrayBuffer
 * @param {Object} dataURL base64格式的數(shù)據(jù)
 */
function base64DataURLToArrayBuffer(dataURL) {
  const base64Regex = /^data:image/(png|jpg|jpeg|svg|svg+xml);base64,/
  if (!base64Regex.test(dataURL)) {
    return false
  }
  const stringBase64 = dataURL.replace(base64Regex, '')
  let binaryString
  if (typeof window !== 'undefined') {
    binaryString = window.atob(stringBase64)
  } else {
    binaryString = new Buffer(stringBase64, 'base64').toString('binary')
  }
  const len = binaryString.length
  const bytes = new Uint8Array(len)
  for (let i = 0; i < len; i++) {
    const ascii = binaryString.charCodeAt(i)
    bytes[i] = ascii
  }
  return bytes.buffer
}

/**
 * 導(dǎo)出word,支持圖片
 * @param {Object} tempDocxPath 模板文件路徑
 * @param {Object} wordData 導(dǎo)出數(shù)據(jù)
 * @param {Object} fileName 導(dǎo)出文件名
 * @param {Object} imgSize 自定義圖片尺寸
 */
export const exportWord = (tempDocxPath, wordData, fileName, imgSize) => {
  // 這里要引入處理圖片的插件
  var ImageModule = require('docxtemplater-image-module-free')

  const expressions = require('angular-expressions')

  // 讀取并獲得模板文件的二進(jìn)制內(nèi)容
  JSZipUtils.getBinaryContent(tempDocxPath, function(error, content) {
    if (error) {
      throw error
    }

    expressions.filters.size = function(input, width, height) {
      return {
        data: input,
        size: [width, height]
      }
    }

    // function angularParser (tag) {
    //   const expr = expressions.compile(tag.replace(/'/g, "'"));
    //   return {
    //     get (scope) {
    //       return expr(scope);
    //     },
    //   };
    // }

    // 圖片處理
    let opts = {}

    opts = {
      // 圖像是否居中
      centered: false
    }

    opts.getImage = (chartId) => {
      // console.log(chartId);//base64數(shù)據(jù)
      // 將base64的數(shù)據(jù)轉(zhuǎn)為ArrayBuffer
      return base64DataURLToArrayBuffer(chartId)
    }

    opts.getSize = function(img, tagValue, tagName) {
      // console.log(img);//ArrayBuffer數(shù)據(jù)
      // console.log(tagValue);//base64數(shù)據(jù)
      // console.log(tagName);//wordData對(duì)象的圖像屬性名
      // 自定義指定圖像大小
      if (Object.prototype.hasOwnProperty.call(imgSize, tagName)) {
        return imgSize[tagName]
      } else {
        return [600, 350]
      }
    }

    // 創(chuàng)建一個(gè)PizZip實(shí)例,內(nèi)容為模板的內(nèi)容
    const zip = new PizZip(content)
    // 創(chuàng)建并加載docxtemplater實(shí)例對(duì)象
    const doc = new Docxtemplater()
    doc.attachModule(new ImageModule(opts))
    doc.loadZip(zip)

    doc.setData(wordData)

    try {
      // 用模板變量的值替換所有模板變量
      doc.render()
    } catch (error) {
      // 拋出異常
      const e = {
        message: error.message,
        name: error.name,
        stack: error.stack,
        properties: error.properties
      }
      console.log(JSON.stringify({
        error: e
      }))
      throw error
    }

    // 生成一個(gè)代表docxtemplater對(duì)象的zip文件(不是一個(gè)真實(shí)的文件,而是在內(nèi)存中的表示)
    const out = doc.getZip().generate({
      type: 'blob',
      mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    })
    // 將目標(biāo)文件對(duì)象保存為目標(biāo)類型的文件,并命名
    saveAs(out, fileName)
  })
}

(3) 在相應(yīng)頁面引入插件

import html2Canvas from 'html2canvas'
import { exportWord } from '@/utils/exportFile'

(4) 在相應(yīng)頁面下載代碼,首先要先在本地存儲(chǔ)一份模版doc文件,vue-cli2存在static文件夾下面,vue-cli3存在public文件夾下面,doc模版類似這樣聲明

實(shí)現(xiàn)代碼如下:

const fileUrl = window.location.href.split('#')[0].replace('index.html', '') + 'data/doc/report-model.docx' // 存在public下的模版文件
html2Canvas(document.querySelector('#abnormalChartExp' + p.value), {
  allowTaint: true
}).then(function(canvas) {
  const contentWidth = canvas.width
  const contentHeight = canvas.height
  const imgWidth = 595.28
  const imgHeight = 592.28 / contentWidth * contentHeight
  const pageData = canvas.toDataURL('image/jpeg', 1.0)
  // console.log(pageData)
  const imgSize = {
    imgUrl: [imgWidth, imgHeight] // 控制導(dǎo)出的word圖片大小,寬度鋪滿
  }
  exportWord(fileUrl, { imgUrl: pageData }, `demo.docx`, imgSize)
})

word導(dǎo)出參考文章:vue實(shí)現(xiàn)導(dǎo)出word文檔

到此這篇關(guān)于vue純前端實(shí)現(xiàn)將頁面導(dǎo)出為pdf和word文件的文章就介紹到這了,更多相關(guān)vue頁面導(dǎo)出為pdf和word內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論