首页 文章

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

提问于
浏览
115

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

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

我想要的是 show 用户我的pdf文件, not creating or download pdf . 这是我从官方php文档中得到的:

<?php
header('Content-type: application/pdf');
readfile('the.pdf');
?>

还有我的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

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

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

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

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

edit :这是我的主要PHP代码:

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

edit :现在代码正常运行 . 但加载进度条(在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);
?>

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

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

谢谢! :)

5 回答

  • 1

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

    还要记住,这也会受到浏览器设置的影响 - 某些浏览器可能被配置为 always 下载PDF文件或在不同的应用程序中打开它们(例如Adobe Reader)

  • 47
    $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);
    

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

    Content-Disposition: inline
    

    Content-Disposition: attachment
    
  • 12

    您可以修改PDF渲染器(如xpdf或evince)以渲染到服务器上的图形图像,然后将图像传送给用户 . 这就是Google的quick view PDF文件的工作方式,它们在本地呈现,然后将图像传送给用户 . 没有下载的PDF文件,并且源代码非常模糊 . :)

  • 0

    使用PDF显示而不是下载的最安全的方法似乎是使用 objectiframe 元素嵌入它 . 还有像Google的PDF查看器这样的第三方解决方案 .

    有关概述,请参见Best Way to Embed PDF in HTML .

    还有DoPDF,一个基于Java的浏览器内PDF浏览器 . 我不能说它的质量,但它看起来很有趣 .

  • 4

    您还可以使用以下网址提供的fpdf类:http://www.fpdf.org . 它提供了输出到文件和在浏览器上显示的选项 .

相关问题