准备工作
//必要的js文件
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="FileSaver.js"></script>
<script type="text/javascript" src="jquery.wordexport.js"></script>
这个链接是几个JS
源文件的压缩包需要的小伙伴自行下载
提取码是 Mont
百度网盘 请输入提取码
//pdf
handleExportPDF(){
var self=this;
var exportMain = $("#exportPDF").clone();
exportMain.find("input").each(function() {
if ($(this).attr("type") != "hidden") {
if ($(this).attr("type") == "radio") {
if ($(this).is(":checked")) {
$(this).after("√");
}
} else {
var html = $(this).val();
$(this).after("<lable>" + html + "</lable>");
}
}
$(this).remove();
});
exportMain.find("button").each(function() {
$(this).remove();
});
exportMain.find(".el-input").each(function(i,item) {
var html = item.innerText;
$(this).after("<lable>" + html + "</lable>");
$(this).remove();
});
exportMain.find(".beizhu").each(function() {
$(this).remove();
});
exportMain.find("textarea").each(function() {
if ($(this).attr("type") != "hidden") {
var html = $(this).val();
$(this).after("<lable>" + html + "</lable>");
}
$(this).remove();
});
exportMain.wordExport(self.rptName.replace(/<[^>]+>/g,""));
},
wordexport.js 都需要将html中的图片转为base64形式
而且,图片的宽度高,最好自己设置下,否则下载的图片会以图片原始大小下载,就会出现图片在文档超出情况
处理图片的方法就在此不做多解释了,大家自行搜索一下吧!
但是我将表格导出到word里却发现样式没有导出,暂且把Style样式写在了标签里。
<table class="layui-table" style="color: red;background-color: black;">
//图片格式转换为base64
function convertImagesToBase64 (content) {
var regularImages = content.querySelectorAll("img");
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
[].forEach.call(regularImages, function (imgElement) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = imgElement.width;
canvas.height = imgElement.height;
ctx.drawImage(imgElement, 0, 0);
var dataURL = canvas.toDataURL();
imgElement.setAttribute('src', dataURL);
})
canvas.remove();
}
var content = document.getElementById('#content');
convertImagesToBase64(content);//转换图片为base64
content = '<!DOCTYPE html><html><head><meta charset="UTF-8"></head>'+ content +'</html>'