vue實(shí)現(xiàn)把頁(yè)面導(dǎo)出成word文件的方法
思路:先把頁(yè)面上的元素轉(zhuǎn)成圖片,然后把圖片放到word文件中進(jìn)行導(dǎo)出.
1.先下載依賴(lài)
npm install docxtemplater pizzip --save npm install jszip-utils --save npm install jszip --save npm install file-saver --save npm install docxtemplater-image-module-free --save npm install angular-expressions --save npm install html2canvas --save
2.準(zhǔn)備word模板
導(dǎo)出word文件需要在項(xiàng)目static文件中先放置一個(gè)模板,名稱(chēng)為demo.docx vue2放在static下面,vue3放在public下面
注意:
1)模板文件必須是docx文件。doc文件不能通過(guò)修改后綴名變?yōu)閐ocx,必須另存時(shí)選擇docx類(lèi)型,才能實(shí)現(xiàn)類(lèi)型轉(zhuǎn)變。但是docx是可以通過(guò)修改后綴名改為doc文件的,因?yàn)閛ffice的升級(jí)基本都是向下兼容的。
2)使用英文下的花括號(hào);
3)花括號(hào)內(nèi)的鍵名前后不要有空格,且它與程序中的data對(duì)象的鍵名必須保持一致 ;
4)表格中想要循環(huán)添加的數(shù)據(jù),需要在開(kāi)頭添加{#鍵名},在結(jié)尾處添加{/鍵名},例如下圖的
{#table}和{/table};5)圖片居中不要使用{%%image2}
3.封裝js,創(chuàng)建一個(gè)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: true }; opts.getImage = (chartId) => { //console.log(chartId);//base64數(shù)據(jù) //將base64的數(shù)據(jù)轉(zhuǎn)為ArrayBuffer return base64DataURLToArrayBuffer(chartId); } opts.getSize = function(img, tagValue, tagName) { //自定義指定圖像大小 if(imgSize.hasOwnProperty(tagName)){ return imgSize[tagName]; }else{ return [300, 300]; } } // 創(chuàng)建一個(gè)PizZip實(shí)例,內(nèi)容為模板的內(nèi)容 let zip = new PizZip(content); // 創(chuàng)建并加載docxtemplater實(shí)例對(duì)象 let doc = new docxtemplater(); doc.attachModule(new ImageModule(opts)); doc.loadZip(zip); doc.setData(wordData); try { // 用模板變量的值替換所有模板變量 doc.render(); } catch (error) { // 拋出異常 let 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)存中的表示) let out = doc.getZip().generate({ type: "blob", mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }); // 將目標(biāo)文件對(duì)象保存為目標(biāo)類(lèi)型的文件,并命名 saveAs(out, fileName); }); } /** * 將圖片的url路徑轉(zhuǎn)為base64路徑 * 可以用await等待Promise的異步返回 * @param {Object} imgUrl 圖片路徑 */ export function getBase64Sync(imgUrl) { return new Promise(function(resolve, reject) { // 一定要設(shè)置為let,不然圖片不顯示 let image = new Image(); //圖片地址 image.src = imgUrl; // 解決跨域問(wèn)題 image.setAttribute("crossOrigin", '*'); // 支持跨域圖片 // image.onload為異步加載 image.onload = function() { let canvas = document.createElement("canvas"); canvas.width = image.width; canvas.height = image.height; let context = canvas.getContext("2d"); context.drawImage(image, 0, 0, image.width, image.height); //圖片后綴名 let ext = image.src.substring(image.src.lastIndexOf(".") + 1).toLowerCase(); //圖片質(zhì)量 let quality = 0.8; //轉(zhuǎn)成base64 let dataurl = canvas.toDataURL("image/" + ext, quality); //返回 resolve(dataurl); }; }) }
4.vue文件使用
<template> <el-container class="a-section xxx"> <el-button type="success" @click="download">導(dǎo)出導(dǎo)出</el-button> <div class="canvasBox"> 測(cè)試文件內(nèi)容展示 <el-progress :text-inside="true" :stroke-width="26" :percentage="70"></el-progress> <el-progress :text-inside="true" :stroke-width="24" :percentage="100" status="success"></el-progress> <el-progress :text-inside="true" :stroke-width="22" :percentage="80" status="warning"></el-progress> <el-progress :text-inside="true" :stroke-width="20" :percentage="50" status="exception"></el-progress> </div> </el-container> </template> <script> //剛剛創(chuàng)建的js文件 import { exportWord, getBase64Sync } from 'xxxx.js' import html2canvas from 'html2canvas'; export default { name: 'xxx', mounted() { }, methods: { async download() { // 找到需要導(dǎo)出的元素 var oTd = document.querySelector('.canvasBox'); //使用html2canvas生成base64的圖片格式 html2canvas(oTd, { width: Math.floor(oTd.clientWidth), //寬 height: Math.floor(oTd.clientHeight), //高 scale: 2, //設(shè)置像素比 useCORS: true, allowTaint: false, }).then((canvas) => { document.body.appendChild(canvas); var img = document.createElement('img'); //獲取圖片路徑 并且轉(zhuǎn)base64格式 img.src = canvas.toDataURL('image/jpeg'); console.log(img.src, "路徑"); var dataURL = img.src console.log(dataURL, 'base64格式'); img.setAttribute('id', 'canvasImg'); let data = { imglist: this.imglist, imgUrl: dataURL } let imgSize = { //控制導(dǎo)出的word圖片大小 imgurl: [200, 200], }; //導(dǎo)出的文件名稱(chēng) let docxName = "測(cè)試使用.docx"; exportWord("/static/demo.docx", data, docxName, imgSize); }) }, } } </script> <style> </style>
結(jié)果展示
以上就是vue實(shí)現(xiàn)把頁(yè)面導(dǎo)出成word文件的方法的詳細(xì)內(nèi)容,更多關(guān)于vue把頁(yè)面導(dǎo)出成word的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Vue中數(shù)組與對(duì)象修改觸發(fā)頁(yè)面更新的機(jī)制與原理解析
這篇文章主要介紹了Vue中關(guān)于數(shù)組與對(duì)象修改觸發(fā)頁(yè)面更新的機(jī)制與原理簡(jiǎn)析,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-12-12Vue3項(xiàng)目中配置TypeScript和JavaScript的兼容
在Vue3開(kāi)發(fā)中,常見(jiàn)的使用JavaScript(JS)編寫(xiě)代碼,但也會(huì)有調(diào)整編寫(xiě)語(yǔ)言使用TypeScript(TS)的需求,因此,在Vue3項(xiàng)目設(shè)置中兼容TS和JS是刻不容緩的重要任務(wù),2023-08-08vue中關(guān)于v-for循環(huán)key值問(wèn)題的研究
這篇文章主要介紹了vue中關(guān)于v-for循環(huán)key值問(wèn)題的研究,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06Vue element-UI el-select循環(huán)選中的問(wèn)題
這篇文章主要介紹了Vue element-UI el-select循環(huán)選中的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10vue keep-alive 動(dòng)態(tài)刪除組件緩存的例子
今天小編就為大家分享一篇vue keep-alive 動(dòng)態(tài)刪除組件緩存的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11Vue2?響應(yīng)式系統(tǒng)之異步隊(duì)列
這篇文章主要介紹了Vue2?響應(yīng)式系統(tǒng)之異步隊(duì)列,文章基于Vue2?的相關(guān)資料展開(kāi)對(duì)主題的詳細(xì)介紹,具有一定的參考價(jià)值需要的小伙伴可以參考一下2022-04-04Vue遞歸組件+Vuex開(kāi)發(fā)樹(shù)形組件Tree--遞歸組件的簡(jiǎn)單實(shí)現(xiàn)
這篇文章也是我自己開(kāi)發(fā)的從無(wú)到有的過(guò)程,所以它可以為你提供一些Tree組件開(kāi)發(fā)的思路,本文重點(diǎn)給大家介紹vue遞歸組件的簡(jiǎn)單實(shí)現(xiàn),感興趣的朋友跟隨小編一起看看吧2019-04-04vue項(xiàng)目在安卓低版本機(jī)顯示空白的原因分析(兩種)
本文給大家?guī)?lái)vue項(xiàng)目在安卓低版本機(jī)顯示空白的原因分析,根據(jù)各自需求給大家?guī)?lái)了兩種原因分析,大家可以參考下2018-09-09