vue3 使用 docx-preview 预览 Word文档
引入第三方库
npm i docx-preview
vue3创建组件
<template>
<div>
<!-- 用于渲染文档的容器 -->
<div ref="previewContainer" class="preview-wrapper"></div>
</div>
</template>
<script setup>
import {defineProps,onMounted} from "vue"
import { renderAsync } from 'docx-preview';
const props = defineProps({
url:{
type:String,
}
})
const previewContainer = ref()
const previewDoc = async () => {
try {
// 假设这里是从后端获取.docx文件的Blob数据
// 你的实际获取文件数据的逻辑可能是一个API调用,如使用 axios
const response = await fetch(props.url);
const blob = await response.blob();
// 获取DOM容器
const container = previewContainer.value;
// 调用 renderAsync 方法渲染文档
await renderAsync(blob, container, null, {
className: 'docx', // 默认和文档样式类的类名/前缀
inWrapper: true, // 启用围绕文档内容渲染包装器
ignoreWidth: false,
ignoreHeight: false,
ignoreFonts: false, // 禁用字体渲染
breakPages: true, // 在分页符上启用分页
});
console.log('文档渲染完成!');
} catch (error) {
console.error('预览失败:', error);
}
}
onMounted(()=>{
previewDoc()
})
</script>
<style lang="scss" scoped>
.preview-wrapper{
width: 100%;
height: 100%;
}
</style>
浙公网安备 33010602011771号