首先需要两个js文件,jquery.wordexport.js 和 FileSaver.js,源码放在下面

// jquery.wordexport.jsif (typeof jQuery !== 'undefined' && typeof saveAs !== 'undefined') {// eslint-disable-next-line no-extra-semi;(function($) {$.fn.wordExport = function(fileName) {fileName =typeof fileName !== 'undefined'? fileName: 'jQuery-Word-Export'var statics = {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 = $(this).clone()// Remove hidden elements from the outputmarkup.each(function() {var self = $(this)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 = wcanvas.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/jpg')$(img[i]).attr('src', img[i].src)img[i].width = wimg[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'// eslint-disable-next-line no-redeclarefor (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=' /* Font Definitions */@font-face{font-family:宋体;panose-1:2 1 6 0 3 1 1 1 1 1;mso-font-alt:SimSun;mso-font-charset:134;mso-generic-font-family:auto;mso-font-pitch:variable;mso-font-signature:3 680460288 22 0 262145 0;}  @font-face{font-family:"Cambria Math";panose-1:2 4 5 3 5 4 6 3 2 4;mso-font-charset:1;mso-generic-font-family:roman;mso-font-format:other;mso-font-pitch:variable;mso-font-signature:0 0 0 0 0 0;}  @font-face{font-family:"\@宋体";panose-1:2 1 6 0 3 1 1 1 1 1;mso-font-charset:134;mso-generic-font-family:auto;mso-font-pitch:variable;mso-font-signature:3 680460288 22 0 262145 0;}/* Style Definitions */p.MsoNormal, li.MsoNormal, div.MsoNormal{mso-style-unhide:no;mso-style-qformat:yes;mso-style-parent:"";margin:0cm;margin-bottom:.0001pt;mso-pagination:widow-orphan;font-size:14.0pt;font-family:宋体;mso-bidi-font-family:宋体;}p.MsoHeader, li.MsoHeader, div.MsoHeader{mso-style-noshow:yes;mso-style-priority:99;mso-style-link:"页眉 Char";margin:0cm;margin-bottom:.0001pt;text-align:center;mso-pagination:widow-orphan;layout-grid-mode:char;font-size:9.0pt;font-family:宋体;mso-bidi-font-family:宋体;}p.MsoFooter, li.MsoFooter, div.MsoFooter{mso-style-noshow:yes;mso-style-priority:99;mso-style-link:"页脚 Char";margin:0cm;margin-bottom:.0001pt;mso-pagination:widow-orphan;layout-grid-mode:char;font-size:9.0pt;font-family:宋体;mso-bidi-font-family:宋体;}p.MsoAcetate, li.MsoAcetate, div.MsoAcetate{mso-style-noshow:yes;mso-style-priority:99;mso-style-link:"批注框文本 Char";margin:0cm;margin-bottom:.0001pt;mso-pagination:widow-orphan;font-size:9.0pt;font-family:宋体;mso-bidi-font-family:宋体;}span.Char{mso-style-name:"页眉 Char";mso-style-noshow:yes;mso-style-priority:99;mso-style-unhide:no;mso-style-locked:yes;mso-style-link:页眉;font-family:宋体;mso-ascii-font-family:宋体;mso-fareast-font-family:宋体;mso-hansi-font-family:宋体;}span.Char0{mso-style-name:"页脚 Char";mso-style-noshow:yes;mso-style-priority:99;mso-style-unhide:no;mso-style-locked:yes;mso-style-link:页脚;font-family:宋体;mso-ascii-font-family:宋体;mso-fareast-font-family:宋体;mso-hansi-font-family:宋体;}span.Char1{mso-style-name:"批注框文本 Char";mso-style-noshow:yes;mso-style-priority:99;mso-style-unhide:no;mso-style-locked:yes;mso-style-link:批注框文本;font-family:宋体;mso-ascii-font-family:宋体;mso-fareast-font-family:宋体;mso-hansi-font-family:宋体;}p.msochpdefault, li.msochpdefault, div.msochpdefault{mso-style-name:msochpdefault;mso-style-unhide:no;mso-margin-top-alt:auto;margin-right:0cm;mso-margin-bottom-alt:auto;margin-left:0cm;mso-pagination:widow-orphan;font-size:10.0pt;font-family:宋体;mso-bidi-font-family:宋体;}span.msonormal0{mso-style-name:msonormal;mso-style-unhide:no;}.MsoChpDefault{mso-style-type:export-only;mso-default-props:yes;font-size:10.0pt;mso-ansi-font-size:10.0pt;mso-bidi-font-size:10.0pt;mso-ascii-font-family:"Times New Roman";mso-hansi-font-family:"Times New Roman";mso-font-kerning:0pt;}/* Page Definitions */  @page WordSection1{size:595.3pt 841.9pt;margin:72.0pt 90.0pt 72.0pt 90.0pt;mso-header-margin:42.55pt;mso-footer-margin:49.6pt;mso-paper-source:0;}div.WordSection1{page:WordSection1;}';var styles = ''// Aggregate parts of the file togethervar fileContent =statics.mhtml.top.replace('_html_',statics.mhtml.head.replace('_styles_', styles) +statics.mhtml.body.replace('_body_', markup.html())) + mhtmlBottom// Create a Blob with the file contentsvar blob = new Blob([fileContent], {type: 'application/msword;charset=utf-8',})// eslint-disable-next-line no-undefsaveAs(blob, fileName + '.doc')}// eslint-disable-next-line no-undef})(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.jsvar saveAs =saveAs ||(function(view) {'use strict'// IE <10 is explicitly unsupportedif (typeof view === 'undefined' ||(typeof navigator !== 'undefined' &&/MSIE [1-9]\./.test(navigator.userAgent))) {return}var doc = view.document,// only get URL when necessary in case Blob.js hasn't overridden it yetget_URL = function() {return view.URL || view.webkitURL || view},save_link = doc.createElementNS('http://www.w3.org/1999/xhtml','a'),can_use_save_link = 'download' in save_link,click = function(node) {var event = new MouseEvent('click')node.dispatchEvent(event)},is_safari = /constructor/i.test(view.HTMLElement),is_chrome_ios = /CriOS\/[\d]+/.test(navigator.userAgent),throw_outside = function(ex) {// eslint-disable-next-line no-extra-semi;(view.setImmediate || view.setTimeout)(function() {throw ex}, 0)},force_saveable_type = 'application/octet-stream',// the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe toarbitrary_revoke_timeout = 1000 * 40, // in msrevoke = function(file) {var revoker = function() {if (typeof file === 'string') {// file is an object URLget_URL().revokeObjectURL(file)} else {// file is a Filefile.remove()}}setTimeout(revoker, arbitrary_revoke_timeout)},dispatch = function(filesaver, event_types, event) {event_types = [].concat(event_types)var i = event_types.lengthwhile (i--) {var listener = filesaver['on' + event_types[i]]if (typeof listener === 'function') {try {listener.call(filesaver, event || filesaver)} catch (ex) {throw_outside(ex)}}}},auto_bom = function(blob) {// prepend BOM for UTF-8 XML and text/* types (including HTML)// note: your browser will automatically convert UTF-16 U+FEFF to EF BB BFif (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {return new Blob([String.fromCharCode(0xfeff), blob], {type: blob.type,})}return blob},FileSaver = function(blob, name, no_auto_bom) {if (!no_auto_bom) {blob = auto_bom(blob)}// First try a.download, then web filesystem, then object URLsvar filesaver = this,type = blob.type,force = type === force_saveable_type,object_url,dispatch_all = function() {dispatch(filesaver,'writestart progress write writeend'.split(' '))},// on any filesys errors revert to saving with object URLsfs_error = function() {if ((is_chrome_ios || (force && is_safari)) &&view.FileReader) {// Safari doesn't allow downloading of blob urlsvar reader = new FileReader()reader.onloadend = function() {var url = is_chrome_ios? reader.result: reader.result.replace(/^data:[^;]*;/,'data:attachment/file;')var popup = view.open(url, '_blank')if (!popup) view.location.href = urlurl = undefined // release reference before dispatchingfilesaver.readyState = filesaver.DONEdispatch_all()}reader.readAsDataURL(blob)filesaver.readyState = filesaver.INITreturn}// don't create more object URLs than neededif (!object_url) {object_url = get_URL().createObjectURL(blob)}if (force) {view.location.href = object_url} else {var opened = view.open(object_url, '_blank')if (!opened) {// Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.htmlview.location.href = object_url}}filesaver.readyState = filesaver.DONEdispatch_all()revoke(object_url)}filesaver.readyState = filesaver.INITif (can_use_save_link) {object_url = get_URL().createObjectURL(blob)setTimeout(function() {save_link.href = object_urlsave_link.download = nameclick(save_link)dispatch_all()revoke(object_url)filesaver.readyState = filesaver.DONE})return}fs_error()},FS_proto = FileSaver.prototype,saveAs = function(blob, name, no_auto_bom) {return new FileSaver(blob,name || blob.name || 'download',no_auto_bom)}// IE 10+ (native saveAs)if (typeof navigator !== 'undefined' && navigator.msSaveOrOpenBlob) {return function(blob, name, no_auto_bom) {name = name || blob.name || 'download'if (!no_auto_bom) {blob = auto_bom(blob)}return navigator.msSaveOrOpenBlob(blob, name)}}FS_proto.abort = function() {}FS_proto.readyState = FS_proto.INIT = 0FS_proto.WRITING = 1FS_proto.DONE = 2FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = nullreturn saveAs})((typeof self !== 'undefined' && self) ||(typeof window !== 'undefined' && window) ||this.content)
// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the windowif (typeof module !== 'undefined' && module.exports) {module.exports.saveAs = saveAs
} else if (typeof define !== 'undefined' &&// eslint-disable-next-line no-undefdefine !== null &&// eslint-disable-next-line no-undefdefine.amd !== null
) {// eslint-disable-next-line no-undefdefine([], function() {return saveAs})
}

安装file-saver

npm install file-saver --save

// 页面完整代码<template><div id="pcContract"><div @click="download()">合同</div><img src="../../assets/logo.png" alt="" /></div>
</template>
<script>
// eslint-disable-next-line no-unused-vars
import saveAs from 'file-saver'
import '../../utils/jquery.wordexport'
export default {data() {return {}},created: function() {},methods: {download() {// eslint-disable-next-line no-undef$('#pcContract').wordExport('文档')},},
}
</script>
<style lang="scss" scoped></style>

这样就能把vue页面下载成word文档啦

实现vue页面下载成word文档相关推荐

  1. 只涉及前端,将html页面导出成word文档

    用docxtemplater插件,前端实现html导出word文档(可导出文字.表格.图片) 下面我用的是vue框架,用其他框架同理,只要这个插件能兼容就行 官方文档https://docxtempl ...

  2. 「Vue To Words」 - 教你在Vue项目中导出Word文档(包含表格合并,图片修改大小)

    前言:最近在项目中遇到了,vue页面需要导出word文档,今日就进行记录一下,如有不对的地方,还请见谅 ^^ 简单说一下需求:需要导出的页面是表格页面,因为包含表格的嵌套和合并,其实最主要的就是导出页 ...

  3. Vue+ElementUi 项目中 将页面内容转为 Word文档下载

    Vue+ElementUi 项目中 将页面内容转为 Word文档下载 需要提前做好的现成模板(魔板个页面基本上相同的内容)-模板内有变量,替换成页面对应的数据 HTML页面: 转换的word 以下是正 ...

  4. 使用PHPWord把html转成word文档并支持下载

    在开发项目中,遇到的需求:把后台录入的数据保存成word文档,以便其他人员使用.于是在调研的时候,从git上找了PHPWord. PHPWord官方文档 PHPWord git地址 一.安装PHPWo ...

  5. html格式图片可以转换成word文档,html网页转换成word文档,转换成功,并且可以保存图片,但是总是为web版式的格式,怎么改成“页面”格式,多谢...

    当前位置:我的异常网» C# » html网页转换成word文档,转换成功,并且可以保存图 html网页转换成word文档,转换成功,并且可以保存图片,但是总是为"web版式"的格 ...

  6. 为什么html转为word之后图片,html网页转换成word文档,转换成功,并且可以保存图片,但是总是为web版式的格式,怎么改成“页面”格式,多谢...

    html网页转换成word文档,转换成功,并且可以保存图片,但是总是为"web版式"的格式,怎么改成"页面"格式,多谢 html网页转换成word文档,转换成功 ...

  7. php将html转成word文档下载

    <?php class word{ function start(){ ob_start(); echo ''; } function save($path) { echo "&quo ...

  8. 前端报表导出成word文档(含echarts图表)

    前端报表导出成word文档(含echarts图表) 一.问题背景: 前端vue做的各种维度的报表,原来是通过前端整体截屏导出成PDF,但部分报表在遇到跨页时会被截断,客户体验极差.然后又考虑客户可能需 ...

  9. 扫描PDF转换成word文档如何操作

    扫描PDF文件转换成word文档如何进行操作呢?作为一般的PDF文件介于它的文件大小都不够大,普通的转换功能都能进行操作,文件过大的话就需要用到扫描PDF转word这种操作,那么关于它的操作是怎样的呢 ...

最新文章

  1. php调用另一个页面内容,php怎么实现调用另一个页面
  2. OD基本快捷键及功能
  3. 日常英语---一、纸质版还是电子版
  4. QT的QUdpSocket类的使用
  5. 模型ks_风控建模 模型指标篇
  6. Kubernetes集群安全:Api Server认证
  7. rdd与mysql表 join_Spark 之RDD
  8. AspnetCore 缓存篇
  9. pcs7组态虚拟机中的服务器,PCS7冗余服务器配置
  10. 浅谈Java中的单例模式及四种懒汉模式
  11. 阿里DATAV的使用方法(大屏生成工具)
  12. 文献学习(part102-A)--Autoencoders
  13. mac 更新系统后 idea 意外退出
  14. Android百度地图(地位和POI附近搜索)-仿微信、QQ地理位置的分享
  15. PHP:执行 PHP 文件
  16. Google Chrome浏览器字体模糊,字体锯齿 的解决方法
  17. 10年后重温《我奋斗了18年才和你坐在一起喝咖啡》
  18. 非隔离开关电源相关知识理解汇总
  19. 1-计算机系统概述(CO)
  20. 妙赞大讲糖:糖尿病患者的手术风险有多大

热门文章

  1. 使用百度天气API制作天气组件
  2. 交叉销售功能介绍-功能
  3. java输出和读取CSV格式文件
  4. 国内首家中高端自由职业者共享平台——易分之一,即将上线运营
  5. Linux面试最高频的5个基本问题
  6. C++ 使用海康威视SDK将视频推流到rtmp服务器
  7. 【JavaWeb】Servlet系列——响应HTML代码、Servlet连接数据库、IDEA开发Servlet程序、Servlet对象的生命周期、GenericServelet适配器模式
  8. 爱因斯坦思考题(多维穷举)
  9. cad lisp 二次抛物线_用Cad画二次抛物线
  10. Face Super-Resolution Guided by 3D Facial Priors(ECCV2020)论文解读