如何使用PHPOffice将Word文档转换为PDF

3
我不知道如何将我从数据库中获取的字符串(blob)格式的Word文档,通过PHPOffice库转换成PDF。以下是实现步骤:
1. 从数据库中获取现有的Word文档字符串。 2. 将该字符串通过PHPOffice库的构造函数或其他函数进行处理。 3. 使用另一个函数获取PDF字符串。 4. 最后使用Content-Type: application/pdf输出字符串给用户。
我已经实现了第1和第4步,但不知道如何完成第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";
}

一些代码可能会帮助我们更快地解决您的问题 :) - King Reload
@KingReload,谢谢您的评论。我已经上传了我现有实现的一些代码。 - Julian Schmuckli
感谢你的代码 :) 非常感激 - King Reload
2个回答

4

在尝试了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 Repository 网站下载文件,并将其加载到一个文件夹中即可。当然,最终它可能不是最好的解决方案,但对我来说,它只是Word文档的预览。因此,该脚本也受到以下两个链接的启发:

0

你可以输出到一个字符串

 ob_start();
 $xmlWriter->save('php://output');
 return ob_get_clean();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接