【问题标题】:PHPWord generating a blank pagePHPWord 生成一个空白页
【发布时间】:2014-07-24 15:39:02
【问题描述】:

这是我的代码:

$PHPWord = new PHPWord();
$section = $PHPWord->createSection();
$section->addText('Goodby WOrld!');

header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=byeWorld.docx");
header("Content-Type: application/docx");
header("Content-Transfer-Encoding: binary");

$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('byeWorld.docx');

它正在下载文件 (byeWorld.docx) 但文件是空白的。

这里有什么问题?

【问题讨论】:

    标签: php phpword


    【解决方案1】:

    保存Word文件后,可以给出文件的完整路径并下载。它目前正在保存为 word 文件。我在 laravel 中使用如下:

    $fileName= "word.docx";
    $fileLink= base_path(). $file;
     
    $headers = array(
                'Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            );
    
    return Response::download($fileLink,$fileName, $headers);
    

    【讨论】:

      【解决方案2】:

      您正在保存到服务器上的文件 ('byeWorld.docx'),而不是发送到浏览器,因此无需设置标题。

      如果你想发送到浏览器,那么你应该保存到'php://output'那么你需要headers

      【讨论】:

        【解决方案3】:

        您的标题似乎有问题。根据我读过的例子,你不需要它们。或者,另一种可能性,不要在创建文档的过程中声明它们。顶一下试试?并确保您在顶部使用requirePHPWord.php

        来自http://phpword.codeplex.com/documentation

        // Include the PHPWord.php, all other classes were loaded by an autoloader
        require_once 'PHPWord.php';
        
        // Create a new PHPWord Object
        $PHPWord = new PHPWord();
        
        // Every element you want to append to the word document is placed in a section. So you need a section:
        $section = $PHPWord->createSection();
        
        // After creating a section, you can append elements:
        $section->addText('Hello world!');
        
        // You can directly style your text by giving the addText function an array:
        $section->addText('Hello world! I am formatted.', array('name'=>'Tahoma', 'size'=>16, 'bold'=>true));
        
        // If you often need the same style again you can create a user defined style to the word document
        // and give the addText function the name of the style:
        $PHPWord->addFontStyle('myOwnStyle', array('name'=>'Verdana', 'size'=>14, 'color'=>'1B2232'));
        $section->addText('Hello world! I am formatted by a user defined style', 'myOwnStyle');
        
        // You can also putthe appended element to local object an call functions like this:
        $myTextElement = $section->addText('Hello World!');
        $myTextElement->setBold();
        $myTextElement->setName('Verdana');
        $myTextElement->setSize(22);
        
        // At least write the document to webspace:
        $objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
        $objWriter->save('helloWorld.docx');
        

        【讨论】:

        • 没有标题,它甚至不会下载。没有他们什么都不会发生(
        • 我使用了文档中的相同示例...同样的事情...不会下载文件