从word文档粘贴公式、图片到富文本
监听粘贴事件,获取剪贴板的数据
onPaste() {
this.$refs.richTextBox.addEventListener('paste', (e) => {
const clipdata = e.clipboardData || window.clipboardData;
const rtf = clipdata.getData('text/rtf')
this.replaceImagesFileSourceWithInlineRepresentation(this.extractImageDataFromRtf(rtf))
});
},
extractImageDataFromRtf(rtfData) {
if (!rtfData) {
return [];
}
const regexPictureHeader = /{\\pict[\s\S]+?({\\\*\\blipuid\s?[\da-fA-F]+)[\s}]*/
const regexPicture = new RegExp('(?:(' + regexPictureHeader.source + '))([\\da-fA-F\\s]+)\\}', 'g');
const images = rtfData.match(regexPicture);
const result = [];
if (images) {
for (const image of images) {
let imageType = false;
if (image.includes('\\pngblip')) {
imageType = 'image/png';
} else if (image.includes('\\jpegblip')) {
imageType = 'image/jpeg';
}
if (imageType) {
result.push({
hex: image.replace(regexPictureHeader, '').replace(/[^\da-fA-F]/g, ''),
type: imageType
});
}
}
}
return result;
},
replaceImagesFileSourceWithInlineRepresentation( imagesHexSources) {
console.log('imagesHexSources', imagesHexSources)
this.pasteSrcList = []
imagesHexSources.forEach(item => {
const newSrc = `data:${item?.type || 'image/png'};base64,${this.convertHexToBase64(item.hex)}`;
this.pasteSrcList.push(newSrc)
})
},
convertHexToBase64(hexString) {
return btoa(hexString.match(/\w{2}/g).map(char => {
return String.fromCharCode(parseInt(char, 16));
}).join(''));
},
initSummernote(height) {
const _this = this
let toolBar = [
['style', ['bold', 'italic', 'underline', 'clear']],
['fontsize', ['fontsize']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['height', ['height']],
['table', ['table']],
['view', ['fullscreen', 'codeview']],
['insert', ['picture', 'link']]
]
if (this.isHidePic) {
toolBar = [
['style', ['bold', 'italic', 'underline', 'clear']],
['fontsize', ['fontsize']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']]
]
}
this.ele.summernote({
lang: 'zh-CN',
placeholder: '请输入内容',
height,
toolbar: toolBar,
callbacks: {
onImageUpload: (files) => {
_this.uploadImage(files[0])
},
onChange: (e) => {
const imgSrcList = this.getRichTextImgList(e)
if (imgSrcList.length > 0) {
var content = this.getRichTextContent()
imgSrcList.forEach((item, index) => {
content = content.replace(item, this.pasteSrcList[index]);
})
this.ele.summernote('code', content);
}
}
}
})
},
getRichTextImgList(str = '') => {
const srcArr = str.split('src=') || []
const imgSrcList = srcArr.filter(f => !f.includes('https://zg-new-order-model') && f.includes('file:') && (f.includes('.png') || f.includes('.jpg') || f.includes('.jpeg') || f.includes('.gif') || f.includes('.bmp'))) || []
imgSrcList.forEach((item, index, arrar) => {
const i = item.indexOf('>')
const i2 = item.indexOf(' ')
if (i !== -1) {
arrar[index] = item.slice(0, i)
}
if (i2 !== -1) {
arrar[index] = item.slice(0, i2)
}
})
const result = imgSrcList.map(m => {
const list = m.split('=').filter(f => f.includes('file:')) || []
return list[0]
})
return result || []
}