如何在PHP下载PDF?

时间:2018-03-27 06:42:02

标签: php

这个代码我用PHP在fpdf中生成简单的pdf文件,我不需要在浏览器中显示。我只需要在页面加载时下载它。

<?Php

  require('fpdf17/fpdf.php');

  $pdf = new FPDF();

  $pdf->AddPage();


  $date = date('Y-m-d');

  $width_cell = array(75, 75, 40);

  $pdf->SetFont('Arial', 'B', 20);

  $pdf->Cell(50, 10, "Contact List( Downloaded on  " . $date . ")");

  $pdf->Ln();

  $pdf->Ln();

  $pdf->SetFont('Arial', '', 14);

  $pdf->SetFillColor(193, 229, 252); // Background color of header

  // Header starts ///

  $pdf->Cell($width_cell[0], 10, 'First Name', 1, 0, 'L', true); // First header column

  $pdf->Cell($width_cell[1], 10, 'Last Name', 1, 0, 'L', true); // Second header column

  $pdf->Cell($width_cell[2], 10, 'Contact Number', 1, 0, 'L', true); // Third header column

  $pdf->Ln();
  //// header ends ///////

  $pdf->SetFillColor(235, 236, 236); // Background color of header
  $fill = false; // to give alternate background fill color to rows

  /// end of records ///

  $pdf->Output();
?>

2 个答案:

答案 0 :(得分:0)

也许你需要readfile() - 函数。

int readfile ( string $filename [, bool $use_include_path = FALSE [, resource $context ]] )

这将读取文件并将其写入输出缓冲区。

任何参考资料见

http://php.net/manual/en/function.readfile.php

希望这有帮助

答案 1 :(得分:0)

我在codeigniter中使用m_pdf库来下载生成的pdf文件,这对我有用。也许这对你有帮助。

function generate_pdf($view_path, $view_data){
    $this->load->library('M_pdf');

    $directory_name = 'abc_pdf';
    $filename       = "abc.pdf";
    $pdfFilePath    = FCPATH."/uploads/".$directory_name.'/'.$filename;

    if (!is_dir(FCPATH.'/uploads/'.$directory_name)) {
        mkdir(FCPATH.'/uploads/' . $directory_name, 0777, TRUE);
    }

    if (file_exists($pdfFilePath)){
        unlink($pdfFilePath);
    }
    $html = $this->load->view('abc/'.$view_path, $view_data, true);
    $this->m_pdf->pdf->WriteHTML($html);
    $this->m_pdf->pdf->Output("./uploads/".$directory_name.'/'.$filename, "F");


    return $directory_name.'/'.$filename;
}