将pdf保存到本地服务器

问题描述:

我从原始二进制数据创建一个PDF文件,它的工作完美,但由于我在PHP文件中定义的标题,它会提示用户“保存”文件或“打开” 。有没有什么办法可以将文件保存在本地服务器http://localhost/pdf将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 
+0

where function generate_pdf()? – 2015-06-05 04:14:04

+0

@skjulikaka:由于问题不是关于使用PHP创建PDF数据,而是关于如何保存超出范围的数据。我的代码示例中的第一行还明确指出“***让我们说**你有一个'generate_pdf()'函数来创建PDF *”。但我相信你可以通过[搜索]找到合适的答案(http://*.com/search?q=generate+%5Bpdf%5D+using+%5Bphp%5D)“使用[标签:pdf]生成[标签:pdf]标签:PHP]“或沿着这些线。 – Simon 2015-06-05 07:20:10

+0

是的,我遇到了很多''生成php内容到pdf'库,但它仍然不能接受,因为我的语言是不理解与pdf :(,,我现在疯狂(); – 2015-06-05 09:35:28

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

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

+0

如果你已经在内存中的PDF数据,wouldn输出缓冲有点像打印一个文件只是为了再次扫描它?即使你想让它保存到磁盘,同时让用户下载它,难道你不能保存它,2。发送标题,3.打印PDF数据? – Simon 2012-02-15 15:33:24

+0

这取决于你使用哪个库来创建PDF文件,有些库只能直接输出到浏览器,所以你不能“保存”。 – 2012-02-17 19:42:24

+0

啊,我明白了。 这就说得通了。 – Simon 2012-02-18 10:42:02