富文本内容导出为 word
- 安装依赖
npm install file-saver --save
npm install html-docx-js --save
- 引入依赖
import htmlDocx from 'html-docx-js/dist/html-docx';
//引入
import {saveAs} from 'file-saver';
- 情况一,内容不带图片直接导出
handleSaveToWord() {
// this.content 富文本内容
// this.tempFileName 导出的文件名
var converted = htmlDocx.asBlob(this.content);
saveAs(converted, this.tempFileName);
},
情况二,内容带图片,需要将图片转换为base64格式才可以导出
formToWord() {
if (!this.value.trim()) {
this.$message.error('内容不能为空')
return
}
this.convertImagesToBase64()
var contentDocument = this.$refs.weditor.editor.$textElem.elems[0];
var content = '<!DOCTYPE html>' + contentDocument.outerHTML;
let converted = htmlDocx.asBlob(content)
saveAs(converted, this.tempFileName);
},
convertImagesToBase64() {
//获取富文本框中的所有图片
let contentDocument = this.$refs.weditor.editor.$textElem.elems[0];
var regularImages = contentDocument.querySelectorAll("img");
for (var i = 0; i < regularImages.length; i++) {
var imgURL = regularImages[i].currentSrc;
this.getBase64(imgURL, regularImages[i]);
}
},
getBase64(url, charImg) {
var Img = new Image();
Img.crossOrigin = "Anonymous";//跨域必须使用,且后台也得设置允许跨域
let dataURL = '';
Img.src = url;
Img.onload = () => { //要先确保图片完整获取到,这是个异步事件
var canvas = document.createElement("canvas"), //创建canvas元素
width = Img.width, //确保canvas的尺寸和图片一样
height = Img.height;
canvas.width = width;
canvas.height = height;
canvas.getContext("2d").drawImage(Img, 0, 0, width, height); //将图片绘制到canvas中
dataURL = canvas.toDataURL('image/jpg'); //转换图片为dataURL
this.condataurl(dataURL, charImg) //调用回调函数
};
},
condataurl(dataURL, charImg) {
charImg.src = dataURL;
//console.log(charImg);
},
富文本导出PDF
- 安装依赖
npm install vue-html2pdf --save
- 引入依赖
import VueHtml2pdf from "vue-html2pdf";
- 使用组件
<vue-html2pdf
:show-layout="false"
:float-layout="true"
:enable-download="true"
:preview-modal="false"
:paginate-elements-by-height="1400"
:filename="tempFileName"
:pdf-quality="2"
:manual-pagination="false"
pdf-format="a3"
pdf-orientation="landscape"
pdf-content-width="98%"
ref="html2Pdf"
>
<section slot="pdf-content">
<!-- PDF 内容 -->
<span id="report" v-html="value"></span>
</section>
</vue-html2pdf>
// 调用方法
formToPDF() {
if (!this.value.trim()) {
this.$message.error('内容不能为空')
}
this.$refs.html2Pdf.generatePdf();
}