h5实现word预览
使用WebOffice API实现Word预览
WebOffice API是一种常见的在线文档预览方案,支持Word、Excel、PPT等格式。需要注册开发者账号获取API密钥。
// 引入WebOffice SDK
<script src="https://web-office.oss-cn-shanghai.aliyuncs.com/weboffice.min.js"></script>
// 初始化配置
const config = {
token: 'YOUR_API_TOKEN',
url: 'https://your-word-file.docx',
type: 'docx'
};
// 创建预览容器
WebOffice.initialize(document.getElementById('container'), config);
使用Microsoft Office Online嵌入
通过Microsoft官方提供的嵌入代码实现Word预览,无需开发API,但需要文档可公开访问。
<iframe
src="https://view.officeapps.live.com/op/embed.aspx?src=YOUR_WORD_URL"
width="100%"
height="600px">
</iframe>
使用PDF.js间接预览
先将Word转换为PDF,再通过PDF.js库实现预览。需要后端转换支持。
// 使用pdf.js加载转换后的PDF
pdfjsLib.getDocument('converted.pdf').promise.then(function(pdf) {
pdf.getPage(1).then(function(page) {
const viewport = page.getViewport({ scale: 1.0 });
const canvas = document.getElementById('pdf-canvas');
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
page.render({
canvasContext: context,
viewport: viewport
});
});
});
使用Mammoth.js纯前端解析
适用于简单的docx文件解析,转换为HTML显示。不支持复杂格式。
mammoth.extractRawText({arrayBuffer: fileArrayBuffer})
.then(function(result) {
document.getElementById('output').innerHTML = result.value;
})
.catch(function(error) {
console.error(error);
});
使用Docx.js库渲染
专门处理docx文件的JavaScript库,能保留部分格式。
const docx = require("docx");
const { Document, Packer, Paragraph, TextRun } = docx;
const doc = new Document({
sections: [{
properties: {},
children: [
new Paragraph({
children: [
new TextRun("Hello World"),
new TextRun({
text: "Foo Bar",
bold: true,
}),
],
}),
],
}],
});
Packer.toBlob(doc).then(blob => {
const url = URL.createObjectURL(blob);
window.open(url);
});
使用后端转换方案
通过后端服务将Word转换为HTML或PDF再返回前端显示。Python示例:
# Python后端使用python-docx转换
from docx import Document
from flask import Flask, send_file
app = Flask(__name__)
@app.route('/preview')
def convert_to_html():
doc = Document('input.docx')
html = ''
for para in doc.paragraphs:
html += f'<p>{para.text}</p>'
return html
浏览器兼容性注意事项
现代浏览器支持上述大部分方案,但需注意:
- IE浏览器需要polyfill支持
- 移动端需测试触控交互
- 大文件需要分片加载处理
- 敏感内容建议使用后端转换避免直接暴露文件URL
安全防护措施
实现预览功能时应当:
- 对用户上传文件进行病毒扫描
- 限制文件大小防止DoS攻击
- 使用临时链接防止盗链
- 对敏感文档添加水印预览



