前端实现 html 下载(保存)为 word 格式的文件
前端實現 html 下載(保存)為 word 格式的文件
需求:不依靠后端的文件鏈接,直接將頁面中的 DOM 元素轉碼為相應的 word 文檔,并保持頁面風格大致不變。
前端一般的下載文件的方式
前端下載文件大致有三種方式,網上都有相應的答案,但是總的來說是通過 a 標簽的her直接訪問或者 a 標簽的H5的download方法來實現,此處我不多贅述,詳情請參考網上的答案
我這里要說的是,如何將一個頁面上的某個 DOM 元素直接轉換成 Word 文件; 并且保存到本地,注意這里沒有下載,只是獲取DOM然后轉存為Word文件,說白了其實就是一種格式的轉換。
如何轉換呢?總的來講,我們要借助JQuery來實現,具體來說就是jquery.wordexport.js,所以首先要在頁面中引入JQ,JQ有許多的版本,網上也有許多的CDN鏈接,我這里使用的是百度的JQ CDN,當然也可以自己 npm i JQ,然后實現全局的引用。
首先你需要引入三個文件
<!-- 引入下載功能的jq依賴 --><script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script><!-- 引入文件保存功能的js--><script type="text/javascript" src="js/FileSaver.js"></script><!-- 引入導出文件的JQ方法--><script type="text/javascript" src="js/jquery.wordexport.js"></script>下邊兩個文件需要自行下載到本地,然后使用script標簽進行相應的引入
文件源碼附在后邊
然后的操作就是
<script type="text/javascript">// 獲取某個元素,添加點擊事件,獲取目標元素,通過wordExport方法實現導入$(".export_button").click(function(event) {$("#pagecontent").wordExport();});</script>當然這是最基本的操作,如果你要在Vue中使用應該怎么辦呢?
看這里!!!
首先你需要在 根元素 app.html 中引入相應的JQ 依賴,或者直接npm i 安裝相應的JQ 環境
然后將 FileSaver.js 以及 jquery.wordexport.js 文件下載到本地進行引用,具體的代碼如下
然后Vue的頁面中有這樣一個標簽
<div class="law-essay-export-contents"><h2 class="law-essay-title" style="text-align:center">{{essayData.title||''}}</h2><div class="law-essay-contents" v-html="essayData.content"></div> </div><div class="download-button" @click="exportDocs(essayData.title||'',essayData.id)">立即下載</div> export default {methods:{exportDocs(title){try{$(".law-essay-export-contents").wordExport(title);}catch{console.error('下載失敗,請稍后重試!');}},} }這樣你就能夠實現相應的頁面下載和保存了
- 當然如果你也想像我一樣使用了后端傳過來的富文本,并且使用 v-html 注入到頁面的話,這里還可以再次優化,我們可以在 node 層對富文本字符串進行解碼,然后返回頁面
- 之后你就能夠直接操作富文本,而不用直接獲取元素,因為直接操作元素,往其中追加樣式或者內容的話,會改變頁面本身的樣式,這樣不太好,所以這里我補充下我優化之后的方法,直接動態創建dom,返回自定義樣式的word文件
雖然堆的東西有點多,但是耐心看完還是會有很大收獲的,這是我工作中遇到的問題,如有不成熟的地方,請大家多多包涵,也歡迎大家多多指點!
附錄
【源碼1】 FileSaver
【源碼2】 FileSaver </jquery.wordexport.js>
if (typeof jQuery !== "undefined" && typeof saveAs !== "undefined") {(function($) {$.fn.wordExport = function(fileName) {fileName = typeof fileName !== 'undefined' ? fileName : "jQuery-Word-Export";var static = {mhtml: {top: "Mime-Version: 1.0\nContent-Base: " + location.href + "\nContent-Type: Multipart/related; boundary=\"NEXT.ITEM-BOUNDARY\";type=\"text/html\"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset=\"utf-8\"\nContent-Location: " + location.href + "\n\n<!DOCTYPE html>\n<html>\n_html_</html>",head: "<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<style>\n_styles_\n</style>\n</head>\n",body: "<body>_body_</body>"}};var options = {maxWidth: 624};// Clone selected element before manipulating itvar markup = $(this).clone();// Remove hidden elements from the outputmarkup.each(function() {var self = $(this);if (self.is(':hidden'))self.remove();});// Embed all images using Data URLsvar images = Array();var img = markup.find('img');for (var i = 0; i < img.length; i++) {// Calculate dimensions of output imagevar w = Math.min(img[i].width, options.maxWidth);var h = img[i].height * (w / img[i].width);// Create canvas for converting image to data URLvar canvas = document.createElement("CANVAS");canvas.width = w;canvas.height = h;// Draw image to canvasvar context = canvas.getContext('2d');context.drawImage(img[i], 0, 0, w, h);// Get data URL encoding of imagevar uri = canvas.toDataURL("image/png");$(img[i]).attr("src", img[i].src);img[i].width = w;img[i].height = h;// Save encoded image to arrayimages[i] = {type: uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")),encoding: uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")),location: $(img[i]).attr("src"),data: uri.substring(uri.indexOf(",") + 1)};}// Prepare bottom of mhtml file with image datavar mhtmlBottom = "\n";for (var i = 0; i < images.length; i++) {mhtmlBottom += "--NEXT.ITEM-BOUNDARY\n";mhtmlBottom += "Content-Location: " + images[i].location + "\n";mhtmlBottom += "Content-Type: " + images[i].type + "\n";mhtmlBottom += "Content-Transfer-Encoding: " + images[i].encoding + "\n\n";mhtmlBottom += images[i].data + "\n\n";}mhtmlBottom += "--NEXT.ITEM-BOUNDARY--";//TODO: load css from included stylesheetvar styles = "";// Aggregate parts of the file togethervar fileContent = static.mhtml.top.replace("_html_", static.mhtml.head.replace("_styles_", styles) + static.mhtml.body.replace("_body_", markup.html())) + mhtmlBottom;// Create a Blob with the file contentsvar blob = new Blob([fileContent], {type: "application/msword;charset=utf-8"});saveAs(blob, fileName + ".doc");};})(jQuery); } else {if (typeof jQuery === "undefined") {console.error("jQuery Word Export: missing dependency (jQuery)");}if (typeof saveAs === "undefined") {console.error("jQuery Word Export: missing dependency (FileSaver.js)");} }總結
以上是生活随笔為你收集整理的前端实现 html 下载(保存)为 word 格式的文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 百鸡百钱问题-从枚举到数学
- 下一篇: 不同传输速率的高速数据采集卡的使用方法