从文件下载PDF的优雅方式


Elegant way to get PDF download from file

我得到了一个文件,当给定一个?ordernummer=123456时,它会从数据库中获取必要的数据,并使用FPDF生成一个PDF文件,强制下载PDF。工作正常。现在我想从另一个页面调用此文件,以便在按下按钮或链接时下载 PDF 文件。现在我正在使用include(),它可以工作,但在我看来不是很优雅。我试过使用file_get_contents();但这也不起作用。有人有好的解决方案吗?

$ordernummer = "204377";
$postdata = http_build_query(
    array(
        'ordernummer' => $ordernummer
    )
);
$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);
$context  = stream_context_create($opts);
$result = file_get_contents('http://url.nl/pdf/generate_pakbon.php', false, $context);

您正在寻找的是PHP中的"强制下载"。这是通过正确设置文件的标头,然后读取PHP文件中的文件来完成的。

使用 PHP 强制下载:

如果是 PDF 文件,则需要以下标头:

header("Content-disposition: attachment; filename=pakbon_".intval($_GET['ordernummer']).".pdf");
header("Content-type: application/pdf");

filename=部分是您强制下载的文件名。所以不是现有文件。

设置标头后,您可以使用以下命令读取文件:

readfile('http://ledisvet.nl/pdf/generate_pakbon.php?ordernummer='.intval($_GET['ordernummer']);

如果您将其全部添加到文档中并将其称为"downloadpakbon.php",您只需链接到页面中的<a href="downloadpakbon.php?ordernummer=123456">download pakbon</a>,下载将是强制的。制作者名单转到此处解释的示例:http://webdesign.about.com/od/php/ht/force_download.htm

仅 FPDF 方法:

还有其他方法可用。FPDF有一个名为"输出"的方法,您可能已经在使用该方法。此方法中有 4 个可能的参数,其中一个是"D",代表强制下载:http://www.fpdf.org/en/doc/output.htm

一种方法是在generate_pakbon.php中添加一个额外的参数,例如 ?download=true,然后将最终输出方法基于此参数:

if($_GET['download'] === true) {
  $pdf->Output('Order123.pdf', 'D');
} else {
  $pdf->Output('Order123.pdf', 'I');
}

您的链接 http://ledisvet.nl/pdf/generate_pakbon.php 确实下载到我的浏览器(Chrome)中。若要确保这不是特定于浏览器的行为,请在generate_pakbon.php的开头添加以下行(注意:确保在任何其他输出之前)

header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=pakbon.pdf");
header("Pragma: no-cache");
header("Expires: 0");

然后我会将你引用的代码移动到这个 php 文件中。