# 文档转换服务使用指南 ## 概述 DocumentConversionService 负责将上传的 Word 文档(.doc/.docx)转换为 Markdown 格式。转换过程是异步的,通过队列系统处理。 ## 功能特性 1. **自动转换**: 文档上传后自动触发转换 2. **异步处理**: 使用队列系统,不阻塞用户操作 3. **错误处理**: 转换失败时记录错误,但不影响文档的基本功能 4. **重试机制**: 转换失败后自动重试(默认 3 次) 5. **预览生成**: 自动生成 Markdown 内容的预览(前 500 字符) ## 使用方法 ### 1. 队列转换(推荐) ```php use App\Services\DocumentConversionService; use App\Models\Document; $document = Document::find($id); $conversionService = app(DocumentConversionService::class); // 将转换任务加入队列 $conversionService->queueConversion($document); ``` ### 2. 同步转换(不推荐用于生产环境) ```php use App\Services\DocumentConversionService; use App\Models\Document; $document = Document::find($id); $conversionService = app(DocumentConversionService::class); try { // 转换文档 $markdown = $conversionService->convertToMarkdown($document); // 保存 Markdown 文件 $markdownPath = $conversionService->saveMarkdownToFile($document, $markdown); // 更新文档信息 $conversionService->updateDocumentMarkdown($document, $markdownPath); } catch (\Exception $e) { // 处理转换失败 $conversionService->handleConversionFailure($document, $e); } ``` ## 转换状态 文档的 `conversion_status` 字段有以下几种状态: - `pending`: 等待转换 - `processing`: 正在转换 - `completed`: 转换完成 - `failed`: 转换失败 ## 配置 转换相关的配置在 `config/documents.php` 文件中: ```php 'conversion' => [ 'driver' => 'pandoc', // 转换驱动 'pandoc_path' => '/usr/local/bin/pandoc', // Pandoc 路径 'timeout' => 300, // 超时时间(秒) 'queue' => 'documents', // 队列名称 'retry_times' => 3, // 重试次数 'retry_delay' => 60, // 重试延迟(秒) ], ``` ## 队列工作进程 确保队列工作进程正在运行: ```bash # 启动队列工作进程 php artisan queue:work --queue=documents # 或者使用 Supervisor 管理队列进程 ``` ## 依赖要求 ### Pandoc 系统需要安装 Pandoc 才能进行文档转换: **macOS:** ```bash brew install pandoc ``` **Ubuntu/Debian:** ```bash sudo apt-get install pandoc ``` **验证安装:** ```bash pandoc --version ``` ## 错误处理 转换失败时,系统会: 1. 记录详细的错误日志 2. 更新文档的 `conversion_status` 为 `failed` 3. 在 `conversion_error` 字段中保存错误信息 4. 保留原始 Word 文档,用户仍可下载 ## 监控和调试 ### 查看转换日志 ```bash tail -f storage/logs/laravel.log | grep "文档转换" ``` ### 查看队列任务 ```bash php artisan queue:failed ``` ### 重试失败的任务 ```bash # 重试所有失败的任务 php artisan queue:retry all # 重试特定任务 php artisan queue:retry {job-id} ``` ## 性能优化 1. **使用 Redis 队列**: 比数据库队列更快 2. **增加队列工作进程**: 并行处理多个转换任务 3. **调整超时时间**: 根据文档大小调整 `timeout` 配置 4. **监控队列长度**: 避免队列积压 ## 故障排查 ### 转换一直处于 processing 状态 - 检查队列工作进程是否运行 - 检查 Pandoc 是否正确安装 - 查看错误日志 ### 转换失败 - 检查 Pandoc 路径配置是否正确 - 检查文档文件是否存在 - 检查文档文件是否损坏 - 查看 `conversion_error` 字段的错误信息 ### 队列任务不执行 - 确认队列连接配置正确(Redis/Database) - 确认队列工作进程正在运行 - 检查队列名称是否匹配