项目开发中遇到了需要将HTML页面的内容导出为一个word文档,所以有了这边随笔。
当然,项目开发又时间有点紧迫,第一时间想到的是用插件,所以百度了下。下面就介绍两个导出word文档的方法。
备注:兼容IE9以上
大概浏览了下jquery.wordexport.js插件的代码,了解到了通过该插件可以导出文本和图片,而图片首先通过canvas的形式
绘制,文本则需要再依赖FileSaver.js插件,FileSaver.js插件则主要通过H5的文件操作新特性new Blob()和new FileReader()
来实现文本的导出。
插件源码:
FileSaver.js
1 /* FileSaver.js 2 * A saveAs() FileSaver implementation. 3 * 1.3.2 4 * 2016-06-16 18:25:19 5 * 6 * By Eli Grey, 7 * License: MIT 8 * See 9 */ 10 11 /*global self */ 12 /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */ 13 14 /*! @source */ 15 16 var saveAs = saveAs || (function(view) { 17 "use strict"; 18 // IE <10 is explicitly unsupported 19 if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) { 20 return; 21 } 22 var 23 doc = view.document 24 // only get URL when necessary in case Blob.js hasn&#39;t overridden it yet 25 , get_URL = function() { 26 return view.URL || view.webkitURL || view; 27 } 28 , save_link = doc.createElementNS("", "a") 29 , can_use_save_link = "download" in save_link 30 , click = function(node) { 31 var event = new MouseEvent("click"); 32 node.dispatchEvent(event); 33 } 34 , is_safari = /constructor/i.test(view.HTMLElement) 35 , is_chrome_ios =/CriOS\/[\d]+/.test(navigator.userAgent) 36 , throw_outside = function(ex) { 37 (view.setImmediate || view.setTimeout)(function() { 38 throw ex; 39 }, 0); 40 } 41 , force_saveable_type = "application/octet-stream" 42 // the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to 43 , arbitrary_revoke_timeout = 1000 * 40 // in ms 44 , revoke = function(file) { 45 var revoker = function() { 46 if (typeof file === "string") { // file is an object URL 47 get_URL().revokeObjectURL(file); 48 } else { // file is a File 49 file.remove(); 50 } 51 }; 52 setTimeout(revoker, arbitrary_revoke_timeout); 53 } 54 , dispatch = function(filesaver, event_types, event) { 55 event_types = [].concat(event_types); 56 var i = event_types.length; 57 while (i--) { 58 var listener = filesaver["on" + event_types[i]]; 59 if (typeof listener === "function") { 60 try { 61 listener.call(filesaver, event || filesaver); 62 } catch (ex) { 63 throw_outside(ex); 64 } 65 } 66 } 67 } 68 , auto_bom = function(blob) { 69 // prepend BOM for UTF-8 XML and text/* types (including HTML) 70 // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF 71 if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) { 72 return new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type}); 73 } 74 return blob; 75 } 76 , FileSaver = function(blob, name, no_auto_bom) { 77 if (!no_auto_bom) { 78 blob = auto_bom(blob); 79 } 80 // First try a.download, then web filesystem, then object URLs 81 var 82 filesaver = this 83 , type = blob.type 84 , force = type === force_saveable_type 85 , object_url 86 , dispatch_all = function() { 87 dispatch(filesaver, "writestart progress write writeend".split(" ")); 88 } 89 // on any filesys errors revert to saving with object URLs 90 , fs_error = function() { 91 if ((is_chrome_ios || (force && is_safari)) && view.FileReader) { 92 // Safari doesn&#39;t allow downloading of blob urls 93 var reader = new FileReader(); 94 reader.Onloadend= function() { 95 var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, &#39;data:attachment/file;&#39;); 96 var popup = view.open(url, &#39;_blank&#39;); 97 if(!popup) view.location.href = url; 98 url=undefined; // release reference before dispatching 99 filesaver.readyState = filesaver.DONE; 100 dispatch_all(); 101 }; 102 reader.readAsDataURL(blob); 103 filesaver.readyState = filesaver.INIT; 104 return; 105 } 106 // don&#39;t create more object URLs than needed 107 if (!object_url) { 108 object_url = get_URL().createObjectURL(blob); 109 } 110 if (force) { 111 view.location.href = object_url; 112 } else { 113 var opened = view.open(object_url, "_blank"); 114 if (!opened) { 115 // Apple does not allow window.open, see 116 view.location.href = object_url; 117 } 118 } 119 filesaver.readyState = filesaver.DONE; 120 dispatch_all(); 121 revoke(object_url); 122 } 123 ; 124 filesaver.readyState = filesaver.INIT; 125 126 if (can_use_save_link) { 127 object_url = get_URL().createObjectURL(blob); 128 setTimeout(function() { 129 save_link.href = object_url; 130 save_link.download = name; 131 click(save_link); 132 dispatch_all(); 133 revoke(object_url); 134 filesaver.readyState = filesaver.DONE; 135 }); 136 return; 137 } 138 139 fs_error(); 140 } 141 , FS_proto = FileSaver.prototype 142 , saveAs = function(blob, name, no_auto_bom) { 143 return new FileSaver(blob, name || blob.name || "download", no_auto_bom); 144 } 145 ; 146 // IE 10+ (native saveAs) 147 if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) { 148 return function(blob, name, no_auto_bom) { 149 name = name || blob.name || "download"; 150 151 if (!no_auto_bom) { 152 blob = auto_bom(blob); 153 } 154 return navigator.msSaveOrOpenBlob(blob, name); 155 }; 156 } 157 158 FS_proto.abort = function(){}; 159 FS_proto.readyState = FS_proto.INIT = 0; 160 FS_proto.WRITING = 1; 161 FS_proto.DOnE= 2; 162 163 FS_proto.error = 164 FS_proto.Onwritestart= 165 FS_proto.Onprogress= 166 FS_proto.Onwrite= 167 FS_proto.Onabort= 168 FS_proto.Onerror= 169 FS_proto.Onwriteend= 170 null; 171 172 return saveAs; 173 }( 174 typeof self !== "undefined" && self 175 || typeof window !== "undefined" && window 176 || this.content 177 )); 178 // `self` is undefined in Firefox for Android content script context 179 // while `this` is nsIContentFrameMessageManager 180 // with an attribute `content` that corresponds to the window 181 182 if (typeof module !== "undefined" && module.exports) { 183 module.exports.saveAs = saveAs; 184 } else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) { 185 define([], function() { 186 return saveAs; 187 }); 188 }
View Code
jquery.wordexport.js
1 if (typeof jQuery !== "undefined" && typeof saveAs !== "undefined") { 2 (function($) { 3 $.fn.wordExport = function(fileName) { 4 fileName = typeof fileName !== &#39;undefined&#39; ? fileName : "jQuery-Word-Export"; 5 var static = { 6 mhtml: { 7 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\n\n_html_", 8 head: "\n\n\n\n", 9 body: "_body_" 10 } 11 }; 12 var optiOns= { 13 maxWidth: 624 14 }; 15 // Clone selected element before manipulating it 16 var markup = $(this).clone(); 17 18 // Remove hidden elements from the output 19 markup.each(function() { 20 var self = $(this); 21 if (self.is(&#39;:hidden&#39;)) 22 self.remove(); 23 }); 24 25 // Embed all images using Data URLs 26 var images = Array(); 27 var img = markup.find(&#39;img&#39;); 28 for (var i = 0; iView Code
插件调用:
1 2 3 4 5 6 7 89
JS导出Word文档
10 11 12 13 14 15 22 23直接调用wordExport()接口就可以导出word文档,传的参数为导出的word文件名。
补充:
通过我们常规写的外联样式设置样式是无效的,通过个人的实践发现需要写内联样式才能生效,而单位也需要按照word的配置
单位pt设置。
而jquery.wordexport.js插件是要配置了个style样式让我们补充样式设置的:
法二:通过百度js模板引擎生成word文档
主要是通过js模板设置对应的标签,然后XDoc.to(baidu.template())导出word,而通过百度js模板引擎的好处是也可以导出PDF文件。
完整demo:
1 2 3 4 5 6 7 16 17 18 19 20
21 36 37 57 58这里我通过renderTemplate函数叫js模板渲染到HTML中,实现了文本的展示和导出内容的结合。而因为这里导出的word文档是需要特别设置样式的,所以在页面样式展示下我们可以通过添加.class的方式设置。
附部分导出word文档样式设置:
以上就是HTML怎么导出生成word文档?的详细内容,更多请关注 第一PHP社区 其它相关文章!