html2word
Version:
this is a module that turn .html to .doc
126 lines (121 loc) • 6.54 kB
JavaScript
/**
* Created by fqh on 2017/3/24.
*/
var saveAs = require('./FileSaver.js');
var jQuery = window.jQuery || jQuery || $ || require('jquery')
(function (factory, jQuery, saveAs) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(jQuery, saveAs);
} else {
factory(jQuery, saveAs);
}
}(function ($, saveAs) {
if (typeof jQuery !== "undefined" && typeof saveAs !== "undefined") {
(function($) {
$.fn.wordExport = function(fileName, style) {
fileName = typeof fileName !== 'undefined' ? fileName : "jQuery-Word-Export";
// var style = "_styles_";
var comptent = {
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 it
var markup = $(this).clone(true, true); //在jquery中fn的this指代获取的jquery对象
// 保持和原来一样的外部样式
// Remove hidden elements from the output 去掉被隐藏的元素
markup.each(function() {
var self = $(this);
if (self.is(':hidden'))
self.remove();
});
// 把canvas转换为image导出
var canvases = markup.find('canvas');
for (var j = 0; j < canvases.length; j++) {
var width = canvases[j].width;
var height = canvases[j].height;
var str = 'width:' + width + 'px; height:' + height + 'px;';
str += canvases.eq(j).attr('style');
var imgData = canvases[j].toDataURL("image/jpg");
var canvas2img = document.createElement('img');
canvas2img.setAttribute('src', imgData);
canvas2img.style = str;
canvas2img.className = 'myCanvas' + j;
canvas2img.onload = function (j) {
canvases.eq(j).replaceWith($('img.myCanvas' + j));
}
}
// Embed all images using Data URLs
var images = [];
var img = markup.find('img');
for (var k = 0; k < img.length; k++) {
// Calculate dimensions of output image
var w = Math.min(img[k].width, options.maxWidth); // 获取图片的宽度
var h = img[k].height * (w / img[k].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[k], 0, 0, w, h);
// Get data URL encoding of image
var uri = canvas.toDataURL("image/jpeg");
$(img[k]).attr("src", img[k].src);
img[k].width = w;
img[k].height = h;
// Save encoded image to array
images[k] = {
type: uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")),
encoding: uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")),
location: $(img[k]).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 = style;
// Aggregate parts of the file together
var bodyAttr = (function getBodyAttr () {
var bodyAttr = '';
var body = document.querySelector('body');
bodyAttr += 'class = "' + body.className + '"';
bodyAttr += ' id = "' + body.id + '"';
bodyAttr += ' style = "' + body.getAttribute('style') + '"';
return bodyAttr;
})();
var fileContent = comptent.mhtml.top.replace("_html_", comptent.mhtml.head.replace("_styles_", styles) + comptent.mhtml.body.replace("_body_", markup.html())) + mhtmlBottom;
// Create a Blob with the file contents
fileContent = fileContent.replace('<body>', '<body ' + bodyAttr + ' >');
console.log(fileContent);
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)");
}
}
}, window.jQuery || $, window.saveAs));