700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 前端将html导出为word文档(原生js篇)

前端将html导出为word文档(原生js篇)

时间:2023-03-11 21:57:53

相关推荐

前端将html导出为word文档(原生js篇)

主要是参考了插件:jquery.wondexport.js👈

下载的文档包含图片,文档类型可为doc、wps

结果预览

💡原理

将 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 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="/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 itvar markup = $(contentNode).clone();// Remove hidden elements from the outputmarkup.each(function() {var self = $(contentNode);if (self.is(':hidden'))self.remove();});// Embed all images using Data URLsvar images = Array();var img = markup.find('img');for (var i = 0; i < img.length; i++) {// Calculate dimensions of output imagevar w = Math.min(img[i].width, options.maxWidth);var h = img[i].height * (w / img[i].width);// Create canvas for converting image to data URLvar canvas = document.createElement("CANVAS");canvas.width = w;canvas.height = h;// Draw image to canvasvar context = canvas.getContext('2d');context.drawImage(img[i], 0, 0, w, h);// Get data URL encoding of imagevar uri = canvas.toDataURL("image/png");$(img[i]).attr("src", img[i].src);img[i].width = w;img[i].height = h;// Save encoded image to arrayimages[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 datavar 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 stylesheetvar styles = "";// Aggregate parts of the file togethervar 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 contentsvar blob = new Blob([fileContent], {type: "application/msword;charset=utf-8"});return fileContent};})/* wps:kswpsdocx: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文档啦😁

❤️ 更多前端知识欢迎关注公众号交流

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。