将pdf保存到本地服务器


Save pdf to local server

我正在从原始二进制数据创建一个PDF文件,它运行得很好,但由于我在PHP文件中定义了头,它会提示用户"保存"文件或"使用打开"。有什么方法可以把文件保存在本地服务器http://localhost/pdf的某个地方吗?

以下是我在页面中定义的标题

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: application/pdf");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Transfer-Encoding: binary");

如果您想将文件保存在服务器上,而不是让访问者下载,则不需要标头。页眉是用来告诉客户端你要发送什么的,在这种情况下什么都不是(尽管你可能会显示一个链接到你新创建的PDF或其他东西的页面)。

因此,只需使用file_put_contents等函数在本地存储文件,最终让您的web服务器处理文件传输和HTTP标头。

// Let's say you have a function `generate_pdf()` which creates the PDF,
// and a variable $pdf_data where the file contents are stored upon creation
$pdf_data = generate_pdf();
// And a path where the file will be created
$path = '/path/to/your/www/root/public_html/newly_created_file.pdf';
// Then just save it like this
file_put_contents( $path, $pdf_data );
// Proceed in whatever way suitable, giving the user feedback if needed 
// Eg. providing a download link to http://localhost/newly_created_file.pdf

您可以使用输出控制函数。将ob_start()放在脚本的开头。最后使用ob_get_contents()并将内容保存到本地文件中。

之后,您可以使用ob_end_clean()或ob_end_flush(),这取决于您是想将PDF输出到浏览器,还是将用户重定向到其他页面。如果使用ob_end_flush(),请确保在刷新数据之前设置了标头。

相关文章: