纯前端将html导出为word文档
主要是参考了插件:jquery.wondexport.js 👈
💡 原理
将 html 内容转为 mhtml 数据,再通过 Blob 转成文件下载。详细步骤如下:
- 将要导出的dom节点clone(),防止对节点做操作(如通过改样式使导出的文档标题居中、删除不需要的节点)影响了html页面上展示的内容。
- 图片处理:
-
- 找到所有的图片进行遍历
- 将图片转为canvas
- 通过canvas.toDataURL( ) 得到base64
- 根据 mhtml 模板,替换已处理好的数据。
- 通过 Blob 转成文件下载
📄 完整demo
<!DOCTYPE html>
<html>
<head>
<title>搞笑哲理故事</title>
</head>
<style>
.down_load {
width: 90px;
height: 36px;
background-color: red;
text-align: center;
line-height: 36px;
color: white;
position: fixed;
right: 50px;
top: 100px;
z-index: 1999;
}
</style>
<body>
<div class="header">
<div class="down_load">下载</div>
</div>
<div class="main">
<div class="article">
<h1 class="title">搞笑哲理故事</h1>
<div class="content">
<h2> 搞笑哲理故事</h2>
<p>
一只火鸡和一头牛闲聊,火鸡说:我盼望能飞到树顶,可我没有勇气。
</p>
<p style="text-align: center">
<img src="./img/2_qq_41248310.jpg" />
</p>
<p> 牛说:为什么不吃一点我的牛粪呢,他们很有养分。</p>
<p>
火鸡吃了一点牛粪,发明它确切给了它足够的力气飞到第一根树枝,
</p>
<p> 第二天,火鸡又吃了更多的牛粪,飞到第二根树枝,</p>
<p> 两个星期后,火鸡自豪的飞到了树顶,</p>
<p> 但不久,一个农民看到了它,敏捷的把它从树上射了下来。</p>
<p> 生存之道:牛屎运让你到达顶峰,但不能让你留在那里。</p>
</div>
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.js"></script>
<script type="text/javascript">
$(function () {
$(".down_load").click(function () {
saveData();
});
function saveData(params) {
var fileName = $(".title").text();
var titleNode = $(".title").clone();
$(titleNode).attr("style", "text-align:center"); //让标题居中
var contentNode = $(".article").clone();
data = wordExport(contentNode);
downLoad(data, fileName);
}
function wordExport(contentNode) {
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<!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 = $(contentNode).clone();
// Remove hidden elements from the output
markup.each(function () {
var self = $(contentNode);
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",
});
return fileContent;
}
});
/*
wps:kswps
docx:msword
*/
function downLoad(data, fileName) {
let blob = new Blob([data], { type: "application/msword" });
let url = URL.createObjectURL(blob);
let link = document.createElement("a");
link.setAttribute("href", url);
link.setAttribute("download", `${fileName}.doc`);
link.style.visibility = "hidden";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
</script>
</body>
</html>
学会这个技能就可以轻松把文章下载成word文档啦😁