使用 PHPWord 库将 Word 文件转换为 PDF

问题描述 投票:0回答:1

我尝试将 Word 文档转换为 PDF,但格式丢失且与原始文档不匹配。具体来说,我将证书从 Word 文件转换为 PDF,导致格式不正确。尽管寻找解决方案,但我找不到解决方案,而且我对 PHPWord 等 PHP 库不是很熟悉。任何帮助将不胜感激。我也包含了我的代码

<?php
require_once 'vendor/autoload.php'; // Include PHPWord autoload.php

use PhpOffice\PhpWord\TemplateProcessor;
use PhpOffice\PhpWord\Settings;
use PhpOffice\PhpWord\IOFactory;

// Specify the PDF rendering library and its path
\PhpOffice\PhpWord\Settings::setPdfRenderer(\PhpOffice\PhpWord\Settings::PDF_RENDERER_DOMPDF, 'vendor/dompdf/dompdf');

// Load the template document
$templateFile = 'docs/certification-of-appreciation.docx'; // Path to your Word template
$templateProcessor = new TemplateProcessor($templateFile);

// Replace placeholders with dynamic content
$templateProcessor->setValue('USERNAME', $_SESSION['worker_name']); // Replace 'USERNAME' with your placeholder for the user's name
// You might need to replace 'SUPERVISOR_SIGNATURE' with the appropriate placeholder for the supervisor's signature

// Save the processed document
$processedFilePath = 'docs/certification-of-appreciation_processed.docx'; // Path to save the processed Word document
$templateProcessor->saveAs($processedFilePath);

// Load the processed document
$processedPhpWord = IOFactory::load($processedFilePath);

// Convert Word to PDF
$pdfWriter = IOFactory::createWriter($processedPhpWord, 'PDF');
$pdfFilePath = 'docs/Certificate.pdf'; // Path to save the PDF file
$pdfWriter->save($pdfFilePath);

// Send the PDF to the browser
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="Certificate.pdf"');
readfile($pdfFilePath);

// Clean up: delete temporary files if needed
unlink($processedFilePath);
unlink($pdfFilePath);

?>

我想要一个输出,它可以成功地将我的 word 文件转换为 pdf 而不会丢失它的格式

php phpword
1个回答
0
投票

确保您已通过 Composer 安装 Dompdf 库(composer 需要 dompdf/dompdf)。此外,请确保 Word 模板和输出文件的路径正确,并且 Word 模板中存在必要的占位符。

此外,请确保您拥有在指定目录中写入和删除文件的必要权限。如果您遇到任何错误,请告诉我,我会进一步帮助您

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.