使用 PHP 查找 PDF、Docx、Doc、Ppt、Pptx 文件的页码

-1 php pdf powerpoint doc docx

我希望我的 PHP 应用程序具有此功能:

当用户上传文档(PDF、DOCX、DOC、PPT、PPTC 扩展名)时,上传后用户将获得文档的总页数。

但没有使用exec()功能。

小智 5

可以在 PHP 中直接处理某些格式。DOCx 和 PPTx 很简单:

对于 Word 文件:

function PageCount_DOCX($file) {
    $pageCount = 0;

    $zip = new ZipArchive();

    if($zip->open($file) === true) {
        if(($index = $zip->locateName('docProps/app.xml')) !== false)  {
            $data = $zip->getFromIndex($index);
            $zip->close();
            $xml = new SimpleXMLElement($data);
            $pageCount = $xml->Pages;
        }
        $zip->close();
    }

    return $pageCount;
}
Run Code Online (Sandbox Code Playgroud)

对于 PowerPoint

function PageCount_PPTX($file) {
    $pageCount = 0;

    $zip = new ZipArchive();

    if($zip->open($file) === true) {
        if(($index = $zip->locateName('docProps/app.xml')) !== false)  {
            $data = $zip->getFromIndex($index);
            $zip->close();
            $xml = new SimpleXMLElement($data);
            print_r($xml);
            $pageCount = $xml->Slides;
        }
        $zip->close();
    }

    return $pageCount;
}
Run Code Online (Sandbox Code Playgroud)

较旧的 Office 文档则是另一回事。您可以在这里找到一些关于执行此操作的讨论:How to get the number of Pages in a Word Document on linux?

至于 PDF 文件,我更喜欢使用 FPDI,尽管它需要许可证才能解析较新的 PDF 文件格式。您可以像这样简单地使用它:

function PageCount_PDF($file) {
    $pageCount = 0;
    if (file_exists($file)) {
        require_once('fpdf/fpdf.php');
        require_once('fpdi/fpdi.php');
        $pdf = new FPDI();                              // initiate FPDI
        $pageCount = $pdf->setSourceFile($file);        // get the page count
    }
    return $pageCount;
}
Run Code Online (Sandbox Code Playgroud)