import { convertToHtml } from 'mammoth';
|
import Vue from 'vue'
|
|
export default {
|
async convertFileToHtml(url) {
|
var xhr = new XMLHttpRequest();
|
xhr.open('GET', Vue.prototype.javaApi+url, true);//获取文件流的接口
|
xhr.send();
|
xhr.responseType = "blob";//不能漏
|
let xhrPromise = new Promise((resolve, reject) => {
|
xhr.onload = async function () {
|
if (this.status === 200) {
|
// 返回的文件流,转换成blob对象
|
var blob = new Blob([this.response],{ type:'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
|
// 使用mammoth将Word转换为HTML
|
let reader = new FileReader();
|
reader.readAsArrayBuffer(blob);
|
let htmlContentPromise = new Promise((resolve, reject) => {
|
reader.onload = async function () {
|
var arrayBuffer = xhr.response; //arrayBuffer
|
const result = await convertToHtml({ arrayBuffer: arrayBuffer })
|
let html = result.value.replace(//g, '')
|
.replace('<h1>', '<h1 style="text-align: center;">')
|
.replace(/<table>/g, '<table style="border-collapse: collapse;border: 1px solid #000;">')
|
.replace(/<tr>/g, '<tr style="height: 30px;">')
|
.replace(/<td>/g, '<td style="border: 1px solid #000;">')
|
.replace(/<p>/g, '<p style="text-indent: 2em;">')
|
.replace(/<a [^>]*>/g, "")
|
.replace(/<\/a>/g, "")
|
// .replace(/em/g, "cm");
|
resolve(html)
|
};
|
})
|
resolve(await htmlContentPromise)
|
}
|
|
}
|
})
|
return await xhrPromise
|
},
|
downloadIamge(imgsrc, name) {//下载图片地址和图片名
|
var image = new Image();
|
// 解决跨域 Canvas 污染问题
|
image.setAttribute("crossOrigin", "anonymous");
|
image.onload = function() {
|
var canvas = document.createElement("canvas");
|
canvas.width = image.width;
|
canvas.height = image.height;
|
var context = canvas.getContext("2d");
|
context.drawImage(image, 0, 0, image.width, image.height);
|
var url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
|
|
var a = document.createElement("a"); // 生成一个a元素
|
var event = new MouseEvent("click"); // 创建一个单击事件
|
a.download = name || "photo"; // 设置图片名称
|
a.href = url; // 将生成的URL设置为a.href属性
|
a.dispatchEvent(event); // 触发a的单击事件
|
};
|
image.src = imgsrc;
|
}
|
};
|
|
|
export function transformExcel(response,tempName){
|
const relType = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel;charset=UTF-8']
|
let type = response.type
|
if (relType.includes(type)) {
|
const blob = new Blob([response], {type: 'application/vnd.ms-excel'})
|
let temp = tempName
|
if(response.headers){
|
const disposition = response.headers["content-disposition"]
|
temp = disposition.substring(disposition.lastIndexOf('=') + 1)
|
}
|
let filename = decodeURI(temp)
|
// 创建一个超链接,将文件流赋进去,然后实现这个超链接的单击事件
|
const elink = document.createElement('a')
|
elink.download = filename
|
elink.style.display = 'none'
|
elink.href = URL.createObjectURL(blob)
|
document.body.appendChild(elink)
|
elink.click()
|
URL.revokeObjectURL(elink.href) // 释放URL 对象
|
document.body.removeChild(elink)
|
}
|
}
|