簡體   English   中英

無法下載為pdf文件

[英]Unable to download as a pdf file

在這里,我一直在嘗試使用PHP將HTML文件轉換為PDF,並在用戶單擊“下載”按鈕時將其下載。 我能夠將HTML轉換為PDF,但我無法下載它,而是在嘗試打開此PHP頁面時下載了一些錯誤的文件($ file)。

我已經提到了使用PHP和SO的下載文件的問題使用php來強制下載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(); ?>"/>

您需要在這里使用雙引號

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

將您的PHP代碼更改為此,並進行相應的更改,尤其是設置文件的路徑。 參考鏈接: 下載文件

<?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>
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM