我如何通过JavaScript和jQuery在word文档的标题中插入图像
通过使用jquery.wordexport.js
和FileSaver.js
我得到一个用给定数据创建的word文档,我必须在jquery.wordexport.js
更改以获取word文档标题中的图像。
请建议使用代码或链接将受到很多赞赏。 提前致谢。
我的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\n\n_html_", head: "\n\n\n_styles_\n\n\n", body: "_body_" } }; var options = { maxWidth: 624 }; // Clone selected element before manipulating it var markup = $(this).clone(); // Remove hidden elements from the output markup.each(function() { var self = $(this); if (self.is(':hidden')) self.remove(); }); // Embed all images using Data URLs var images = Array(); var img = markup.find('img'); for (var i = 0; i < img.length; i++) { // Calculate dimensions of output image var w = Math.min(img[i].width, options.maxWidth); var h = img[i].height * (w / img[i].width); // Create canvas for converting image to data URL var canvas = document.createElement("CANVAS"); canvas.width = w; canvas.height = h; // Draw image to canvas var context = canvas.getContext('2d'); context.drawImage(img[i], 0, 0, w, h); // Get data URL encoding of image var uri = canvas.toDataURL("image/png"); $(img[i]).attr("src", img[i].src); img[i].width = w; img[i].height = h; // Save encoded image to array images[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 data var 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 stylesheet var styles = ""; // Aggregate parts of the file together var 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 contents var 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)"); } }
我的FileSaver.js如下
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ var saveAs=saveAs||function(e){"use strict";if("undefined"==typeof navigator||!/MSIE [1-9]\./.test(navigator.userAgent)){var t=e.document,n=function(){return e.URL||e.webkitURL||e},o=t.createElementNS("http://www.w3.org/1999/xhtml","a"),r="download"in o,i=function(e){var t=new MouseEvent("click");e.dispatchEvent(t)},a=/Version\/[\d\.]+.*Safari/.test(navigator.userAgent),c=e.webkitRequestFileSystem,d=e.requestFileSystem||c||e.mozRequestFileSystem,u=function(t){(e.setImmediate||e.setTimeout)(function(){throw t},0)},s="application/octet-stream",f=0,l=4e4,v=function(e){var t=function(){"string"==typeof e?n().revokeObjectURL(e):e.remove()};setTimeout(t,l)},p=function(e,t,n){t=[].concat(t);for(var o=t.length;o--;){var r=e["on"+t[o]];if("function"==typeof r)try{r.call(e,n||e)}catch(i){u(i)}}},w=function(e){return/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob(["\uFEFF",e],{type:e.type}):e},y=function(t,u,l){l||(t=w(t));var y,m,S,h=this,R=t.type,O=!1,g=function(){p(h,"writestart progress write writeend".split(" "))},b=function(){if(m&&a&&"undefined"!=typeof FileReader){var o=new FileReader;return o.onloadend=function(){var e=o.result;m.location.href="data:attachment/file"+e.slice(e.search(/[,;]/)),h.readyState=h.DONE,g()},o.readAsDataURL(t),void(h.readyState=h.INIT)}if((O||!y)&&(y=n().createObjectURL(t)),m)m.location.href=y;else{var r=e.open(y,"_blank");void 0===r&&a&&(e.location.href=y)}h.readyState=h.DONE,g(),v(y)},E=function(e){return function(){return h.readyState!==h.DONE?e.apply(this,arguments):void 0}},N={create:!0,exclusive:!1};return h.readyState=h.INIT,u||(u="download"),r?(y=n().createObjectURL(t),void setTimeout(function(){o.href=y,o.download=u,i(o),g(),v(y),h.readyState=h.DONE})):(e.chrome&&R&&R!==s&&(S=t.slice||t.webkitSlice,t=S.call(t,0,t.size,s),O=!0),c&&"download"!==u&&(u+=".download"),(R===s||c)&&(m=e),d?(f+=t.size,void d(e.TEMPORARY,f,E(function(e){e.root.getDirectory("saved",N,E(function(e){var n=function(){e.getFile(u,N,E(function(e){e.createWriter(E(function(n){n.onwriteend=function(t){m.location.href=e.toURL(),h.readyState=h.DONE,p(h,"writeend",t),v(e)},n.onerror=function(){var e=n.error;e.code!==e.ABORT_ERR&&b()},"writestart progress write abort".split(" ").forEach(function(e){n["on"+e]=h["on"+e]}),n.write(t),h.abort=function(){n.abort(),h.readyState=h.DONE},h.readyState=h.WRITING}),b)}),b)};e.getFile(u,{create:!1},E(function(e){e.remove(),n()}),E(function(e){e.code===e.NOT_FOUND_ERR?n():b()}))}),b)}),b)):void b())},m=y.prototype,S=function(e,t,n){return new y(e,t,n)};return"undefined"!=typeof navigator&&navigator.msSaveOrOpenBlob?function(e,t,n){return n||(e=w(e)),navigator.msSaveOrOpenBlob(e,t||"download")}:(m.abort=function(){var e=this;e.readyState=e.DONE,p(e,"abort")},m.readyState=m.INIT=0,m.WRITING=1,m.DONE=2,m.error=m.onwritestart=m.onprogress=m.onwrite=m.onabort=m.onerror=m.onwriteend=null,S)}}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||this.content);"undefined"!=typeof module&&module.exports?module.exports.saveAs=saveAs:"undefined"!=typeof define&&null!==define&&null!==define.amd&&define([],function(){return saveAs});
wordexport.js
利用Word在.doc
文件中呈现HTML内容的能力。 所以答案就像将图像添加到HTML文档一样: img
标记:
... 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\n\n_html_", head: "\n\n\n\n", body: "_body_" } }; ...
根据此页面 ,适当地设置mso-element
样式可用于指定页眉和页脚。 如果没有完全尝试,你可能还必须将页眉/页脚视为一个单独的文件(它在“文件的聚合部分”中合并在一起):