我如何使用php自动下载生成的pdf

时间:2020-02-24 11:43:35

标签: php pdf

我需要使我的网站自动下载我生成的pdf文件, 所以我用这段代码使用dompdf生成了pdf:

include('pdf.php');
$file_name = "ORDER-".$name . '.pdf';
$html_code = '<link rel="stylesheet" href="bootstrap.min.css">';
$html_code .= fetch_customer_data();
$pdf = new Pdf();
$pdf->load_html($html_code);
$pdf->render();
$file = $pdf->output();
file_put_contents($file_name, $file);

当我在本地主机中运行pdf时,将pdf下载到存在源代码文件的同一文件中,并且一切都很好,但是当我尝试在真实服务器上运行时,我找不到pdf,所以我使用了此代码,因此它将自动下载到下载文件中:

    header('Content-Type: application/download');
    header("Content-Disposition: attachment; filename=\"" . $file_name . "\"");
    header("Content-Length: " . filesize($file_name));

这样就完成了工作,但是当我打开文件时,我发现它为空或带有代码源页面的结果 我不知道这是怎么回事有人可以告诉我

pdf.php文件:

<?php

//pdf.php

require_once 'dompdf/autoload.inc.php';

use Dompdf\Dompdf;

class Pdf extends Dompdf{

 public function __construct(){
  parent::__construct();
 }
}

?>

1 个答案:

答案 0 :(得分:0)

我刚刚添加了return $pdf->stream();并删除了

    header('Content-Type: application/download');
    header("Content-Disposition: attachment; filename=\"" . $file_name . "\"");
    header("Content-Length: " . filesize($file_name));