php 实现pdf 转换word
使用 PHP 进行 PDF 转 Word 的方法
PHP 可以通过调用外部库或 API 实现 PDF 转 Word 的功能。以下是几种常见的方法:
调用外部工具(如 LibreOffice)
LibreOffice 可以通过命令行将 PDF 转换为 Word 文档,PHP 可以调用系统命令执行此操作。
$pdfFile = '/path/to/input.pdf';
$outputDir = '/path/to/output';
$command = "libreoffice --headless --convert-to docx --outdir {$outputDir} {$pdfFile}";
exec($command, $output, $returnCode);
if ($returnCode === 0) {
echo "PDF 转换为 Word 成功!";
} else {
echo "转换失败,错误代码:{$returnCode}";
}
确保服务器已安装 LibreOffice,并正确配置路径。
使用 PHP 库(如 Spatie\PdfToText)
虽然 Spatie\PdfToText 主要用于提取 PDF 文本,但可以结合其他工具生成 Word 文档。

use Spatie\PdfToText\Pdf;
$text = Pdf::getText('/path/to/input.pdf');
file_put_contents('/path/to/output.docx', $text);
注意:此方法仅提取文本,不保留格式。
调用第三方 API(如 CloudConvert)
CloudConvert 提供 PDF 转 Word 的 API 服务,PHP 可通过 HTTP 请求调用。

$apiKey = 'YOUR_API_KEY';
$pdfFile = '/path/to/input.pdf';
$apiUrl = 'https://api.cloudconvert.com/v2/convert';
$data = [
'tasks' => [
'import' => [
'operation' => 'import/upload',
'file' => base64_encode(file_get_contents($pdfFile))
],
'convert' => [
'operation' => 'convert',
'input' => 'import',
'output_format' => 'docx'
],
'export' => [
'operation' => 'export/url',
'input' => 'convert'
]
]
];
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
if (isset($result['data']['tasks'][0]['result']['files'][0]['url'])) {
$downloadUrl = $result['data']['tasks'][0]['result']['files'][0]['url'];
file_put_contents('/path/to/output.docx', file_get_contents($downloadUrl));
echo "转换成功!";
} else {
echo "转换失败:" . $response;
}
需要注册 CloudConvert 并获取 API Key。
使用 PHPWord 生成 Word 文档
如果只需将 PDF 文本内容写入 Word 文档,可以使用 PHPWord 库。
require_once 'vendor/autoload.php';
use PhpOffice\PhpWord\PhpWord;
$pdfText = file_get_contents('/path/to/input.pdf');
$phpWord = new PhpWord();
$section = $phpWord->addSection();
$section->addText($pdfText);
$writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$writer->save('/path/to/output.docx');
需要先安装 PHPWord 库:
composer require phpoffice/phpword
注意事项
- 直接转换可能无法完美保留 PDF 的复杂格式(如图片、表格)。
- 调用外部工具或 API 需确保服务器权限和网络连接正常。
- 第三方 API 可能有调用限制或收费。






