php实现word在线预览
使用Office Online或Google Docs嵌入预览
将Word文档上传至公共可访问的存储空间(如OneDrive或Google Drive),生成共享链接后嵌入iframe。Office Online需使用https://view.officeapps.live.com/op/embed.aspx?src=前缀,Google Docs使用https://docs.google.com/viewer?embedded=true&url=前缀。
$fileUrl = urlencode('https://yourdomain.com/path/to/document.docx');
$officeUrl = "https://view.officeapps.live.com/op/embed.aspx?src={$fileUrl}";
echo "<iframe src='{$officeUrl}' width='100%' height='600px'></iframe>";
转换为PDF后预览
通过LibreOffice或第三方API将Word转换为PDF,使用PDF.js库实现预览。需服务器安装LibreOffice:

sudo apt install libreoffice
PHP调用转换命令:
$docPath = '/path/to/document.docx';
$pdfPath = '/path/to/output.pdf';
exec("libreoffice --headless --convert-to pdf {$docPath} --outdir " . dirname($pdfPath));
前端使用PDF.js加载:

<iframe src="/web/viewer.html?file=/output.pdf" style="width:100%;height:600px;"></iframe>
使用第三方API服务
调用GroupDocs、Aspose等专业文档处理API,需注册获取API密钥:
$apiUrl = "https://api.groupdocs.com/v2.0/viewer/request?fileUrl=YOUR_FILE_URL";
$headers = ['Authorization: Bearer YOUR_API_KEY'];
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
浏览器直接打开策略
对于现代浏览器(Chrome/Firefox/Edge),可直接输出文件流并设置Content-Disposition: inline:
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: inline; filename="document.docx"');
readfile('/path/to/document.docx');
注意事项
- 隐私文件需设置访问权限控制
- 大文件处理建议使用队列异步转换
- 移动端适配需调整iframe视口设置
- 商业方案需考虑API调用成本
每种方案各有利弊,可根据项目需求选择最适合的技术路径。Office Online方案适合快速实现,而PDF转换方案更适合需要自定义样式的场景。






