如何使用PHPOffice从Word转换PDF

问题描述 投票:2回答:2

我没有任何计划如何将Word文档(我的数据库中的字符串(blob))通过PHPOffice库转换为PDF格式。

概念:

  1. 我从数据库中获取现有word文档作为字符串
  2. 将字符串传递给构造函数或PHPOffice库的函数。
  3. 然后通过另一个函数获取PDF作为字符串
  4. 最后用Content-Type: application/pdf将字符串输出给用户。

NR。 1和4我已经实施了。但我不知道如何完成nr。 2和3.有人可以帮助我吗?

码:

//DB-Connection, Composer autoload, ...

$id = htmlspecialchars(trim($_REQUEST["id"]));

$get_data = $con->query("SELECT * FROM word_documents WHERE id='$id'"); //Get the blob 
$data = $get_data->fetch();
if ($get_data->rowCount() == 1) {
    header("Content-Type: application/pdf");
    header("Content-Disposition: inline; filename=" . $data["name"]);

    //TODO: Print the PDF as an string

} else {
    echo "File not found";
}
php pdf ms-word phpoffice
2个回答
1
投票

在我尝试了PhpOffice库中的一些函数后,我终于找到了解决方案。

因此,对于自己的库,您无法将其直接从字符串加载并保存到字符串。您必须当前创建文件。

//Set header to show as PDF
header("Content-Type: application/pdf");
header("Content-Disposition: inline; filename=" . $data["name"]);

//Create a temporary file for Word
$temp = tmpfile();
fwrite($temp, $data["data"]); //Write the data in the file
$uri = stream_get_meta_data($temp)["uri"]; //Get the location of the temp file

//Convert the docx file in to an PhpWord Object
$doc = PhpOffice\PhpWord\IOFactory::load($uri);

//Set the PDF Engine Renderer Path. Many engines are supported (TCPDF, DOMPDF, ...).
\PhpOffice\PhpWord\Settings::setPdfRendererPath("path/to/tcpdf");
\PhpOffice\PhpWord\Settings::setPdfRendererName('TCPDF');

//Create a writer, which converts the PhpWord Object into an PDF
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($doc, 'PDF');

//Create again an temp file for the new generated PDF.
$pdf_temp = tmpfile();
$pdf_uri = stream_get_meta_data($pdf_temp)["uri"];

//Save the PDF to the path
$xmlWriter->save($pdf_uri);

//Now print the file from the temp path.
echo file_get_contents($pdf_uri);

我选择TCPDF引擎,因为它非常容易安装。只需从Git Repositorywebsite下载文件并将其加载到文件夹即可。

当然,最后它可能不是最好的解决方案,但对我来说,它只是一个word文档的预览。

所以这个脚本也受到以下两个链接的启发:


0
投票

您可以输出到字符串

 ob_start();
 $xmlWriter->save('php://output');
 return ob_get_clean();
© www.soinside.com 2019 - 2024. All rights reserved.