【问题标题】:How to edit headers/footers from a document using PHPWord?如何使用 PHPWord 编辑文档的页眉/页脚?
【发布时间】:2015-08-24 01:43:09
【问题描述】:

我正在使用 PHPWord 创建文档。我需要做的是编辑现有 docx/odt 文档的页眉/页脚内容。将内容添加到文档中并不难。但是我花了一整天的时间在互联网上寻找解决方案。这是我只能通过它向现有页眉/页脚内容添加内容的代码:

$source = "DumpFiles/".$_FILES['file']['name'];
    $fileName = $_FILES['file']['name'];
    $phpWord = \PhpOffice\PhpWord\IOFactory::load($source);
    echo "File Loaded";

    // Get Sections from the imported document...
    $sections = $phpWord->getSections();
    $section = $sections[0];

    // Adding Header and Footer Content
    if(isset($_POST['headerContent']) && $_POST['headerContent']!=null)
    {
        $headert = $section->createHeader();
        $table = $headert->addTable();
        $table->addRow();
        $table->addCell(4500)->addText($_POST['headerContent']);
    }
    if(isset($_POST['footerContent']) && $_POST['footerContent'])
    {
        $footervar = $section->createFooter();
        $table = $footervar->addTable();
        $table->addRow();
        $table->addCell(4500)->addText($_POST['footerContent']);
    }

我知道直接使用global 变量是一种不好的做法。 :-p

一旦我让现有代码工作,我会纠正我的代码中的这些差异。

非常感谢带有示例的解决方案。

【问题讨论】:

    标签: php phpword


    【解决方案1】:

    另一种方式是这样的:

    $PHPWord = new PHPWord();
    $section = $PHPWord->createSection();
    $header = $section->createHeader();
    $header->addImage('images/header.png');
    $footer = $section->createFooter();
    $footer->addImage('images/footer.png');
    

    【讨论】:

      【解决方案2】:

      您可以通过以下方式访问现有标题内容(简化以使其更短,即缺少所有存在和类型检查):

      $headers = $section->getHeaders();
      $header1 = $headers[1]; // note that the first index is 1 here (not 0)
      
      $elements = $header1->getElements();
      $element1 = $elements[0]; // and first index is 0 here normally
      
      // for example manipulating simple text information ($element1 is instance of Text object)
      $element1->setText("This is my text addition - old part: " . $element1->getText());
      

      获取页脚数据非常相似:

      $footers = $section->getFooters();
      

      【讨论】:

      • 感谢您的回复。刚刚试用了您的代码,它返回以下错误:Fatal error: Call to undefined method PhpOffice\PhpWord\Element\Table::setText() 可能出了什么问题?
      • 这意味着现有的(第一个)标题元素是一个 Table 对象(而不是直接的示例 Text 对象),即您只需要更改访问数据的方式: $element1->getRows( ) 为您获取行,然后您继续前进(详细信息取决于您在页眉和页脚中实际拥有的内容以及您要修改的部分)
      • 再次感谢您的建议。我稍微改变了我以前的代码并让它工作。再次感谢。
      猜你喜欢
      • 2011-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2013-03-14
      • 2021-08-29
      • 1970-01-01
      相关资源
      最近更新 更多