PHPWord - Getting a count of pages?

2019-09-11 13:11发布

问题:

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


标签: php phpword