正在从url检索输出.如何使用php强制从url下载PDF


Retrieving output from a url. How do I force the dowload of a PDF from a url using php

我需要从jasperserver报告引擎中以PDF格式检索我们的报告,然后我希望PDF被强制下载,而不是显示在浏览器中。在浏览器中显示的问题是,我们不希望在url中向最终用户显示报告参数。

如果我在浏览器中输入这个URL路径,我会得到一个PDF文档,它显示在同一个浏览器窗口中,包含所有报告数据:

https://mysite.com:8443/jasperserver/flow.html?_flowId=viewReportFlow&reportUnit=sample_report&output=pdf;

我更希望使用下载对话框,让用户将PDF下载到他们的计算机上,而不是显示在浏览器中。

我已经尝试了以下php代码,但无法使其工作。我得到一个返回值false,但服务器日志中没有显示错误。

ob_start();
    header("Location: $src"); /* Redirect browser */
    $report_contents = ob_get_contents();
    ob_end_clean();
    var_dump($report_contents);

我真的不知道该怎么办。。。有人有什么想法吗?

谢谢你的帮助。

您可以将文件缓冲到PHP服务器,然后通过强制下载输出:

header('Content-disposition: attachment; filename=huge_document.pdf');
header('Content-type: application/pdf');
readfile('https://mysite.com:8443/jasperserver/flow.html?_flowId=viewReportFlow&reportUnit=sample_report&output=pdf;');

请参阅有关在HTTP流包装器上使用readfile的说明http://php.net/manual/en/function.readfile.php

怎么样

$source=$url
header("Expires: 0");
header("Cache-Control: private");
header("Pragma: cache");
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
readfile($source);
exit();