场景描述:
在一个即将迎来美好周末的Friday,领导找到我,问我是不是做过html导出word文档的功能,我很诚恳地说做过图片。
项目需求:
项目当中某一个详情页,页面中包含基本内容以及图片,且图片是外部链接。点击导出按钮,实现导出页面内容至word文档实现直接下载。
实现思路:
Q1:我们可以使用什么实现word导出?
A1:Blob对象和FilerSaver
解析:Blob 对象表示一个不可变、原始数据的类文件对象。Blob对象可以看作是存放二进制数据的容器,此外还可以通过blob设置二进制数据的MIME类型。
//创建blob:
//dataArr:数组,包含了要添加到blob对象中的数据,数据可以是任意多个ArrayBuffer,ArrayBufferView,blob或者DOMString对象
//opt:对象,用于设置Blob对象的属性(如MIME类型)
var blob = new Blob(dataArr:Array<any>,opt:{type:string});
//示例如下:
let fileContent= '<div>hello world!</div>';
let blob = new Blob([fileContent], {type: "application/msword;charset=utf-8"});
FileSaver 在没有原生支持 saveAs() 的浏览器上实现了 saveAs()。它是在客户端保存文件的解决方案,非常适合需要生成文件,或者保存不应该发送到外部服务器的敏感信息的 web App。
// 导入saveAs 方法
// 1)先获取需导出内容
// 2)使用Blob() 将内容编译一下
// 3)定义文件名,saveAs()导出文件
import {saveAs} from 'file-saver';
let fileContent= '<div>hello world!</div>';
let blob = new Blob([fileContent], {type: "application/msword;charset=utf-8"});
saveAs(blob, '导出文档.doc') //至此文件已成功下载
现在是不是已经了解了Blob和fileSaver的基本使用?接下来上样例!
一、安装file-saver
npm install @types/file-saver --save
npm install file-saver --save
二、html处理
// 简单写写,假设需要导出以下内容
<div #gridsterEl>
<div class="export-html">
<p>你猜导出到word里面我长什么样子?<p>
<img width="200" height="300" src="https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3011722798,2565193467&fm=15&gp=0.jpg">
<p>我管你长什么样子<p>
<img src="https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1984448902,388620416&fm=15&gp=0.jpg">
</div>
</div>
<button nz-button [nzType]="'primary'" (click)='exportWord()'>导出报告</button>
三、ts处理
// 1.首先引入saveAs方法
import {saveAs} from 'file-saver';
// 2.获取要导出的dom元素区块
@ViewChild('gridsterEl', { static: true })
gridsterEl: ElementRef;
public dropContainer:any;
ngAfterViewInit() {
this.dropContainer = $(this.gridsterEl.nativeElement);
}
//处理dom元素
//这里有两种情况:
//1.导出的页面比较简单,不需要后端介入
//2.导出页面图片比较多,可以让后端处理
//此处以情况2后端j介入为例:后端需要将前端发送的html中的img筛选出来。以数组形式返回,返回样例如下:
// {
// state:"ok",
// html:'<div>这是第一个图<img src="0" />这是第二个图<img src="1" /></div>xxxxxxxxxxxxxxx',
// pics:[{
// index:0,
// src:"data:image/png;base64,iVBORw0KGgoAxxxxxxxxxxxxxxx"
// },{
// index:1,
// src:"data:image/png;base64,iVssssBORw0KGgoAxxxxxxxxxxxxxxx"
// }]
// }
// 获取需要导出的具体HTML内容
getPreViewHtml(){
let htmlSrc = '';
this.dropContainer.find('.export-html').each((index, _elem) => {
htmlSrc += $(_elem).prop('outerHTML');
});
return htmlSrc;
}
}
//点击导出按钮,实现word导出下载
exportWord(){
let htmlInfo = this.getPreViewHtml();
const info = {
html:htmlInfo
}
this.xxxService.xxx(info).subscribe(val){
if(val.state==='ok'){
const _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>"
}
};
const dealhtml = v.html;
const img = v.pics;
let mhtmlBottom = "\n";
for (let i = 0; i < img.length; i++) {
const uri = img[i].src;
const index = img[i].index;
mhtmlBottom += "--NEXT.ITEM-BOUNDARY\n";
mhtmlBottom += "Content-Location: " + index + "\n";
mhtmlBottom += "Content-Type: " + uri.substring(uri.indexOf(":") + 1, uri.indexOf(";")) + "\n";
mhtmlBottom += "Content-Transfer-Encoding: " + uri.substring(uri.indexOf(";") + 1, uri.indexOf(",")) + "\n\n";
mhtmlBottom += uri.substring(uri.indexOf(",") + 1) + "\n\n";
}
mhtmlBottom += "--NEXT.ITEM-BOUNDARY--";
// 如果导出的文档需要生成目录,则使用h标签即可,如果有table也可以设置style
const styles = `
h1{font-family: FangSong_GB2312}
h2{font-family: FangSong_GB2312;font-size:24px;}
h3{font-family: FangSong_GB2312;font-size:22px;}
h4{font-family: FangSong_GB2312;font-size:20px;}
h5{font-family: FangSong_GB2312}
table {border-collapse:collapse;border: 1px solid #000}
th{ border: 1px solid #000;font-family: KaiTi_GB2312;padding:5px}
td{ border: 1px solid #000;font-family: KaiTi_GB2312;padding:5px;min-width:120px}
`;
// 整合html代码片段
const fileContent = _static.mhtml.top.replace("_html_", _static.mhtml.head.replace("_styles_", styles) + _static.mhtml.body.replace("_body_", dealhtml)) + mhtmlBottom;
// 导出
const blob = new Blob([fileContent], {type: "application/msword;charset=utf-8"});
saveAs(blob, `文档的名称啊.doc`) //至此文档已成功下载
}
}
}
四、导出效果:
五、那些天,我们一起踩过的坑:
一、导出的文件中,图片不能正常展示。
图片的处理逻辑是按照上述的写法,那就保证代码没有问题,那是哪里出了问题呢?百思不得其解。在经过一天半的呕心沥血的bug排查的艰难过程后,终于找到了原因,因为项目使用了哈希路由(#),去掉就OK了图片,我也有点方。(因为在设置word的头信息时包含了content-base 和 content-location,如果包含#,那#后面的地址不被解析。这是一点浅显的猜测,不保证准确)
二、word里如果需要展示图片,需要将其转成base64。
前端在进行外部链接转base64的时候,如果外部服务器未设置允许跨域,那么前端是转不了的。该转换工作可以交由后端同学处理。
the end~✿✿ヽ(°▽°)ノ✿