if (file_exists("folder/$unique_id.pdf")) {
header('Content-type: application/pdf');
ob_clean(); // Added after reading similar question's answer
flush(); // Added after reading similar question's answer
readfile("folder/$unique_id.pdf");
} else {
$html = "PLACING_MY_HTML_CODE_HERE";
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->set_paper("A4");
$dompdf->render();
$output = $dompdf->output();
file_put_contents("folder/$unique_id.pdf", $output);
header('Content-type: application/pdf');
ob_clean(); // Added after reading similar question's answer
flush(); // Added after reading similar question's answer
readfile("folder/$unique_id.pdf");
}
如果PDF文件不存在,則使用DOMPDF生成PDF文件。生成的文件沒有任何錯誤,並存儲在文件夾內。但有時,而不是讀取生成的文件,它下載一個文件沒有擴展名,主要是名稱「下載」。我試圖打開在文本編輯器中的文件,我看到的符號與某些標題如application
,content-type
等使用PHP讀取生成的PDF文件有時會下載
後來,搜查SO看到this question,並在我的代碼添加ob_clean
,flush
。但問題仍然存在。
注意:我檢查了使用Adobe閱讀器和谷歌瀏覽器打開存儲在文件夾中的PDF文件。這些文件已完全呈現並正確保存。
編輯:
相反readfile
我試過header
直接重定向到文件中。這沒有問題。
有什麼建議嗎?
嘗試移動'header('Content-type:application/pdf');'在PDF生成之前 –
關於它在下載之前花費多少時間來生成PDF? –
您確定此代碼是否工作,因爲在if條件的第一行中使用的函數應該是** file_exists ** – Vagabond