php实现word转pdf
使用 PHPWord 和 TCPDF 库
安装 PHPWord 和 TCPDF 库。可以通过 Composer 进行安装:
composer require phpoffice/phpword
composer require tecnickcom/tcpdf
创建 PHP 脚本读取 Word 文档并转换为 PDF:

require_once 'vendor/autoload.php';
$phpWord = \PhpOffice\PhpWord\IOFactory::load('input.docx');
$pdfWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'PDF');
$pdfWriter->save('output.pdf');
使用 LibreOffice 命令行工具
确保服务器安装了 LibreOffice,通过命令行调用转换:

$command = 'libreoffice --headless --convert-to pdf --outdir /path/to/output /path/to/input.docx';
exec($command);
使用 Google Docs API
注册 Google Cloud 项目并启用 Docs API。使用以下代码通过 API 转换:
$client = new Google_Client();
$client->setAuthConfig('credentials.json');
$client->addScope(Google_Service_Drive::DRIVE);
$service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile();
$file->setName('output.pdf');
$result = $service->files->export(
'word-file-id',
'application/pdf',
array('alt' => 'media')
);
file_put_contents('output.pdf', $result->getBody());
使用第三方 API 服务
调用如 CloudConvert 或 Zamzar 的 API:
$apiKey = 'your-api-key';
$url = 'https://api.cloudconvert.com/v2/convert';
$data = [
'input_format' => 'docx',
'output_format' => 'pdf',
'file' => base64_encode(file_get_contents('input.docx'))
];
$options = [
'http' => [
'header' => "Content-type: application/json\r\nAuthorization: Bearer $apiKey",
'method' => 'POST',
'content' => json_encode($data),
],
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
file_put_contents('output.pdf', base64_decode(json_decode($result)->data->file));
注意事项
确保服务器有足够的权限读写文件。对于大型文档,可能需要增加 PHP 的内存限制和执行时间。LibreOffice 方法需要服务器支持图形界面或无头模式。API 方法需要有效的网络连接和 API 密钥。






