无法下载为pdf文件

时间:2014-02-03 07:00:16

标签: php pdf

在这里,我一直在尝试使用PHP将HTML文件转换为PDF,并在用户点击“下载”按钮时下载它。我能够将HTML转换为PDF但我无法下载,而是在尝试打开此PHP页面时,会下载一些错误的文件($ file)。

我提到download file using PHP和问题Using php to force download a pdf,但没有帮助我。

这是我的PHP代码:

<?php

  function download_pdf()
  {
     require('html2pdf/html2fpdf.php');
     $pdf=new HTML2FPDF();

     $pdf->AddPage();
     $fp = fopen("demo.html","r");
     $strContent = fread($fp, filesize("demo.html"));
     fclose($fp);

     $pdf->WriteHTML($strContent);
     $pdf->Output("sample.pdf");

  }

  function download()
  {

 download_pdf();
// Define the path to file,you want to make it downloadable
 $file = ‘sample.pdf’;
 if(!$file)
 {
      // File doesn’t exist, output will show error
      die(" file not found");
 }
 else
 {
   // Set headers
      header('Cache-Control: public');
      header('Content-Description: File Transfer');
      header('Content-Disposition: attachment; filename=$file');
      header('Content-Type: application/pdf');
      header('Content-Transfer-Encoding: binary');
  // Read the file from disk
      readfile($file);
 }
 }

?> 
<input type="button" name="download" value="Download as PDF" style=" position:absolute; top:520px; left:600px;" onclick="<?php download(); ?>"/>

2 个答案:

答案 0 :(得分:0)

您需要double quotes

header("Content-Disposition: attachment; filename=$file");

答案 1 :(得分:0)

将您的PHP代码更改为此并相应地进行一些更改,尤其是设置文件的路径。参考链接:download file

<?php

// place this code inside a php file and call it f.e. "download.php"
$path = $_SERVER['DOCUMENT_ROOT']."/path2file/"; // change the path to fit your websites document structure
$fullPath = $path.$_GET['download_file'];

if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
    case "pdf":
    header("Content-type: application/pdf"); // add here more headers for diff. extensions
    header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to    force a download
    break;
    default;
    header("Content-type: application/octet-stream");
    header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
    $buffer = fread($fd, 2048);
    echo $buffer;
}
}
fclose ($fd);
exit;
// example: place this kind of link into the document where the file download is offered:
// <a href="download.php?download_file=some_file.pdf">Download here</a>
?>