jquery实现HTML页面导入word文档

FileSaver.js

/*
* FileSaver.js
* A saveAs() FileSaver implementation.
*
* By Eli Grey, http://eligrey.com
*
* License : https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md (MIT)
* source  : http://purl.eligrey.com/github/FileSaver.js
*/// The one and only way of getting global scope in all environments
// https://stackoverflow.com/q/3277182/1008999
var _global = typeof window === 'object' && window.window === window? window : typeof self === 'object' && self.self === self? self : typeof global === 'object' && global.global === global? global: thisfunction bom (blob, opts) {if (typeof opts === 'undefined') opts = { autoBom: false }else if (typeof opts !== 'object') {console.warn('Deprecated: Expected third argument to be a object')opts = { autoBom: !opts }}// 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 (opts.autoBom && /^\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
}function download (url, name, opts) {var xhr = new XMLHttpRequest()xhr.open('GET', url)xhr.responseType = 'blob'xhr.onload = function () {saveAs(xhr.response, name, opts)}xhr.onerror = function () {console.error('could not download file')}xhr.send()
}function corsEnabled (url) {var xhr = new XMLHttpRequest()// use sync to avoid popup blockerxhr.open('HEAD', url, false)try {xhr.send()} catch (e) {}return xhr.status >= 200 && xhr.status <= 299
}// `a.click()` doesn't work for all browsers (#465)
function click (node) {try {node.dispatchEvent(new MouseEvent('click'))} catch (e) {var evt = document.createEvent('MouseEvents')evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80,20, false, false, false, false, 0, null)node.dispatchEvent(evt)}
}// Detect WebView inside a native macOS app by ruling out all browsers
// We just need to check for 'Safari' because all other browsers (besides Firefox) include that too
// https://www.whatismybrowser.com/guides/the-latest-user-agent/macos
var isMacOSWebView = _global.navigator && /Macintosh/.test(navigator.userAgent) && /AppleWebKit/.test(navigator.userAgent) && !/Safari/.test(navigator.userAgent)var saveAs = _global.saveAs || (// probably in some web worker(typeof window !== 'object' || window !== _global)? function saveAs () { /* noop */ }// Use download attribute first if possible (#193 Lumia mobile) unless this is a macOS WebView: ('download' in HTMLAnchorElement.prototype && !isMacOSWebView)? function saveAs (blob, name, opts) {var URL = _global.URL || _global.webkitURLvar a = document.createElement('a')name = name || blob.name || 'download'a.download = namea.rel = 'noopener' // tabnabbing// TODO: detect chrome extensions & packaged apps// a.target = '_blank'if (typeof blob === 'string') {// Support regular linksa.href = blobif (a.origin !== location.origin) {corsEnabled(a.href)? download(blob, name, opts): click(a, a.target = '_blank')} else {click(a)}} else {// Support blobsa.href = URL.createObjectURL(blob)setTimeout(function () { URL.revokeObjectURL(a.href) }, 4E4) // 40ssetTimeout(function () { click(a) }, 0)}}// Use msSaveOrOpenBlob as a second approach: 'msSaveOrOpenBlob' in navigator? function saveAs (blob, name, opts) {name = name || blob.name || 'download'if (typeof blob === 'string') {if (corsEnabled(blob)) {download(blob, name, opts)} else {var a = document.createElement('a')a.href = bloba.target = '_blank'setTimeout(function () { click(a) })}} else {navigator.msSaveOrOpenBlob(bom(blob, opts), name)}}// Fallback to using FileReader and a popup: function saveAs (blob, name, opts, popup) {// Open a popup immediately do go around popup blocker// Mostly only available on user interaction and the fileReader is async so...popup = popup || open('', '_blank')if (popup) {popup.document.title =popup.document.body.innerText = 'downloading...'}if (typeof blob === 'string') return download(blob, name, opts)var force = blob.type === 'application/octet-stream'var isSafari = /constructor/i.test(_global.HTMLElement) || _global.safarivar isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent)if ((isChromeIOS || (force && isSafari) || isMacOSWebView) && typeof FileReader !== 'undefined') {// Safari doesn't allow downloading of blob URLsvar reader = new FileReader()reader.onloadend = function () {var url = reader.resulturl = isChromeIOS ? url : url.replace(/^data:[^;]*;/, 'data:attachment/file;')if (popup) popup.location.href = urlelse location = urlpopup = null // reverse-tabnabbing #460}reader.readAsDataURL(blob)} else {var URL = _global.URL || _global.webkitURLvar url = URL.createObjectURL(blob)if (popup) popup.location = urlelse location.href = urlpopup = null // reverse-tabnabbing #460setTimeout(function () { URL.revokeObjectURL(url) }, 4E4) // 40s}}
)_global.saveAs = saveAs.saveAs = saveAsif (typeof module !== 'undefined') {module.exports = saveAs;
}

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<!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>'// }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 xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40">\n_html_</html>',head:'<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<style>\n_styles_\n</style>\n<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val="Cambria Math"/><m:brkBin m:val="before"/><m:brkBinSub m:val="--"/><m:smallFrac m:val="off"/><m:dispDef/><m:lMargin m:val="0"/> <m:rMargin m:val="0"/><m:defJc m:val="centerGroup"/><m:wrapIndent m:val="1440"/><m:intLim m:val="subSup"/><m:naryLim m:val="undOvr"/></m:mathPr></w:WordDocument></xml><![endif]--></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)// var w = '200'// var h = '100'// 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')$(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'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'})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)')}
}

Demo.html

<!DOCTYPE html>
<html><head><meta charset="utf-8" /><title>打印demo</title>
</head><body><div id="page" style="font-family: Microsoft YaHei;">导出的内容<p class="title" style="color: red;font-size: 18px;">修改基本的导出样式</p><span style="color: deeppink;font-size: 38px;font-family: Microsoft YaHei;">你好你好你好你好你好</span><img src="images/avatar.png"><table border="1"><tr><td>姓名</td><td>年龄</td><td>性别</td></tr><tr><td>孙艺珍</td><td>孙艺珍</td><td>孙艺珍</td></tr><tr><td>孙艺珍</td><td>孙艺珍</td><td>孙艺珍</td></tr><tr><td>孙艺珍</td><td>孙艺珍</td><td>孙艺珍</td></tr></table><!-- <img src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3363295869,2467511306&fm=26&gp=0.jpg"> --></div><a class="page-btn" href="javascript:void(0)"> 导出 </a>
</body></html>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script src="FileSaver.js"></script>
<script src="jquery.wordexport.js"></script>
<script type="text/javascript">jQuery(document).ready(function ($) {$("a.page-btn").click(function (event) {$("#page").wordExport('aaa');});});
</script>



代码贴上就能用,自己把图片地址换下即可。我试了网图好像不行,有行的可以教教我。感谢!

jquery实现HTML页面导入word文档相关推荐

  1. html保存导入word文档格式,WordPress网站在导入Word文档时如何保持原有格式

    WordPress程序后台有文章发布功能,可以添加文字和图片.如果想将自己在排版好的Word 文档导入到WordPress ,作为文章发布,却不是一件容易的事情,如果我们直接复制,Word 文档本身的 ...

  2. 怎么把cad文件导入word文档?

    方法:我们把CAD图纸以图片的形式插 入Word.方法如下: 1.我们运行CAD编辑器专 业版,点 击菜单栏"文件-打开"选项,或是按快捷键"Ctrl+O",打 ...

  3. 前端页面嵌入word文档_word文档怎样加页面

    word文档怎么加页 一.添加页在WORD中,使用键盘组合键:Ctrl + 回车键可以添加页. 方法2:单击页面布局---->分隔符---->分页符,如图所示. word文档怎么在两页之中 ...

  4. vue页面导出Word文档(含图片)

    引用插件 安装 npm i docxtemplater@3.17.6 npm i pizzip npm i jszip-utils@0.1.0 npm i jszip@2.6.1 npm i file ...

  5. html word页面展示,word文档怎样调页面

    word文档如何调整页面?在页面设置对话框的"页边距2003版"选项卡中选择"方向"为横向或是纵向. Word中怎么设置一个页面显示4页 Word一页只显示四页 ...

  6. h5页面打开word文档ios_H5页面生成word文件及发送邮件

    最近工作中有用到生成word文档及发送该附件的邮件.先说说我的思路和流程吧; 1.在后台用PHP将数据组合拼接成HTML格式: 2.生成带数据(HTML)的word文档(生成到项目对应的目录下): 3 ...

  7. 前端页面嵌入word文档_Java 处理word文档后在前端展示

    这个是个比较传统的解决思路,搜一搜其实发现很多人都这么干,这批人难道也是对上述方法(jsp直接显示)失望了后找的这种模式?呵呵 比较常用的开源免费的有且只有几种,选择其中几种我尝试了一下. 首先想到的 ...

  8. 数据库数据导入word文档

    第一步:打开word,设计表格,另存为另一种格式的word也就是.xml的格式 第二步:把文档需要更改的数据替换成${字段名} 并且把修改后的文档修改后缀名.ftl,放入到eclipse的根目录下建一 ...

  9. Altium designer原理图导入word文档模糊——终极解决办法

    硬件相关专业的小伙伴在写毕业论文的时候可能会遇到AD原理图导入word后变模糊的情况,经过多方摸索,终于找到一个可行的方法. (1)前情回顾 网上常用的AD原理图导入word方法总结如下: 1. 直接 ...

最新文章

  1. OCS 企业版图解详细部署
  2. 软件工程团队项目Alpha版本产品介绍
  3. 能力=知识+技能+经验
  4. 想买基金,在哪个银行开户好呢?
  5. 关于springboot集成redis及关于redis的Key 乱码问题
  6. JavaWeb如何学?
  7. 【渝粤教育】国家开放大学2018年春季 0234-22T公务员制度讲座 参考试题
  8. louvain算法python_【转载】LOUVAIN算法
  9. 5 个关键点!优化你的 UI 原型设计
  10. MATLAB Smoothing Spline 拟合
  11. 《声声慢·寻寻觅觅》 李清照
  12. SpringBoot核心注解
  13. 【剑指offer-54】20190907/03 字符流中第一个不重复的字符
  14. 【Linux】Shell 特殊符号总结 数组
  15. 怎么用IDEA上传本地项目到码云/Github?
  16. 虚拟内存架设服务器客户端,怎么在服务器上开虚拟内存
  17. 如何压缩照片到30kb以下?三个方法
  18. Python 实现 JSON 解析器
  19. TKO 6-4 DP入门之最少拦截系统
  20. 找到不偏科的学生(提取学生的所有课程都大于各个课程平均分的学生)

热门文章

  1. TransModeler典型项目应用介绍
  2. 与某易易盾的加固历程
  3. 提供可制定化的路由加载方式,Vue 如何做到?| 小智内部团队分享
  4. 毕业设计 基于STM32单片机的水箱水位控制系统
  5. IMT-2020(5G)推进组发布5G技术研发试验第二阶段技术规范
  6. oracle员工表和部门表基本操作
  7. DNFSF怎么选服务器? 选什么样的服务器?
  8. Linux (Ubuntu)磁盘管理与文件压缩解压(入门必看)
  9. 【ASP.net文档】用C#实现HTTP协议下的多线程文件传输
  10. 孩子幽门螺旋菌感染如何治疗?怎么办?别慌