vue純前端實現將頁面導出為pdf和word文件
適用業(yè)務需求:將當前頁面顯示內容導出pdf或者word文件
實現思路:先將顯示內容轉成圖片base64地址,再生成相應文件
注意:顯示內容直接轉圖片慎用::before、::after這些css,svg圖標,不然可能出現生成的圖片樣式丟失問題,如果確實需要顯示svg圖標的話目前做法是轉成png顯示,如有更好方法,歡迎補充
導出pdf方式:
1.安裝相應插件
npm i html2canvas jspdf -S
2.相應頁面引入插件
import html2Canvas from 'html2canvas' import JsPDF from 'jspdf'
3.相應頁面下載代碼實現
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('導出文件名.pdf')
})
導出word方式:
(1) 安裝相應插件
npm i html2canvas docxtemplater pizzip jszip-utils jszip file-saver angular-expressions image-size docxtemplater-image-module-free -S
(2) 新建exportFile.js,存儲位置自定義,本例放在utils/exportFile.js,代碼如下
import PizZip from 'pizzip'
import Docxtemplater from 'docxtemplater'
import JSZipUtils from 'jszip-utils'
import { saveAs } from 'file-saver'
/**
* 將base64格式的數據轉為ArrayBuffer
* @param {Object} dataURL base64格式的數據
*/
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
}
/**
* 導出word,支持圖片
* @param {Object} tempDocxPath 模板文件路徑
* @param {Object} wordData 導出數據
* @param {Object} fileName 導出文件名
* @param {Object} imgSize 自定義圖片尺寸
*/
export const exportWord = (tempDocxPath, wordData, fileName, imgSize) => {
// 這里要引入處理圖片的插件
var ImageModule = require('docxtemplater-image-module-free')
const expressions = require('angular-expressions')
// 讀取并獲得模板文件的二進制內容
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數據
// 將base64的數據轉為ArrayBuffer
return base64DataURLToArrayBuffer(chartId)
}
opts.getSize = function(img, tagValue, tagName) {
// console.log(img);//ArrayBuffer數據
// console.log(tagValue);//base64數據
// console.log(tagName);//wordData對象的圖像屬性名
// 自定義指定圖像大小
if (Object.prototype.hasOwnProperty.call(imgSize, tagName)) {
return imgSize[tagName]
} else {
return [600, 350]
}
}
// 創(chuàng)建一個PizZip實例,內容為模板的內容
const zip = new PizZip(content)
// 創(chuàng)建并加載docxtemplater實例對象
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
}
// 生成一個代表docxtemplater對象的zip文件(不是一個真實的文件,而是在內存中的表示)
const out = doc.getZip().generate({
type: 'blob',
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
})
// 將目標文件對象保存為目標類型的文件,并命名
saveAs(out, fileName)
})
}
(3) 在相應頁面引入插件
import html2Canvas from 'html2canvas'
import { exportWord } from '@/utils/exportFile'
(4) 在相應頁面下載代碼,首先要先在本地存儲一份模版doc文件,vue-cli2存在static文件夾下面,vue-cli3存在public文件夾下面,doc模版類似這樣聲明

實現代碼如下:
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] // 控制導出的word圖片大小,寬度鋪滿
}
exportWord(fileUrl, { imgUrl: pageData }, `demo.docx`, imgSize)
})
word導出參考文章:vue實現導出word文檔
到此這篇關于vue純前端實現將頁面導出為pdf和word文件的文章就介紹到這了,更多相關vue頁面導出為pdf和word內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
適用于 Vue 的播放器組件Vue-Video-Player操作
這篇文章主要介紹了適用于 Vue 的播放器組件Vue-Video-Player操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11

