2015-06-09 133 views
1

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

$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

我会改正我的代码中的这些差异,一旦我得到现有的代码工作。

一个例子的解决方案将不胜感激。

回答

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(); 
+0

谢谢您的答复。刚刚试过你的代码,它返回以下错误: '致命错误:调用未定义的方法PhpOffice \ PhpWord \ Element \ Table :: setText()' 什么可能会出错? –

+1

这意味着现有的(第一个)头元素是一个Table对象(而不是直接使用示例Text对象),也就是说,您只需要改变访问数据的方式:$ element1-> getRows()为您提供行,而您请继续阅读(详细信息取决于您在页眉和页脚中实际存在的内容以及要修改的部分) – ejuhjav

+0

再次感谢您的建议。我改变了我以前的代码,并得到了这个工作。再次感谢。 –

2

另一种方法是这样的:

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