如何使用PHP在网络浏览器中打开PDF文件?

2021年3月9日16:13:08 发表评论 1,236 次浏览

PHP使用标准代码在Web浏览器中显示pdf文件。显示pdf的过程涉及服务器上PDF文件的位置, 并且它使用各种类型的标头以类型, 处置, 传输编码等形式定义内容组成。PHP传递PDF文件以在浏览器中读取它。浏览器要么显示它, 要么从本地服务器下载它, 然后显示pdf。

注意:PHP实际上并未读取PDF文件。无法将文件识别为pdf。它仅将PDF文件传递到浏览器以在其中读取。如果将pdf文件复制到XAMPP的htdocs文件夹中, 则无需指定文件路径。

范例1:本示例在浏览器上显示pdf文件。

<?php
  
// Store the file name into variable
$file = 'filename.pdf' ;
$filename = 'filename.pdf' ;
  
// Header content type
header( 'Content-type: application/pdf' );
  
header( 'Content-Disposition: inline; filename="' . $filename . '"' );
  
header( 'Content-Transfer-Encoding: binary' );
  
header( 'Accept-Ranges: bytes' );
  
// Read the file
@readfile( $file );
  
?>

输出如下:

如何使用PHP在网络浏览器中打开PDF文件?1

范例2:

本示例显示格式并解释代码的每个部分

<?php
  
// The location of the PDF file
// on the server
$filename = "/path/to/the/file.pdf" ;
  
// Header content type
header( "Content-type: application/pdf" );
  
header( "Content-Length: " . filesize ( $filename ));
  
// Send the file to the browser.
readfile( $filename );
?>

输出如下:

如何使用PHP在网络浏览器中打开PDF文件?2

木子山

发表评论

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