exportWord.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. function _initData(exPortData) {
  2. exPortData.fileName =
  3. typeof exPortData.fileName !== "undefined"
  4. ? exPortData.fileName
  5. : "jQuery-Word-Export";
  6. exPortData.fileType =
  7. typeof exPortData.fileType !== "undefined" ? exPortData.fileType : ".doc";
  8. }
  9. function getModelHtml(mhtml, mhtmlBottom, exPortData) {
  10. // console.log(exPortData.dev);
  11. var styles,
  12. updateStyles,
  13. Brow = '',
  14. direction =
  15. typeof exPortData.direction !== "undefined"
  16. ? exPortData.direction
  17. : "Vertical",
  18. header,
  19. dev =
  20. typeof exPortData.dev !== "undefined"
  21. ? exPortData.dev
  22. : " margin:72.0pt 90.0pt 72.0pt 90.0pt;",
  23. footer = "";
  24. let devStyle = typeof exPortData.style !== 'undefined'
  25. ? exPortData.style
  26. : ''
  27. if (exPortData.styles) {
  28. styles = exPortData.styles.html();
  29. }
  30. if (exPortData.updateExportCss) {
  31. updateStyles = exPortData.updateExportCss.html();
  32. }
  33. if (exPortData.direction == "Horizontal") {
  34. // 横向
  35. direction = `
  36. @page Section1{
  37. size:841.95pt 595.35pt;
  38. mso-page-orientation:landscape;
  39. margin:90.0pt 72.0pt 90.0pt 72.0pt;
  40. mso-header-margin:42.55pt;
  41. mso-footer-margin:49.6pt;
  42. mso-gutter-margin:0.0pt;
  43. mso-paper-source:0;
  44. padding:24.0pt 24.0pt 24.0pt 24.0pt;
  45. layout-grid:16.3pt;
  46. }
  47. div.Section1{
  48. page:Section1;
  49. }
  50. `;
  51. } else {
  52. // 纵向
  53. direction = `
  54. @page Section1{
  55. size:595.35pt 841.95pt;
  56. mso-page-orientation:luprightness;
  57. ${dev}
  58. mso-header-margin:42.55pt;
  59. mso-footer-margin:49.6pt;
  60. mso-gutter-margin:0.0pt;
  61. mso-paper-source:0;
  62. padding:24.0pt 24.0pt 24.0pt 24.0pt;
  63. layout-grid:16.3pt;
  64. }
  65. div.Section1{
  66. page:Section1;
  67. }
  68. `;
  69. }
  70. if (typeof exPortData.header !== 'undefined') {
  71. header =
  72. '<div style="mso-element:header;padding-bottom:20px;" id="h1">\n' +
  73. '<p class="MsoHeader">' +
  74. exPortData.header +
  75. "</p>\n" +
  76. "</div>";
  77. }
  78. if (typeof exPortData.footer !== 'undefined') {
  79. footer =
  80. '<div style="mso-element:footer;text-align: center;" id="f1">\n' +
  81. '<p class="MsoHeader">' +
  82. exPortData.footer +
  83. "</p>\n" +
  84. '<p class="MsoNum"><span class="num" style="mso-field-code: PAGE "></span>/<span style="mso-field-code:NUMPAGES"></span>\n</p>\n' +
  85. "</div>";
  86. }
  87. if (typeof exPortData.header !== 'undefined' && typeof exPortData.footer !== 'undefined') {
  88. Brow = `
  89. <table id="hrdftrtbl" border="0" cellspacing="0" cellpadding="0">
  90. <tbody>
  91. <tr>
  92. <td>
  93. ${header}
  94. </td>
  95. <td>
  96. ${footer}
  97. </td>
  98. </tr>
  99. </tbody>
  100. </table>
  101. `
  102. }
  103. // console.log(devStyle);
  104. return `
  105. <!DOCTYPE html>
  106. <html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\" xmlns=\"http://www.w3.org/TR/REC-html40\">
  107. <head>
  108. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  109. <!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val=\"Cambria Math\"/><m:brkBin m:val=\"before\"/><m:brkBinSub m:val=\"--\"/><m:smallFrac m:val=\"off\"/><m:dispDef/><m:lMargin m:val=\"0\"/> <m:rMargin m:val=\"0\"/><m:defJc m:val=\"centerGroup\"/><m:wrapIndent m:val=\"1440\"/><m:intLim m:val=\"subSup\"/><m:naryLim m:val=\"undOvr\"/></m:mathPr></w:WordDocument></xml><![endif]-->
  110. <style type="text/css">
  111. table#hrdftrtbl {
  112. width: 1px;
  113. height: 1px;
  114. overflow: hidden;
  115. }
  116. p.MsoHeader {
  117. font-size: 20px;
  118. font-weight: bold;
  119. text-align: center;
  120. }
  121. p.MsoFooter, li.MsoFooter, div.MsoFooter {
  122. margin: 0in;
  123. mso-pagination: widow-orphan;
  124. tab-stops: center 3.0in right 6.0in;
  125. font-size: 20pt;
  126. font-weight: bold
  127. }
  128. p.MsoNum{
  129. text-align: center;
  130. }
  131. /*FontDefinitions*/
  132. @page Section1 {
  133. mso-title-page:yes; //首页不显示页眉页脚
  134. mso-page-numbers:0; //起始页码从0开始
  135. mso-header-margin: 20px;
  136. mso-footer-margin: 20px;
  137. mso-header: h1;
  138. mso-footer: f1;
  139. }
  140. div.Section1 {
  141. page: WordSection;
  142. }
  143. ${direction}
  144. ${devStyle}
  145. ${styles}
  146. ${updateStyles}
  147. </style>
  148. </head>
  149. <body lang=ZH-CN style="tab-interval:21.0pt">
  150. <div class="Section1">
  151. ${mhtml}
  152. ${Brow}
  153. </div>
  154. </body>
  155. </html>
  156. ${mhtmlBottom}
  157. `;
  158. }
  159. const exportWord = function (exPortData) {
  160. // console.log(exPortData, 1);
  161. // 文档类型 fileType 可以doc xls html 其他的自己去试
  162. if (typeof jQuery !== "undefined" && typeof saveAs !== "undefined") {
  163. _initData(exPortData);
  164. var options = {
  165. maxWidth: 624,
  166. };
  167. // Clone selected element before manipulating it
  168. var markup = $(exPortData.dom).clone();
  169. // Remove hidden elements from the output
  170. markup.each(function () {
  171. var self = $(exPortData.dom);
  172. if (self.is(":hidden")) self.remove();
  173. });
  174. // Embed all images using Data URLs
  175. var images = Array();
  176. var img = markup.find("img");
  177. for (var i = 0; i < img.length; i++) {
  178. // Calculate dimensions of output image
  179. var w = Math.min(img[i].width, options.maxWidth);
  180. var h = img[i].height * (w / img[i].width);
  181. // Create canvas for converting image to data URL
  182. var canvas = document.createElement("CANVAS");
  183. canvas.width = w;
  184. canvas.height = h;
  185. // Draw image to canvas
  186. var context = canvas.getContext("2d");
  187. context.drawImage(img[i], 0, 0, w, h);
  188. // Get data URL encoding of image
  189. var uri = canvas.toDataURL("image/png");
  190. $(img[i]).attr("src", img[i].src);
  191. img[i].width = w;
  192. img[i].height = h;
  193. // Save encoded image to array
  194. images[i] = {
  195. type: uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")),
  196. encoding: uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")),
  197. location: $(img[i]).attr("src"),
  198. data: uri.substring(uri.indexOf(",") + 1),
  199. };
  200. }
  201. // Prepare bottom of mhtml file with image data
  202. var mhtmlBottom = "\n";
  203. for (var i = 0; i < images.length; i++) {
  204. mhtmlBottom += "--NEXT.ITEM-BOUNDARY\n";
  205. mhtmlBottom += "Content-Location: " + images[i].location + "\n";
  206. mhtmlBottom += "Content-Type: " + images[i].type + "\n";
  207. mhtmlBottom +=
  208. "Content-Transfer-Encoding: " + images[i].encoding + "\n\n";
  209. mhtmlBottom += images[i].data + "\n\n";
  210. }
  211. mhtmlBottom += "--NEXT.ITEM-BOUNDARY--";
  212. var fileContent = getModelHtml(markup.html(), mhtmlBottom, exPortData);
  213. // console.log(fileContent, 22);
  214. var blob = new Blob([fileContent], {
  215. type: "application/msword;charset=utf-8",
  216. });
  217. saveAs(blob, exPortData.fileName + exPortData.fileType);
  218. } else {
  219. if (typeof jQuery === "undefined") {
  220. console.error("Please make sure your (jQuery) exists --faith");
  221. }
  222. if (typeof saveAs === "undefined") {
  223. console.error("Please make sure your (FileSaver.js) exists --faith");
  224. }
  225. }
  226. };
  227. export default exportWord;