1.npm安装
npm install --save html-docx-js
npm install --save file-saver
2.引入
import htmlDocx from 'html-docx-js/dist/html-docx';
import saveAs from 'file-saver';
3.导出
import htmlDocx from 'html-docx-js/dist/html-docx';
import saveAs from 'file-saver';
import axios from 'axios'
export const downloadWord = {
data() {
return {
}
},
methods: {
//type有pdf和docx类型
async downloadWord(id, result, type) {
//自定义
const cssStyle = `
<style>
body{
font-size: 16px;
}
.red{
color: blue;
}
.divCenter{
text-align: center;
font-size: 25px;
font-weight: bold;
}
.mb20{
margin-bottom: 20px;
}
</style>`
const loading = this.$loading({
lock: true,
customClass: "create-isLoading",
text: "正在下载,请稍后...",
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0)"
});
let content = `
<div class="divCenter" >${result.title}</div>
<div class="mb20">${result.htmlContent.replace(/ /g, ' ')}</div>
</div>`
const articleContent =
`<!DOCTYPE html><html><head><meta charset="UTF-8">${cssStyle}</head><body>${content}</body></html>`
const blob = htmlDocx.asBlob(articleContent);
const file = await new File([blob], result.title + "." + type, {
lastModified: Date.now()
});
let fileName = result.title + "." + type;
let formData = new FormData()
formData.append('file', file)
formData.append('id', id)
formData.append('convertType', type)
const config = {
headers: {
"Content-Type": "multipart/form-data;"
},
responseType: "blob"
};
const res = await axios.post(this.$prefix + "/api/v2/file/convert", formData, config)
if (res.status === 200) {
const blob = new Blob([res.data], { type: "octet-stream" });
saveAs(blob, fileName);
}
loading.close();
},
},
}