PHPWord - Getting a count of pages?

自古美人都是妖i 提交于 2019-12-12 03:47:45

问题


I'm using PHPWord's template parser to make a document, then the command line to auto-print the document. The document MUST be on a single page, because it's a certificate, and is to be printed on special paper.

I'm adding in peoples' names, so people with longer names could throw one line onto two, and push everything down onto a second page.

Does PHPWord have a way to count the number of pages, so I can raise an error if the number of pages exceeds one?


回答1:


After pawing through the source, it looks like it can't be done yet.

However in app.xml there's a tag called "Pages" that should contain the number of pages. I don't think it's accurate, but it's at least something.

Here's some sample code:

  // Include PHPWord and other stuff before here
  function getPages() {
    $zip = new \PhpOffice\PhpWord\Shared\ZipArchive();
    $zip->open("/path/to/your/document.docx");
    preg_match("/\<Pages>(.*)\<\/Pages\>/", $zip->getFromName("docProps/app.xml"), $var);
    return $var[0];
  }

This returns 1 for me on a document that should have 2 pages. It could be PHPWord not bothering to calculate the number of pages, or it counting page breaks only, but at least it's a start.

EDIT: Using the Word command line, I can update the page count programatically:

\path\to\winword.exe /mToolsWordCountRecount /mFileSave /mFileCloseOrExit myfile.docx

This adds a second or two to generation, but at least now I can accurately detect the number of pages




回答2:


This is an alternative (PhpOffice\PHPWord library required).

    $zip = new \PhpOffice\PhpWord\Shared\ZipArchive();
    $zip->open('Path/to/Doc/File');
    $xml = new \DOMDocument();
    $xml->loadXML($zip->getFromName("docProps/app.xml"));

    /* Echoes number of pages according to app.xml */
    echo $xml->getElementsByTagName('Pages')->item(0)->nodeValue);


来源:https://stackoverflow.com/questions/40210468/phpword-getting-a-count-of-pages

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!