我没有任何计划如何将Word文档(我的数据库中的字符串(blob))通过PHPOffice库转换为PDF格式。
概念
Content-Type: application/pdf
的字符串输出给用户。NR。 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";
}
答案 0 :(得分:2)
在我尝试了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或website下载文件,然后将其加载到文件夹即可。
当然,最后它可能不是最好的解决方案,但对我来说,它只是一个word文档的预览。
所以这个脚本也受到以下两个链接的启发:
答案 1 :(得分:0)
您可以输出到字符串
ob_start();
$xmlWriter->save('php://output');
return ob_get_clean();