当 PHP 遇到 PDF

< ?php 一.在线预览

在web开发当中我们经常需要进行需要在线浏览PDf内容,在线嵌入动态pdf,传统的解决方法安装客户端PDF阅读器,如果是在谷歌是可以在线浏览的,因为他自身就带了一些插件,以前遇到这样的问题往往是费时又费力,很不好解决
试用了几个方案:

  1. 截图
    1.1 方案是实现了,用php插件Imagick配合Ghostscript可以达到要求,但是有几个问题,比如:浪费空间,对SEO不友好。。。故放弃了;
    1.2 用一些直接展示pdf或者转换成Flash的方式,类似文库,听说比较简单,但是没有试过,同样是不利于SEO,直接Pass掉。

  2. javascript实现的pdf插件效果,使用是PDF.js,和 Google Chrome 使用的源自 Foxit 的闭源 PDF 浏览插件不同,PDF.js 是基于开放的 HTML5 及 JavaScript 技术实现的开源产品。Git代码地址https://github.com/mozilla/pdf.js

    linux下的教程网上可以有
    我的是Windows下,写一下经验:
    最初直接在页面导入各种js,发现文件死活导不进去,也不去整了,因为要做页面嵌入,所以用一个Iframe,代码:


<iframe src="url?file=damo.pdf" />" width="100%" height="800"></iframe>

搞定!!,DIY一下就OK

< ?php 二.读取PDF页数

  1. 用Imagick插件

    这两函数都可以 getNumberImages() and identifyImage()
    使用心得:尼玛,太慢了,完全等不起也伤不起,因为他要把整个文件读完,擦

  2. FPDI
function getNumPagesPdf($filepath){
    $fp = @fopen(preg_replace("/\[(.*?)\]/i", "",$filepath),"r");
    $max=0;
    while(!feof($fp)) {
            $line = fgets($fp,255);
            if (preg_match('/\/Count [0-9]+/', $line, $matches)){
                    preg_match('/[0-9]+/',$matches[0], $matches2);
                    if ($max<$matches2[0]) $max=$matches2[0];
            }
    }
    fclose($fp);
    if($max==0){
        $im = new imagick($filepath);
        $max=$im->getNumberImages();
    }

    return $max;
} 

这加了一个慢速的backup<方法一>,因为不是每一个PDF都用Count,这也不是普适的

  1. 用插件pdfin,
    Linux和Windows下有相应的版本,自行下载http://www.foolabs.com/xpdf/download.html
Title:          test1.pdf
Author:         John Smith
Creator:        PScript5.dll Version 5.2.2
Producer:       Acrobat Distiller 9.2.0 (Windows)
CreationDate:   01/09/13 19:46:57
ModDate:        01/09/13 19:46:57
Tagged:         yes
Form:           none
Pages:          13    <-- This is what we need
Encrypted:      no
Page size:      2384 x 3370 pts (A0)
File size:      17569259 bytes
Optimized:      yes
PDF version:    1.6

听说这是他的运行了的返回结果,不管怎样,下面牛逼了

function getPDFPages($document)
{
    $cmd = "/path/pdfinfo";           // Linux
    $cmd = "C:\\path\\pdfinfo.exe";  // Windows

    // Parse entire output
    // Surround with double quotes if file name has spaces
    exec("$cmd \"$document\"", $output);

    // Iterate through lines
    $pagecount = 0;
    foreach($output as $op)
    {
        // Extract the number
        if(preg_match("/Pages:\s*(\d+)/i", $op, $matches) === 1)
        {
            $pagecount = intval($matches[1]);
            break;
        }
    }

    return $pagecount;
}

// Use the function
echo getPDFpages("test 1.pdf");  

OK!大功告成,特别是Linux上,效率不错

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值