LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

[点晴永久免费OA]js将HTML导出生成word文档

admin
2022年4月14日 18:11 本文热度 2162

在项目开发中中,遇到将HTML导出生成word文档,刚开始在网上找了很多资料,基本都是jQuery中的插件jquery.wordexport.js,刚开始是不想用这个的,这个要引用另一个插件FileSaver.js;但是没有找到更好的方法,所以在这里记录下js将HTML导出生成word文档的方法;如果有其他方法的可以提供下链接;学习下

jquery.wordexport.js插件的代码,了解到了通过该插件可以导出文本和图片,而图片首先通过canvas的形式

绘制,文本则需要再依赖FileSaver.js插件,FileSaver.js插件则主要通过H5的文件操作新特性new Blob()和new FileReader()

来实现文本的导出。

在这里给出jquery.wordexport.js源码

  1. if (typeof jQuery !== "undefined" && typeof saveAs !== "undefined") {
  2. (function ($) {
  3. $.fn.wordExport = function (fileName) {
  4. fileName = typeof fileName !== 'undefined' ? fileName : "jQuery-Word-Export";
  5. var statics = {
  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<!DOCTYPE html>\n<html>\n_html_</html>",
  8. head: "<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<style>\n_styles_\n</style>\n</head>\n",
  9. body: "<body>_body_</body>"
  10. }
  11. };
  12. var options = {
  13. maxWidth: 624
  14. };
  15. // Clone selected element before manipulating it
  16. var markup = $(this).clone();
  17. // Remove hidden elements from the output
  18. markup.each(function () {
  19. var self = $(this);
  20. if (self.is(':hidden'))
  21. self.remove();
  22. });
  23. // Embed all images using Data URLs
  24. var images = Array();
  25. var img = markup.find('img');
  26. for (var i = 0; i < img.length; i++) {
  27. // Calculate dimensions of output image
  28. var w = Math.min(img[i].width, options.maxWidth);
  29. var h = img[i].height * (w / img[i].width);
  30. // create canvas for converting image to data URL
  31. var canvas = document.createElement("CANVAS");
  32. canvas.width = w;
  33. canvas.height = h;
  34. // Draw image to canvas
  35. var context = canvas.getContext('2d');
  36. context.drawImage(img[i], 0, 0, w, h);
  37. // Get data URL encoding of image
  38. var uri = canvas.toDataURL("image/png/jpg");
  39. $(img[i]).attr("src", img[i].src);
  40. img[i].width = w;
  41. img[i].height = h;
  42. // Save encoded image to array
  43. images[i] = {
  44. type: uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")),
  45. encoding: uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")),
  46. location: $(img[i]).attr("src"),
  47. data: uri.substring(uri.indexOf(",") + 1)
  48. };
  49. }
  50. // Prepare bottom of mhtml file with image data
  51. var mhtmlBottom = "\n";
  52. for (var i = 0; i < images.length; i++) {
  53. mhtmlBottom += "--NEXT.ITEM-BOUNDARY\n";
  54. mhtmlBottom += "Content-Location: " + images[i].location + "\n";
  55. mhtmlBottom += "Content-Type: " + images[i].type + "\n";
  56. mhtmlBottom += "Content-Transfer-Encoding: " + images[i].encoding + "\n\n";
  57. mhtmlBottom += images[i].data + "\n\n";
  58. }
  59. mhtmlBottom += "--NEXT.ITEM-BOUNDARY--";
  60. //TODO: load css from included stylesheet
  61. //var styles=' /* Font Definitions */@font-face{font-family:宋体;panose-1:2 1 6 0 3 1 1 1 1 1;mso-font-alt:SimSun;mso-font-charset:134;mso-generic-font-family:auto;mso-font-pitch:variable;mso-font-signature:3 680460288 22 0 262145 0;} @font-face{font-family:"Cambria Math";panose-1:2 4 5 3 5 4 6 3 2 4;mso-font-charset:1;mso-generic-font-family:roman;mso-font-format:other;mso-font-pitch:variable;mso-font-signature:0 0 0 0 0 0;} @font-face{font-family:"\@宋体";panose-1:2 1 6 0 3 1 1 1 1 1;mso-font-charset:134;mso-generic-font-family:auto;mso-font-pitch:variable;mso-font-signature:3 680460288 22 0 262145 0;}/* Style Definitions */p.MsoNormal, li.MsoNormal, div.MsoNormal{mso-style-unhide:no;mso-style-qformat:yes;mso-style-parent:"";margin:0cm;margin-bottom:.0001pt;mso-pagination:widow-orphan;font-size:14.0pt;font-family:宋体;mso-bidi-font-family:宋体;}p.MsoHeader, li.MsoHeader, div.MsoHeader{mso-style-noshow:yes;mso-style-priority:99;mso-style-link:"页眉 Char";margin:0cm;margin-bottom:.0001pt;text-align:center;mso-pagination:widow-orphan;layout-grid-mode:char;font-size:9.0pt;font-family:宋体;mso-bidi-font-family:宋体;}p.MsoFooter, li.MsoFooter, div.MsoFooter{mso-style-noshow:yes;mso-style-priority:99;mso-style-link:"页脚 Char";margin:0cm;margin-bottom:.0001pt;mso-pagination:widow-orphan;layout-grid-mode:char;font-size:9.0pt;font-family:宋体;mso-bidi-font-family:宋体;}p.MsoAcetate, li.MsoAcetate, div.MsoAcetate{mso-style-noshow:yes;mso-style-priority:99;mso-style-link:"批注框文本 Char";margin:0cm;margin-bottom:.0001pt;mso-pagination:widow-orphan;font-size:9.0pt;font-family:宋体;mso-bidi-font-family:宋体;}span.Char{mso-style-name:"页眉 Char";mso-style-noshow:yes;mso-style-priority:99;mso-style-unhide:no;mso-style-locked:yes;mso-style-link:页眉;font-family:宋体;mso-ascii-font-family:宋体;mso-fareast-font-family:宋体;mso-hansi-font-family:宋体;}span.Char0{mso-style-name:"页脚 Char";mso-style-noshow:yes;mso-style-priority:99;mso-style-unhide:no;mso-style-locked:yes;mso-style-link:页脚;font-family:宋体;mso-ascii-font-family:宋体;mso-fareast-font-family:宋体;mso-hansi-font-family:宋体;}span.Char1{mso-style-name:"批注框文本 Char";mso-style-noshow:yes;mso-style-priority:99;mso-style-unhide:no;mso-style-locked:yes;mso-style-link:批注框文本;font-family:宋体;mso-ascii-font-family:宋体;mso-fareast-font-family:宋体;mso-hansi-font-family:宋体;}p.msochpdefault, li.msochpdefault, div.msochpdefault{mso-style-name:msochpdefault;mso-style-unhide:no;mso-margin-top-alt:auto;margin-right:0cm;mso-margin-bottom-alt:auto;margin-left:0cm;mso-pagination:widow-orphan;font-size:10.0pt;font-family:宋体;mso-bidi-font-family:宋体;}span.msonormal0{mso-style-name:msonormal;mso-style-unhide:no;}.MsoChpDefault{mso-style-type:export-only;mso-default-props:yes;font-size:10.0pt;mso-ansi-font-size:10.0pt;mso-bidi-font-size:10.0pt;mso-ascii-font-family:"Times New Roman";mso-hansi-font-family:"Times New Roman";mso-font-kerning:0pt;}/* Page Definitions */ @page WordSection1{size:595.3pt 841.14px;margin:72.0pt 90.0pt 72.0pt 90.0pt;mso-header-margin:42.55pt;mso-footer-margin:49.6pt;mso-paper-source:0;}div.WordSection1{page:WordSection1;}';
  62. var styles = "";
  63. // Aggregate parts of the file together
  64. var fileContent = statics.mhtml.top.replace("_html_", statics.mhtml.head.replace("_styles_", styles) + statics.mhtml.body.replace("_body_", markup.html())) + mhtmlBottom;
  65. // create a Blob with the file contents
  66. var blob = new Blob([fileContent], {
  67. type: "application/msword;charset=utf-8"
  68. });
  69. saveAs(blob, fileName + ".doc");
  70. };
  71. })(jQuery);
  72. } else {
  73. if (typeof jQuery === "undefined") {
  74. console.error("jQuery Word Export: missing dependency (jQuery)");
  75. }
  76. if (typeof saveAs === "undefined") {
  77. console.error("jQuery Word Export: missing dependency (FileSaver.js)");
  78. }
  79. }

和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, http://eligrey.com
  7. * License: MIT
  8. * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
  9. */
  10. /*global self */
  11. /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
  12. /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
  13. var saveAs = saveAs || (function (view) {
  14. "use strict";
  15. // IE <10 is explicitly unsupported
  16. if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
  17. return;
  18. }
  19. var
  20. doc = view.document
  21. // only get URL when necessary in case Blob.js hasn't overridden it yet
  22. , get_URL = function () {
  23. return view.URL || view.webkitURL || view;
  24. }
  25. , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
  26. , can_use_save_link = "download" in save_link
  27. , click = function (node) {
  28. var event = new MouseEvent("click");
  29. node.dispatchEvent(event);
  30. }
  31. , is_safari = /constructor/i.test(view.HTMLElement)
  32. , is_chrome_ios = /CriOS\/[\d]+/.test(navigator.userAgent)
  33. , throw_outside = function (ex) {
  34. (view.setImmediate || view.setTimeout)(function () {
  35. throw ex;
  36. }, 0);
  37. }
  38. , force_saveable_type = "application/octet-stream"
  39. // the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to
  40. , arbitrary_revoke_timeout = 1000 * 40 // in ms
  41. , revoke = function (file) {
  42. var revoker = function () {
  43. if (typeof file === "string") { // file is an object URL
  44. get_URL().revokeObjectURL(file);
  45. } else { // file is a File
  46. file.remove();
  47. }
  48. };
  49. setTimeout(revoker, arbitrary_revoke_timeout);
  50. }
  51. , dispatch = function (filesaver, event_types, event) {
  52. event_types = [].concat(event_types);
  53. var i = event_types.length;
  54. while (i--) {
  55. var listener = filesaver["on" + event_types[i]];
  56. if (typeof listener === "function") {
  57. try {
  58. listener.call(filesaver, event || filesaver);
  59. } catch (ex) {
  60. throw_outside(ex);
  61. }
  62. }
  63. }
  64. }
  65. , auto_bom = function (blob) {
  66. // prepend BOM for UTF-8 XML and text/* types (including HTML)
  67. // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
  68. if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  69. return new Blob([String.fromCharCode(0xFEFF), blob], { type: blob.type });
  70. }
  71. return blob;
  72. }
  73. , FileSaver = function (blob, name, no_auto_bom) {
  74. if (!no_auto_bom) {
  75. blob = auto_bom(blob);
  76. }
  77. // First try a.download, then web filesystem, then object URLs
  78. var
  79. filesaver = this
  80. , type = blob.type
  81. , force = type === force_saveable_type
  82. , object_url
  83. , dispatch_all = function () {
  84. dispatch(filesaver, "writestart progress write writeend".split(" "));
  85. }
  86. // on any filesys errors revert to saving with object URLs
  87. , fs_error = function () {
  88. if ((is_chrome_ios || (force && is_safari)) && view.FileReader) {
  89. // Safari doesn't allow downloading of blob urls
  90. var reader = new FileReader();
  91. reader.onloadend = function () {
  92. var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');
  93. var popup = view.open(url, '_blank');
  94. if (!popup) view.location.href = url;
  95. url = undefined; // release reference before dispatching
  96. filesaver.readyState = filesaver.DONE;
  97. dispatch_all();
  98. };
  99. reader.readAsDataURL(blob);
  100. filesaver.readyState = filesaver.INIT;
  101. return;
  102. }
  103. // don't create more object URLs than needed
  104. if (!object_url) {
  105. object_url = get_URL().createObjectURL(blob);
  106. }
  107. if (force) {
  108. view.location.href = object_url;
  109. } else {
  110. var opened = view.open(object_url, "_blank");
  111. if (!opened) {
  112. // Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html
  113. view.location.href = object_url;
  114. }
  115. }
  116. filesaver.readyState = filesaver.DONE;
  117. dispatch_all();
  118. revoke(object_url);
  119. }
  120. ;
  121. filesaver.readyState = filesaver.INIT;
  122. if (can_use_save_link) {
  123. object_url = get_URL().createObjectURL(blob);
  124. setTimeout(function () {
  125. save_link.href = object_url;
  126. save_link.download = name;
  127. click(save_link);
  128. dispatch_all();
  129. revoke(object_url);
  130. filesaver.readyState = filesaver.DONE;
  131. });
  132. return;
  133. }
  134. fs_error();
  135. }
  136. , FS_proto = FileSaver.prototype
  137. , saveAs = function (blob, name, no_auto_bom) {
  138. return new FileSaver(blob, name || blob.name || "download", no_auto_bom);
  139. }
  140. ;
  141. // IE 10+ (native saveAs)
  142. if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
  143. return function (blob, name, no_auto_bom) {
  144. name = name || blob.name || "download";
  145. if (!no_auto_bom) {
  146. blob = auto_bom(blob);
  147. }
  148. return navigator.msSaveOrOpenBlob(blob, name);
  149. };
  150. }
  151. FS_proto.abort = function () { };
  152. FS_proto.readyState = FS_proto.INIT = 0;
  153. FS_proto.WRITING = 1;
  154. FS_proto.DONE = 2;
  155. FS_proto.error =
  156. FS_proto.onwritestart =
  157. FS_proto.onprogress =
  158. FS_proto.onwrite =
  159. FS_proto.onabort =
  160. FS_proto.onerror =
  161. FS_proto.onwriteend =
  162. null;
  163. return saveAs;
  164. }(
  165. typeof self !== "undefined" && self
  166. || typeof window !== "undefined" && window
  167. || this.content
  168. ));
  169. // `self` is undefined in Firefox for Android content script context
  170. // while `this` is nsIContentFrameMessageManager
  171. // with an attribute `content` that corresponds to the window
  172. if (typeof module !== "undefined" && module.exports) {
  173. module.exports.saveAs = saveAs;
  174. } else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) {
  175. define([], function () {
  176. return saveAs;
  177. });
  178. }

调用插件

  1. <!DOCTYPE html>
  2. <html>
  3. <head lang="en">
  4. <meta charset="UTF-8">
  5. <title>html导出生成word文档</title>
  6. </head>
  7. <body>
  8. <div class="word">
  9. <h1>我们的梦想来自内心深处的孤独</h1>>
  10. <p align="center" style="font-size:20pt;font-weight:bold;">JS导出Word文档</p>
  11. <div>我们来自同一个世界</div>
  12. </div>
  13. <input type="button" value="导出word">
  14. <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.js"></script>
  15. <script type="text/javascript" src="FileSaver.js"></script>
  16. <script type="text/javascript" src="jquery.wordexport.js"></script>
  17. <script>
  18. $(function () {
  19. $("input[type='button']").click(function (event) {
  20. $(".word").wordExport('word文档');
  21. });
  22. })
  23. </script>
  24. </body>
  25. </html>

导出的html代码样式需要内联样式,

2.vue中使用

首先看看结构目录

2.1 在index.html全局引入jQuery

2.2   cmd安装FileSaver.js

npm install file-saver --save

在需要的组件中引入file-saver

2.3  在需要的组件中引入

2.4使用

.wordExport("生成文档");这个是生成文档的文件名


该文章在 2022/4/14 18:11:57 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved