通过PHP/Perl在用户浏览器中显示PDF文件

dim*_*ony 117 php pdf perl

我想向用户显示PDF文件.我使用cgi来显示pdf的原因是我想跟踪pdf的点击次数,并隐藏保存的pdf的真实位置.

我一直在互联网上搜索,只发现如何向用户显示保存对话框并创建pdf,而不是向用户显示文件.

我想要的是用户显示我的pdf文件,而不是创建或下载 pdf.这是我从官方php文档中得到的:

<?php
header('Content-type: application/pdf');
readfile('the.pdf');
?>
Run Code Online (Sandbox Code Playgroud)

还有我的google-search-result perl代码:

open(PDF, "the.pdf") or die "could not open PDF [$!]";
binmode PDF;
my $output = do { local $/; <PDF> };
close (PDF);

print "Content-Type: application/pdf\n";
print "Content-Length: " .length($output) . "\n\n";
print $output
Run Code Online (Sandbox Code Playgroud)

如果你在红宝石上做,请告诉我.但我不确定我的服务器是否支持rails.

很抱歉,如果我的代码与显示pdf的方法相距太远,因为我对pdf处理以及如何实现此问题一无所知.

让我们假设用户拥有Adobe Reader插件.那么,如何解决我的问题呢?

编辑:我想显示普通的pdf文件.我的主要目的:跟踪我的pdf文件并使用一些花哨的网址.

编辑:这是我的主要PHP代码:

<?php
$file='/files/the.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="the.pdf"');
@readfile($file);
?>
Run Code Online (Sandbox Code Playgroud)

编辑:现在代码正常工作.但是加载进度条(在Adobe Reader X插件上)没有显示出来.为什么?有人可以帮帮我吗?这是我的主要代码:

<?php
$file='./files/the.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="the.pdf"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
@readfile($file);
?>
Run Code Online (Sandbox Code Playgroud)

编辑:我的所有问题都解决了.这是最终的代码:

<?php
$file = './path/to/the.pdf';
$filename = 'Custom file name for the.pdf'; /* Note: Always use .pdf at the end. */

header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');

@readfile($file);
?>
Run Code Online (Sandbox Code Playgroud)

谢谢!:)

Ste*_*hen 49

我假设您希望PDF在浏览器中显示,而不是强制下载.如果是这种情况,请尝试Content-Disposition使用值设置标头inline.

另请记住,这也会受到浏览器设置的影响 - 某些浏览器可能配置为始终下载PDF文件或在其他应用程序中打开它们(例如Adobe Reader)

  • 很高兴听到,很高兴知道解决方案!如果你能发布最终代码,显示你发送的标题,对于遇到这个问题的其他人来说,这将是一件好事. (7认同)
  • <?php header('Content-type:application/pdf'); header('Content-Disposition:inline; filename ="the.pdf"'); ReadFile的( '/目录/到/ the.pdf'); ?> (4认同)

Kar*_*eem 14

    $url ="https://yourFile.pdf";
    $content = file_get_contents($url);

    header('Content-Type: application/pdf');
    header('Content-Length: ' . strlen($content));
    header('Content-Disposition: inline; filename="YourFileName.pdf"');
    header('Cache-Control: private, max-age=0, must-revalidate');
    header('Pragma: public');
    ini_set('zlib.output_compression','0');

    die($content);
Run Code Online (Sandbox Code Playgroud)

经过测试,工作正常.如果您想要下载文件,请替换

    Content-Disposition: inline
Run Code Online (Sandbox Code Playgroud)

    Content-Disposition: attachment
Run Code Online (Sandbox Code Playgroud)