如何使用PHP在HTML链接中下载PDF文件?

2021年3月29日17:41:28 发表评论 942 次浏览

PHP的帮助下使用HTML从HTML链接下载PDFheader()函数在PHP中。的header()函数用于发送原始HTTP标头。有时它希望提示用户保存诸如生成的PDF之类的数据。

语法如下:

http响应头以下载任何应用程序头(" Content-Type:应用程序/八位字节流");

http响应标头, 用于设置组成和文件以下载标头(" Content-Disposition:附件; filename =" downloaded.pdf"");

请求的文件的长度需要下载头文件(" Content-Length:"。filesize(" download.pdf"));

读取文件并将其写入输出缓冲区。 readfile('original.pdf');

注意:请记住, 在发送任何实际输出之前, 必须通过常规HTML标记, 文件中的空白行或从PHP发送HTTP header()。

范例1:将以下HTML文件另存为htmllinkpdf.html并将PHP文件另存为downloadpdf.php

以下示例说明了使用HTML链接下载PDF文件的概念。

这里下载的文件似乎是PDF格式, 但没有任何内容, 在任何应用程序中打开时都显示错误

HTML代码:

<!DOCTYPE html>
< html >
  
< head >
     < title >Download PDF using PHP from HTML Link</ title >
</ head >
  
< body >
     < center >
         < h2 style = "color:green;" >Welcome To GFG</ h2 >
         < p >< b >Click below to download PDF</ b >
         </ p >
         < a href = "gfgpdf.php?file=gfgpdf" >Download PDF Now</ a ></ center >
</ body >
  
</ html >

PHP代码:

<?php
  
$file = $_GET [ "file" ] . ".pdf" ;
  
// We will be outputting a PDF
header( 'Content-Type: application/pdf' );
  
// It will be called downloaded.pdf
header( 'Content-Disposition: attachment; filename="gfgpdf.pdf"' );
  
$imagpdf = file_put_contents ( $image , file_get_contents ( $file )); 
  
echo $imagepdf ;
?>

输出如下:

如何使用PHP在HTML链接中下载PDF文件?1
如何使用PHP在HTML链接中下载PDF文件?2

以下示例说明了使用HTML链接在本地下载PDF文件(即从local读取gfgpdf.pdf文件)的概念。

范例2:将HTML文件另存为htmllinkpdf.html并将PHP文件另存为downloadpdf.php

HTML代码:

<!DOCTYPE html>
< html >
  
< head >
     < title >Download PDF using PHP from HTML Link</ title >
</ head >
  
< body >
     < center >
         < h2 style = "color:green;" >Welcome To GFG</ h2 >
         < p >< b >Click below to download PDF</ b >
         </ p >
         < a href = "downloadpdf.php?file=gfgpdf" >Download PDF Now</ a >
     </ center >
</ body >
  
</ html >

PHP代码:

<?php
  
header( "Content-Type: application/octet-stream" );
  
$file = $_GET [ "file" ]  . ".pdf" ;
  
header( "Content-Disposition: attachment; filename=" . urlencode( $file ));   
header( "Content-Type: application/download" );
header( "Content-Description: File Transfer" );            
header( "Content-Length: " . filesize ( $file ));
  
flush (); // This doesn't really matter.
  
$fp = fopen ( $file , "r" );
while (! feof ( $fp )) {
     echo fread ( $fp , 65536);
     flush (); // This is essential for large downloads
} 
  
fclose( $fp ); 
?>

输出如下:

如何使用PHP在HTML链接中下载PDF文件?3
如何使用PHP在HTML链接中下载PDF文件?4

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: