PhpWord将页脚添加到模板

问题描述

我想在创建的文档中添加页脚,如何用PHPword做到这一点?

我的模板处理代码

$template = new \PHPOffice\PHPWord\TemplateProcessor("my-template.docx");

$table = new \PHPOffice\PHPWord\Element\Table();

$table->addRow();
$table->addCell()->addText("test");

$template->setComplexBlock('table_var',$table);

$template->saveAs("new-file.docx");

解决方法

another post中所述,首先保存模板,然后再次打开结果,如下所示:

$file = \PhpOffice\PhpWord\IOFactory::load("new-file.docx");

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

然后,如果您的模板没有任何页脚,请添加以下内容:

$footer1 = $section->createFooter();
$footer1->addImage('images/footer.png');

或者,您可以编辑现有页脚,例如:

// Note that the first index is 1 here (not 0).
$footers = $section->getFooters();
$footer1 = $footers[1];

// And first index is 0 for elements normally.
$elements = $footer1->getElements();
$element1 = $elements[0];

// For example manipulating simple text information ($element1 is instance of Text object)
$element1->setText("My new text,old content: " . $element1->getText());