This project is read-only.

PHPWord version capable of embedding docx. pptx and xlsx files into Word files

Mar 18, 2013 at 6:34 PM
I have created a version of PHPWord which allows to generate Word documents with embedded .xls. .xlsx, .doc. .docx. .ppt and .pptx files. It's not capable to attach PDFs because PDFs have to be transformed by wrapping them with something (some data added at the beginning and end of the PDF file) and I couldn't find out how to do this transformation.

The modification involved changes to these files:
PHPWord directory:
  • Media.php
  • Section.php
PHPWord/_staticDocParts directory: added PNG image files for xlsx, docx and pptx (simply duplicated the existing xls, doc and ppt PNGs)

PHPWord/Section directory:
  • Object.php
PHPWord/Section/Table directory:
  • Cell.php
PHPWord/Writer directory:
  • Word2007.php
PHPWord/Writer/Word2007 directory:
  • Document.php
  • DocumentRels.php
  • ContentTypes.php
If anybody would like to have this version of PHPWord, just let me know.
Apr 8, 2013 at 3:45 PM
Since i received a request for this version of PHPWord, but don't know how to post a new version of PHPWord here, I'll simply post as a reply to this message the source code of the files I modified. The replies to this message contain the source code of the files listed in my first post.
Apr 8, 2013 at 3:46 PM
File media.php in PHPWord directory:

<?php
/**
  • PHPWord
    *
  • Copyright (c) 2011 PHPWord
    *
  • This library is free software; you can redistribute it and/or
  • modify it under the terms of the GNU Lesser General Public
  • License as published by the Free Software Foundation; either
  • version 2.1 of the License, or (at your option) any later version.
    *
  • This library is distributed in the hope that it will be useful,
  • but WITHOUT ANY WARRANTY; without even the implied warranty of
  • MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  • Lesser General Public License for more details.
    *
  • You should have received a copy of the GNU Lesser General Public
  • License along with this library; if not, write to the Free Software
  • Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
    *
  • @category PHPWord
  • @package PHPWord
  • @copyright Copyright (c) 010 PHPWord
  • @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  • @version Beta 0.6.3, 08.07.2011
    */
/**
  • PHPWord_Media
    *
  • @category PHPWord
  • @package PHPWord
  • @copyright Copyright (c) 2011 PHPWord
    */
    class PHPWord_Media {

    /**
    • Section Media Elements
    • @var array
      */
      private static $_sectionMedia = array('images'=>array(),
                                    'embeddings'=>array(),
                                    'links'=>array());
      
    /**
    • Header Media Elements
    • @var array
      */
      private static $_headerMedia = array();
    /**
    • Footer Media Elements
    • @var array
      */
      private static $_footerMedia = array();
    /**
    • ObjectID Counter
    • @var int
      */
      private static $_objectId = 1325353440;
    /**
    • Add new Section Media Element
    • @param string $src
    • @param string $type
    • @return mixed
      */
      public static function addSectionMediaElement($src, $type, PHPWord_Section_MemoryImage $memoryImage = null) {
      $mediaId = md5($src);
      $type = strtolower($type);
      $key = ($type == 'image') ? 'images' : 'embeddings';
      $oleobject = in_array ($type, array ('xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx'));

      if(!array_key_exists($mediaId, self::$_sectionMedia[$key])) {
      $cImg = self::countSectionMediaElements('images');
      $cObj = self::countSectionMediaElements('embeddings');
      $rID = self::countSectionMediaElements() + 7;
      
      $media = array();
      
      if($type == 'image') {
          $cImg++;
          $inf = pathinfo($src);
          $isMemImage = (substr(strtolower($inf['extension']), 0, 3) == 'php' && $type == 'image') ? true : false;
      
          if($isMemImage) {
              $ext = $memoryImage->getImageExtension();
              $media['isMemImage'] = true;
              $media['createfunction'] = $memoryImage->getImageCreateFunction();
              $media['imagefunction'] = $memoryImage->getImageFunction();
          } else {
              $ext = $inf['extension'];
              if($ext == 'jpeg') { // Office crashes when adding a jpEg Image, so rename to jpg
                  $ext = 'jpg';
              }
          }
      
          $folder = 'media';
          $file = $type.$cImg.'.'.strtolower($ext);
      // } elseif($type == 'oleObject') {
      } elseif ($oleobject) {         
          $cObj++;
          $folder = 'embedding';
          // $file = $type.$cObj.'.bin';
          $file = $type.$cObj.".$type";
      }
      
      $media['source'] = $src;
      $media['target'] = "$folder/section_$file";
      $media['type'] = $type;
      $media['rID'] = $rID;
      
      self::$_sectionMedia[$key][$mediaId] = $media;
      
      // if($type == 'oleObject') {
      if($oleobject) {
          return array($rID, ++self::$_objectId);
      } else {
          return $rID;
      }
      } else {
      // if($type == 'oleObject') {
      if ($oleobject) {
          $rID = self::$_sectionMedia[$key][$mediaId]['rID'];
          return array($rID, ++self::$_objectId);
      } else {
          return self::$_sectionMedia[$key][$mediaId]['rID'];
      }
      }
      }
    /**
    • Add new Section Link Element
    • @param string $linkSrc
    • @param string $linkName
    • @return mixed
      */
      public static function addSectionLinkElement($linkSrc) {
      $rID = self::countSectionMediaElements() + 7;

      $link = array();
      $link['target'] = $linkSrc;
      $link['rID'] = $rID;
      $link['type'] = 'hyperlink';

      self::$_sectionMedia['links'][] = $link;

      return $rID;
      }
    /**
    • Get Section Media Elements
    • @param string $key
    • @return array
      */
      public static function getSectionMediaElements($key = null) {
      if(!is_null($key)) {
      return self::$_sectionMedia[$key];
      } else {
      $arrImages = self::$_sectionMedia['images'];
      $arrObjects = self::$_sectionMedia['embeddings'];
      $arrLinks = self::$_sectionMedia['links'];
      return array_merge($arrImages, $arrObjects, $arrLinks);
      }
      }
    /**
    • Get Section Media Elements Count
    • @param string $key
    • @return int
      */
      public static function countSectionMediaElements($key = null) {
      if(!is_null($key)) {
      return count(self::$_sectionMedia[$key]);
      } else {
      $cImages = count(self::$_sectionMedia['images']);
      $cObjects = count(self::$_sectionMedia['embeddings']);
      $cLinks = count(self::$_sectionMedia['links']);
      return ($cImages + $cObjects + $cLinks);
      }
      }
    /**
    • Add new Header Media Element
    • @param int $headerCount
    • @param string $src
    • @return int
      */
      public static function addHeaderMediaElement($headerCount, $src, PHPWord_Section_MemoryImage $memoryImage = null) {
      $mediaId = md5($src);
      $key = 'header'.$headerCount;

      if(!array_key_exists($key, self::$_headerMedia)) {
      self::$_headerMedia[$key] = array();
      }

      if(!array_key_exists($mediaId, self::$_headerMedia[$key])) {
      $cImg = self::countHeaderMediaElements($key);
      $rID = $cImg + 1;
      
      $cImg++;
      $inf = pathinfo($src);
      $isMemImage = (substr(strtolower($inf['extension']), 0, 3) == 'php') ? true : false;
      
      $media = array();
      if($isMemImage) {
          $ext = $memoryImage->getImageExtension();
          $media['isMemImage'] = true;
          $media['createfunction'] = $memoryImage->getImageCreateFunction();
          $media['imagefunction'] = $memoryImage->getImageFunction();
      } else {
          $ext = $inf['extension'];
          if($ext == 'jpeg') { // Office crashes when adding a jpEg Image, so rename to jpg
              $ext = 'jpg';
          }
      }
      $file = 'image'.$cImg.'.'.strtolower($ext);
      
      $media['source'] = $src;
      $media['target'] = 'media/'.$key.'_'.$file;
      $media['type'] = 'image';
      $media['rID'] = $rID;
      
      self::$_headerMedia[$key][$mediaId] = $media;
      
      return $rID;
      } else {
      return self::$_headerMedia[$key][$mediaId]['rID'];
      }
      }
    /**
    • Get Header Media Elements Count
    • @param string $key
    • @return int
      */
      public static function countHeaderMediaElements($key) {
      return count(self::$_headerMedia[$key]);
      }
    /**
    • Get Header Media Elements
    • @return int
      */
      public static function getHeaderMediaElements() {
      return self::$_headerMedia;
      }
    /**
    • Add new Footer Media Element
    • @param int $footerCount
    • @param string $src
    • @return int
      */
      public static function addFooterMediaElement($footerCount, $src, PHPWord_Section_MemoryImage $memoryImage = null) {
      $mediaId = md5($src);
      $key = 'footer'.$footerCount;

      if(!array_key_exists($key, self::$_footerMedia)) {
      self::$_footerMedia[$key] = array();
      }

      if(!array_key_exists($mediaId, self::$_footerMedia[$key])) {
      $cImg = self::countFooterMediaElements($key);
      $rID = $cImg + 1;
      
      $cImg++;
      $inf = pathinfo($src);
      $isMemImage = (substr(strtolower($inf['extension']), 0, 3) == 'php') ? true : false;
      
      $media = array();
      if($isMemImage) {
          $ext = $memoryImage->getImageExtension();
          $media['isMemImage'] = true;
          $media['createfunction'] = $memoryImage->getImageCreateFunction();
          $media['imagefunction'] = $memoryImage->getImageFunction();
      } else {
          $ext = $inf['extension'];
          if($ext == 'jpeg') { // Office crashes when adding a jpEg Image, so rename to jpg
              $ext = 'jpg';
          }
      }
      $file = 'image'.$cImg.'.'.strtolower($ext);
      
      $media['source'] = $src;
      $media['target'] = 'media/'.$key.'_'.$file;
      $media['type'] = 'image';
      $media['rID'] = $rID;
      
      self::$_footerMedia[$key][$mediaId] = $media;
      
      return $rID;
      } else {
      return self::$_footerMedia[$key][$mediaId]['rID'];
      }
      }
    /**
    • Get Footer Media Elements Count
    • @param string $key
    • @return int
      */
      public static function countFooterMediaElements($key) {
      return count(self::$_footerMedia[$key]);
      }
    /**
    • Get Footer Media Elements
    • @return int
      */
      public static function getFooterMediaElements() {
      return self::$_footerMedia;
      }
      }
      ?>
Apr 8, 2013 at 3:48 PM
File section.php in PHPWord directory:

<?php
/**
  • PHPWord
    *
  • Copyright (c) 2011 PHPWord
    *
  • This library is free software; you can redistribute it and/or
  • modify it under the terms of the GNU Lesser General Public
  • License as published by the Free Software Foundation; either
  • version 2.1 of the License, or (at your option) any later version.
    *
  • This library is distributed in the hope that it will be useful,
  • but WITHOUT ANY WARRANTY; without even the implied warranty of
  • MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  • Lesser General Public License for more details.
    *
  • You should have received a copy of the GNU Lesser General Public
  • License along with this library; if not, write to the Free Software
  • Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
    *
  • @category PHPWord
  • @package PHPWord
  • @copyright Copyright (c) 010 PHPWord
  • @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  • @version Beta 0.6.3, 08.07.2011
    */
/**
  • PHPWord_Section
    *
  • @category PHPWord
  • @package PHPWord_Section
  • @copyright Copyright (c) 2011 PHPWord
    */
    class PHPWord_Section {

    /**
    • Section count
    • @var int
      */
      private $_sectionCount;
    /**
    • Section settings
    • @var PHPWord_Section_Settings
      */
      private $_settings;
    /**
    • Section Element Collection
    • @var array
      */
      private $_elementCollection = array();
    /**
    • Section Header
    • @var PHPWord_Section_Header
      */
      private $_header = null;
    /**
    • Section Footer
    • @var PHPWord_Section_Footer
      */
      private $_footer = null;
    /**
    • Create a new Section
    • @param int $sectionCount
    • @param mixed $settings
      */
      public function __construct($sectionCount, $settings = null) {
      $this->_sectionCount = $sectionCount;
      $this->_settings = new PHPWord_Section_Settings();

      if(!is_null($settings) && is_array($settings)) {
      foreach($settings as $key => $value) {
          if(substr($key, 0, 1) != '_') {
              $key = '_'.$key;
          }
          $this->_settings->setSettingValue($key, $value);
      }
      }
      }
    /**
    • Get Section Settings
    • @return PHPWord_Section_Settings
      */
      public function getSettings() {
      return $this->_settings;
      }
    /**
    • Add a Text Element
    • @param string $text
    • @param mixed $styleFont
    • @param mixed $styleParagraph
    • @return PHPWord_Section_Text
      */
      public function addText($text, $styleFont = null, $styleParagraph = null) {
      $givenText = utf8_encode($text);
      $text = new PHPWord_Section_Text($givenText, $styleFont, $styleParagraph);
      $this->_elementCollection[] = $text;
      return $text;
      }
    /**
    • Add a Link Element
    • @param string $linkSrc
    • @param string $linkName
    • @param mixed $styleFont
    • @param mixed $styleParagraph
    • @return PHPWord_Section_Link
      */
      public function addLink($linkSrc, $linkName = null, $styleFont = null, $styleParagraph = null) {
      $linkSrc = utf8_encode($linkSrc);
      if(!is_null($linkName)) {
      $linkName = utf8_encode($linkName);
      }

      $link = new PHPWord_Section_Link($linkSrc, $linkName, $styleFont, $styleParagraph);
      $rID = PHPWord_Media::addSectionLinkElement($linkSrc);
      $link->setRelationId($rID);

      $this->_elementCollection[] = $link;
      return $link;
      }
    /**
    • Add a TextBreak Element
    • @param int $count
      */
      public function addTextBreak($count = 1) {
      for($i=1; $i<=$count; $i++) {
      $this->_elementCollection[] = new PHPWord_Section_TextBreak();
      }
      }
    /**
    • Add a PageBreak Element
      */
      public function addPageBreak() {
      $this->_elementCollection[] = new PHPWord_Section_PageBreak();
      }
    /**
    • Add a Table Element
    • @param mixed $style
    • @return PHPWord_Section_Table
      */
      public function addTable($style = null) {
      $table = new PHPWord_Section_Table('section', $this->_sectionCount, $style);
      $this->_elementCollection[] = $table;
      return $table;
      }
    /**
    • Add a ListItem Element
    • @param string $text
    • @param int $depth
    • @param mixed $styleFont
    • @param mixed $styleList
    • @param mixed $styleParagraph
    • @return PHPWord_Section_ListItem
      */
      public function addListItem($text, $depth = 0, $styleFont = null, $styleList = null, $styleParagraph = null) {
      $text = utf8_encode($text);
      $listItem = new PHPWord_Section_ListItem($text, $depth, $styleFont, $styleList, $styleParagraph);
      $this->_elementCollection[] = $listItem;
      return $listItem;
      }
    /**
    • Add a OLE-Object Element
    • @param string $src
    • @param mixed $style
    • @return PHPWord_Section_Object
      */
      public function addObject($src, $style = null) {

      $object = new PHPWord_Section_Object($src, $style);

      if(!is_null($object->getSource())) {
      $inf = pathinfo($src);
      $ext = strtolower($inf['extension']);
      // if(strlen($ext) == 4 && strtolower(substr($ext, -1)) == 'x') {
      //  $ext = substr($ext, 0, -1);
      // }
      
      $iconSrc = PHPWORD_BASE_PATH . 'PHPWord/_staticDocParts/';
      if(!file_exists($iconSrc.'_'.$ext.'.png')) {
          $iconSrc = $iconSrc.'_default.png';
      } else {
          $iconSrc .= '_'.$ext.'.png';
      }
      
      $rIDimg = PHPWord_Media::addSectionMediaElement($iconSrc, 'image');
      $data = PHPWord_Media::addSectionMediaElement($src, $ext);
      $rID = $data[0];
      $objectId = $data[1];
      
      $object->setRelationId($rID);
      $object->setObjectId($objectId);
      $object->setImageRelationId($rIDimg);
      
      $this->_elementCollection[] = $object;
      return $object;
      } else {
      trigger_error('Source does not exist or unsupported object type.');
      }
      }
    /**
    • Add a Image Element
    • @param string $src
    • @param mixed $style
    • @return PHPWord_Section_Image
      */
      public function addImage($src, $style = null) {
      $image = new PHPWord_Section_Image($src, $style);

      if(!is_null($image->getSource())) {
      $rID = PHPWord_Media::addSectionMediaElement($src, 'image');
      $image->setRelationId($rID);
      
      $this->_elementCollection[] = $image;
      return $image;
      } else {
      trigger_error('Source does not exist or unsupported image type.');
      }
      }
    /**
    • Add a by PHP created Image Element
    • @param string $link
    • @param mixed $style
    • @return PHPWord_Section_MemoryImage
      */
      public function addMemoryImage($link, $style = null) {
      $memoryImage = new PHPWord_Section_MemoryImage($link, $style);
      if(!is_null($memoryImage->getSource())) {
      $rID = PHPWord_Media::addSectionMediaElement($link, 'image', $memoryImage);
      $memoryImage->setRelationId($rID);
      
      $this->_elementCollection[] = $memoryImage;
      return $memoryImage;
      } else {
      trigger_error('Unsupported image type.');
      }
      }
    /**
    • Add a Table-of-Contents Element
    • @param mixed $styleFont
    • @param mixed $styleTOC
    • @return PHPWord_TOC
      */
      public function addTOC($styleFont = null, $styleTOC = null) {
      $toc = new PHPWord_TOC($styleFont, $styleTOC);
      $this->_elementCollection[] = $toc;
      return $toc;
      }
    /**
    • Add a Title Element
    • @param string $text
    • @param int $depth
    • @return PHPWord_Section_Title
      */
      public function addTitle($text, $depth = 1) {
      $text = utf8_encode($text);
      $styles = PHPWord_Style::getStyles();
      if(array_key_exists('Heading_'.$depth, $styles)) {
      $style = 'Heading'.$depth;
      } else {
      $style = null;
      }

      $title = new PHPWord_Section_Title($text, $depth, $style);

      $data = PHPWord_TOC::addTitle($text, $depth);
      $anchor = $data[0];
      $bookmarkId = $data[1];

      $title->setAnchor($anchor);
      $title->setBookmarkId($bookmarkId);

      $this->_elementCollection[] = $title;
      return $title;
      }
    /**
    • Create a new TextRun
    • @return PHPWord_Section_TextRun
      */
      public function createTextRun($styleParagraph = null) {
      $textRun = new PHPWord_Section_TextRun($styleParagraph);
      $this->_elementCollection[] = $textRun;
      return $textRun;
      }
    /**
    • Get all Elements
    • @return array
      */
      public function getElements() {
      return $this->_elementCollection;
      }
    /**
    • Create a new Header
    • @return PHPWord_Section_Header
      */
      public function createHeader() {
      $header = new PHPWord_Section_Header($this->_sectionCount);
      $this->_header = $header;
      return $header;
      }
    /**
    • Get Header
    • @return PHPWord_Section_Header
      */
      public function getHeader() {
      return $this->_header;
      }
    /**
    • Create a new Footer
    • @return PHPWord_Section_Footer
      */
      public function createFooter() {
      $footer = new PHPWord_Section_Footer($this->_sectionCount);
      $this->_footer = $footer;
      return $footer;
      }
    /**
    • Get Footer
    • @return PHPWord_Section_Footer
      */
      public function getFooter() {
      return $this->_footer;
      }
      }
      ?>
Apr 8, 2013 at 3:49 PM
File object.php in PHPWord/Section directory:

<?php
/**
  • PHPWord
    *
  • Copyright (c) 2011 PHPWord
    *
  • This library is free software; you can redistribute it and/or
  • modify it under the terms of the GNU Lesser General Public
  • License as published by the Free Software Foundation; either
  • version 2.1 of the License, or (at your option) any later version.
    *
  • This library is distributed in the hope that it will be useful,
  • but WITHOUT ANY WARRANTY; without even the implied warranty of
  • MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  • Lesser General Public License for more details.
    *
  • You should have received a copy of the GNU Lesser General Public
  • License along with this library; if not, write to the Free Software
  • Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
    *
  • @category PHPWord
  • @package PHPWord
  • @copyright Copyright (c) 010 PHPWord
  • @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  • @version Beta 0.6.3, 08.07.2011
    */
/**
  • PHPWord_Section_Object
    *
  • @category PHPWord
  • @package PHPWord_Section
  • @copyright Copyright (c) 2011 PHPWord
    */
    class PHPWord_Section_Object {

    /**
    • Ole-Object Src
    • @var string
      */
      private $_src;
    /**
    • Image Style
    • @var PHPWord_Style_Image
      */
      private $_style;
    /**
    • Object Relation ID
    • @var int
      */
      private $_rId;
    /**
    • Image Relation ID
    • @var int
      */
      private $_rIdImg;
    /**
    • Object ID
    • @var int
      */
      private $_objId;
    /**
    • Create a new Ole-Object Element
    • @param string $src
    • @param mixed $style
      */
      public function __construct($src, $style = null) {
      $_supportedObjectTypes = array('xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx');
      $inf = pathinfo($src);

      if(file_exists($src) && in_array($inf['extension'], $_supportedObjectTypes)) {
      $this->_src = $src;
      $this->_style = new PHPWord_Style_Image();
      
      if(!is_null($style) && is_array($style)) {
          foreach($style as $key => $value) {
              if(substr($key, 0, 1) != '_') {
                  $key = '_'.$key;
              }
              $this->_style->setStyleValue($key, $value);
          }
      }
      
      return $this;
      } else {
      return false;
      }
      }
    /**
    • Get Image style
    • @return PHPWord_Style_Image
      */
      public function getStyle() {
      return $this->_style;
      }
    /**
    • Get Source
    • @return string
      */
      public function getSource() {
      return $this->_src;
      }
    /**
    • Get Object Relation ID
    • @return int
      */
      public function getRelationId() {
      return $this->_rId;
      }
    /**
    • Set Object Relation ID
    • @param int $rId
      */
      public function setRelationId($rId) {
      $this->_rId = $rId;
      }
    /**
    • Get Image Relation ID
    • @return int
      */
      public function getImageRelationId() {
      return $this->_rIdImg;
      }
    /**
    • Set Image Relation ID
    • @param int $rId
      */
      public function setImageRelationId($rId) {
      $this->_rIdImg = $rId;
      }
    /**
    • Get Object ID
    • @return int
      */
      public function getObjectId() {
      return $this->_objId;
      }
    /**
    • Set Object ID
    • @param int $objId
      */
      public function setObjectId($objId) {
      $this->_objId = $objId;
      }
      }
      ?>
Apr 8, 2013 at 3:51 PM
File cell.php in PHPWord/Section/Table directory:

<?php
/**
  • PHPWord
    *
  • Copyright (c) 2011 PHPWord
    *
  • This library is free software; you can redistribute it and/or
  • modify it under the terms of the GNU Lesser General Public
  • License as published by the Free Software Foundation; either
  • version 2.1 of the License, or (at your option) any later version.
    *
  • This library is distributed in the hope that it will be useful,
  • but WITHOUT ANY WARRANTY; without even the implied warranty of
  • MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  • Lesser General Public License for more details.
    *
  • You should have received a copy of the GNU Lesser General Public
  • License along with this library; if not, write to the Free Software
  • Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
    *
  • @category PHPWord
  • @package PHPWord
  • @copyright Copyright (c) 010 PHPWord
  • @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  • @version Beta 0.6.3, 08.07.2011
    */
/**
  • PHPWord_Section_Table_Cell
    *
  • @category PHPWord
  • @package PHPWord_Section_Table
  • @copyright Copyright (c) 2011 PHPWord
    */
    class PHPWord_Section_Table_Cell {

    /**
    • Cell Width
    • @var int
      */
      private $_width = null;
    /**
    • Cell Style
    • @var PHPWord_Style_Cell
      */
      private $_style;
    /**
    • Cell Element Collection
    • @var array
      */
      private $_elementCollection = array();
    /**
    • Table holder
    • @var string
      */
      private $_insideOf;
    /**
    • Section/Header/Footer count
    • @var int
      */
      private $_pCount;
    /**
    • Create a new Table Cell
    • @param string $insideOf
    • @param int $pCount
    • @param int $width
    • @param mixed $style
      */
      public function __construct($insideOf, $pCount, $width = null, $style = null) {
      $this->_insideOf = $insideOf;
      $this->_pCount = $pCount;
      $this->_width = $width;

      if(!is_null($style)) {
      if(is_array($style)) {
          $this->_style = new PHPWord_Style_Cell();
      
          foreach($style as $key => $value) {
              if(substr($key, 0, 1) != '_') {
                  $key = '_'.$key;
              }
              $this->_style->setStyleValue($key, $value);
          }
      } else {
          $this->_style = $style;
      }
      }
      }
    /**
    • Add a Text Element
    • @param string $text
    • @param mixed $style
    • @return PHPWord_Section_Text
      */
      public function addText($text, $styleFont = null, $styleParagraph = null) {
      $text = utf8_encode($text);
      $text = new PHPWord_Section_Text($text, $styleFont, $styleParagraph);
      $this->_elementCollection[] = $text;
      return $text;
      }
    /**
    • Add a Link Element
    • @param string $linkSrc
    • @param string $linkName
    • @param mixed $style
    • @return PHPWord_Section_Link
      */
      public function addLink($linkSrc, $linkName = null, $style = null) {
      if($this->_insideOf == 'section') {
      $linkSrc = utf8_encode($linkSrc);
      if(!is_null($linkName)) {
          $linkName = utf8_encode($linkName);
      }
      
      $link = new PHPWord_Section_Link($linkSrc, $linkName, $style);
      $rID = PHPWord_Media::addSectionLinkElement($linkSrc);
      $link->setRelationId($rID);
      
      $this->_elementCollection[] = $link;
      return $link;
      } else {
      trigger_error('Unsupported Link header / footer reference');
      return false;
      }
      }
    /**
    • Add a TextBreak Element
    • @param int $count
      */
      public function addTextBreak() {
      $this->_elementCollection[] = new PHPWord_Section_TextBreak();
      }
    /**
    • Add a ListItem Element
    • @param string $text
    • @param int $depth
    • @param mixed $styleText
    • @param mixed $styleList
    • @return PHPWord_Section_ListItem
      */
      public function addListItem($text, $depth = 0, $styleText = null, $styleList = null) {
      $text = utf8_encode($text);
      $listItem = new PHPWord_Section_ListItem($text, $depth, $styleText, $styleList);
      $this->_elementCollection[] = $listItem;
      return $listItem;
      }
    /**
    • Add a Image Element
    • @param string $src
    • @param mixed $style
    • @return PHPWord_Section_Image
      */
      public function addImage($src, $style = null) {
      $image = new PHPWord_Section_Image($src, $style);

      if(!is_null($image->getSource())) {
      if($this->_insideOf == 'section') {
          $rID = PHPWord_Media::addSectionMediaElement($src, 'image');
      } elseif($this->_insideOf == 'header') {
          $rID = PHPWord_Media::addHeaderMediaElement($this->_pCount, $src);
      } elseif($this->_insideOf == 'footer') {
          $rID = PHPWord_Media::addFooterMediaElement($this->_pCount, $src);
      }
      $image->setRelationId($rID);
      
      $this->_elementCollection[] = $image;
      return $image;
      } else {
      trigger_error('Source does not exist or unsupported image type.');
      }
      }
    /**
    • Add a by PHP created Image Element
    • @param string $link
    • @param mixed $style
    • @return PHPWord_Section_MemoryImage
      */
      public function addMemoryImage($link, $style = null) {
      $memoryImage = new PHPWord_Section_MemoryImage($link, $style);
      if(!is_null($memoryImage->getSource())) {
      if($this->_insideOf == 'section') {
          $rID = PHPWord_Media::addSectionMediaElement($link, 'image', $memoryImage);
      } elseif($this->_insideOf == 'header') {
          $rID = PHPWord_Media::addHeaderMediaElement($this->_pCount, $link, $memoryImage);
      } elseif($this->_insideOf == 'footer') {
          $rID = PHPWord_Media::addFooterMediaElement($this->_pCount, $link, $memoryImage);
      }
      $memoryImage->setRelationId($rID);
      
      $this->_elementCollection[] = $memoryImage;
      return $memoryImage;
      } else {
      trigger_error('Unsupported image type.');
      }
      }
    /**
    • Add a OLE-Object Element
    • @param string $src
    • @param mixed $style
    • @return PHPWord_Section_Object
      */
      public function addObject($src, $style = null) {

      $object = new PHPWord_Section_Object($src, $style);

      if(!is_null($object->getSource())) {
      $inf = pathinfo($src);
      $ext = strtolower($inf['extension']);
      //if(strlen($ext) == 4 && strtolower(substr($ext, -1)) == 'x') {
      //  $ext = substr($ext, 0, -1);
      //}
      
      $iconSrc = PHPWORD_BASE_PATH . 'PHPWord/_staticDocParts/';
      if(!file_exists($iconSrc.'_'.$ext.'.png')) {
          $iconSrc = $iconSrc.'_default.png';
      } else {
          $iconSrc .= '_'.$ext.'.png';
      }
      
      $rIDimg = PHPWord_Media::addSectionMediaElement($iconSrc, 'image');
      $data = PHPWord_Media::addSectionMediaElement($src, $ext);
      $rID = $data[0];
      $objectId = $data[1];
      
      $object->setRelationId($rID);
      $object->setObjectId($objectId);
      $object->setImageRelationId($rIDimg);
      
      $this->_elementCollection[] = $object;
      return $object;
      } else {
      trigger_error('Source does not exist or unsupported object type.');
      }
      }
    /**
    • Add a PreserveText Element
    • @param string $text
    • @param mixed $styleFont
    • @param mixed $styleParagraph
    • @return PHPWord_Section_Footer_PreserveText
      */
      public function addPreserveText($text, $styleFont = null, $styleParagraph = null) {
      if($this->_insideOf == 'footer' || $this->_insideOf == 'header') {
      $text = utf8_encode($text);
      $ptext = new PHPWord_Section_Footer_PreserveText($text, $styleFont, $styleParagraph);
      $this->_elementCollection[] = $ptext;
      return $ptext;
      } else {
      trigger_error('addPreserveText only supported in footer/header.');
      }
      }
    /**
    • Create a new TextRun
    • @return PHPWord_Section_TextRun
      */
      public function createTextRun($styleParagraph = null) {
      $textRun = new PHPWord_Section_TextRun($styleParagraph);
      $this->_elementCollection[] = $textRun;
      return $textRun;
      }
    /**
    • Get all Elements
    • @return array
      */
      public function getElements() {
      return $this->_elementCollection;
      }
    /**
    • Get Cell Style
    • @return PHPWord_Style_Cell
      */
      public function getStyle() {
      return $this->_style;
      }
    /**
    • Get Cell width
    • @return int
      */
      public function getWidth() {
      return $this->_width;
      }
      }
      ?>
Apr 8, 2013 at 3:54 PM
File word2007.php in PHPWord/Writer directory:

<?php
/**
  • PHPWord
    *
  • Copyright (c) 2011 PHPWord
    *
  • This library is free software; you can redistribute it and/or
  • modify it under the terms of the GNU Lesser General Public
  • License as published by the Free Software Foundation; either
  • version 2.1 of the License, or (at your option) any later version.
    *
  • This library is distributed in the hope that it will be useful,
  • but WITHOUT ANY WARRANTY; without even the implied warranty of
  • MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  • Lesser General Public License for more details.
    *
  • You should have received a copy of the GNU Lesser General Public
  • License along with this library; if not, write to the Free Software
  • Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
    *
  • @category PHPWord
  • @package PHPWord
  • @copyright Copyright (c) 010 PHPWord
  • @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  • @version Beta 0.6.3, 08.07.2011
    */
class PHPWord_Writer_Word2007 implements PHPWord_Writer_IWriter {
private $_document;
private $_writerParts;
private $_diskCachingDirectory;
private $_useDiskCaching = false;
private $_imageTypes = array();
private $_objectTypes = array();

public function __construct(PHPWord $PHPWord = null) {
    $this->_document = $PHPWord;

    $this->_diskCachingDirectory = './';

    $this->_writerParts['contenttypes'] = new PHPWord_Writer_Word2007_ContentTypes();
    $this->_writerParts['rels'] = new PHPWord_Writer_Word2007_Rels();
    $this->_writerParts['docprops'] = new PHPWord_Writer_Word2007_DocProps();
    $this->_writerParts['documentrels'] = new PHPWord_Writer_Word2007_DocumentRels();
    $this->_writerParts['document'] = new PHPWord_Writer_Word2007_Document();
    $this->_writerParts['styles'] = new PHPWord_Writer_Word2007_Styles();
    $this->_writerParts['header'] = new PHPWord_Writer_Word2007_Header();
    $this->_writerParts['footer'] = new PHPWord_Writer_Word2007_Footer();

    foreach($this->_writerParts as $writer) {
        $writer->setParentWriter($this);
    }
}

public function save($pFilename = null) {
    if(!is_null($this->_document)) {

        // If $pFilename is php://output or php://stdout, make it a temporary file...
        $originalFilename = $pFilename;
        if(strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') {
            $pFilename = @tempnam('./', 'phppttmp');
            if($pFilename == '') {
                $pFilename = $originalFilename;
            }
        }

        // Create new ZIP file and open it for writing
        $objZip = new ZipArchive();

        // Try opening the ZIP file
        if($objZip->open($pFilename, ZIPARCHIVE::OVERWRITE) !== true) {
            if($objZip->open($pFilename, ZIPARCHIVE::CREATE) !== true) {
                throw new Exception("Could not open " . $pFilename . " for writing.");
            }
        }


        $sectionElements = array();
        $_secElements = PHPWord_Media::getSectionMediaElements();
        $extensions = array ();
        foreach($_secElements as $element) { // loop through section media elements
            if($element['type'] != 'hyperlink') {
                $this->_addFileToPackage($objZip, $element);
                $inf = pathinfo($element['source']);
                $ext = strtolower($inf['extension']);
                $extensions[$ext] = true;
            }
            $sectionElements[] = $element;
        }
        $extensions = array_keys ($extensions);

        $_hdrElements = PHPWord_Media::getHeaderMediaElements();
        foreach($_hdrElements as $_headerFile => $_hdrMedia) { // loop through headers
            if(count($_hdrMedia) > 0) {
                $objZip->addFromString('word/_rels/'.$_headerFile.'.xml.rels', $this->getWriterPart('documentrels')->writeHeaderFooterRels($_hdrMedia));
                foreach($_hdrMedia as $element) { // loop through header media elements
                    $this->_addFileToPackage($objZip, $element);
                }
            }
        }

        $_ftrElements = PHPWord_Media::getFooterMediaElements();
        foreach($_ftrElements as $_footerFile => $_ftrMedia) { // loop through footers
            if(count($_ftrMedia) > 0) {
                $objZip->addFromString('word/_rels/'.$_footerFile.'.xml.rels', $this->getWriterPart('documentrels')->writeHeaderFooterRels($_ftrMedia));
                foreach($_ftrMedia as $element) { // loop through footers media elements
                    $this->_addFileToPackage($objZip, $element);
                }
            }
        }



        $_cHdrs    = 0;
        $_cFtrs    = 0;
        $rID       = PHPWord_Media::countSectionMediaElements() + 6;
        $_sections = $this->_document->getSections();

        foreach($_sections as $section) {
            $_header = $section->getHeader();
            if(!is_null($_header)) {
                $_cHdrs++;
                $_header->setRelationId(++$rID);
                $_headerCount = $_header->getHeaderCount();
                $_headerFile = 'header'.$_headerCount.'.xml';
                $sectionElements[] = array('target'=>$_headerFile, 'type'=>'header', 'rID'=>$rID);
                $objZip->addFromString('word/'.$_headerFile, $this->getWriterPart('header')->writeHeader($_header));
            }

            $_footer = $section->getFooter();
            if(!is_null($_footer)) {
                $_cFtrs++;
                $_footer->setRelationId(++$rID);
                $_footerCount = $_footer->getFooterCount();
                $_footerFile = 'footer'.$_footerCount.'.xml';
                $sectionElements[] = array('target'=>$_footerFile, 'type'=>'footer', 'rID'=>$rID);
                $objZip->addFromString('word/'.$_footerFile, $this->getWriterPart('footer')->writeFooter($_footer));
            }
        }

        // build docx file
        // Write dynamic files
        // $objZip->addFromString('[Content_Types].xml', $this->getWriterPart('contenttypes')->writeContentTypes($this->_imageTypes, $this->_objectTypes, $_cHdrs, $_cFtrs));
        $objZip->addFromString('[Content_Types].xml', $this->getWriterPart('contenttypes')->writeContentTypes($this->_imageTypes, $extensions, $_cHdrs, $_cFtrs));          
        $objZip->addFromString('_rels/.rels', $this->getWriterPart('rels')->writeRelationships($this->_document));
        $objZip->addFromString('docProps/app.xml', $this->getWriterPart('docprops')->writeDocPropsApp($this->_document));
        $objZip->addFromString('docProps/core.xml', $this->getWriterPart('docprops')->writeDocPropsCore($this->_document));
        $objZip->addFromString('word/document.xml', $this->getWriterPart('document')->writeDocument($this->_document));
        $objZip->addFromString('word/_rels/document.xml.rels', $this->getWriterPart('documentrels')->writeDocumentRels($sectionElements));
        $objZip->addFromString('word/styles.xml', $this->getWriterPart('styles')->writeStyles($this->_document));

        // Write static files
        $objZip->addFile(PHPWORD_BASE_PATH . 'PHPWord/_staticDocParts/numbering.xml', 'word/numbering.xml');
        $objZip->addFile(PHPWORD_BASE_PATH . 'PHPWord/_staticDocParts/settings.xml', 'word/settings.xml');
        $objZip->addFile(PHPWORD_BASE_PATH . 'PHPWord/_staticDocParts/theme1.xml', 'word/theme/theme1.xml');
        $objZip->addFile(PHPWORD_BASE_PATH . 'PHPWord/_staticDocParts/webSettings.xml', 'word/webSettings.xml');
        $objZip->addFile(PHPWORD_BASE_PATH . 'PHPWord/_staticDocParts/fontTable.xml', 'word/fontTable.xml');


        // Close file
        if($objZip->close() === false) {
            throw new Exception("Could not close zip file $pFilename.");
        }

        // If a temporary file was used, copy it to the correct file stream
        if($originalFilename != $pFilename) {
            if (copy($pFilename, $originalFilename) === false) {
                throw new Exception("Could not copy temporary zip file $pFilename to $originalFilename.");
            }
            @unlink($pFilename);
        }
    } else {
        throw new Exception("PHPWord object unassigned.");
    }
}

private function _chkContentTypes($src) {
    $srcInfo   = pathinfo($src);
    $extension = strtolower($srcInfo['extension']);
    if(substr($extension, 0, 3) == 'php') {
        $extension = 'php';
    }
    $_supportedImageTypes = array('jpg', 'jpeg', 'gif', 'png', 'bmp', 'tif', 'tiff', 'php');

    if(in_array($extension, $_supportedImageTypes)) {
        $imagedata = getimagesize($src);
        $imagetype = image_type_to_mime_type($imagedata[2]);
        $imageext = image_type_to_extension($imagedata[2]);
        $imageext = str_replace('.', '', $imageext);
        if($imageext == 'jpeg') $imageext = 'jpg';

        if(!in_array($imagetype, $this->_imageTypes)) {
            $this->_imageTypes[$imageext] = $imagetype;
        }
    } else {
        if(!in_array($extension, $this->_objectTypes)) {
            $this->_objectTypes[] = $extension;
        }
    }
}

public function getWriterPart($pPartName = '') {
    if ($pPartName != '' && isset($this->_writerParts[strtolower($pPartName)])) {
        return $this->_writerParts[strtolower($pPartName)];
    } else {
        return null;
    }
}

public function getUseDiskCaching() {
    return $this->_useDiskCaching;
}

public function setUseDiskCaching($pValue = false, $pDirectory = null) {
    $this->_useDiskCaching = $pValue;

    if (!is_null($pDirectory)) {
        if (is_dir($pDirectory)) {
            $this->_diskCachingDirectory = $pDirectory;
        } else {
            throw new Exception("Directory does not exist: $pDirectory");
        }
    }

    return $this;
}

private function _addFileToPackage($objZip, $element) {
    if(isset($element['isMemImage']) && $element['isMemImage']) {
        $image = call_user_func($element['createfunction'], $element['source']);
        ob_start();
        call_user_func($element['imagefunction'], $image);
        $imageContents = ob_get_contents();
        ob_end_clean();
        $objZip->addFromString('word/'.$element['target'], $imageContents);
        imagedestroy($image);

        $this->_chkContentTypes($element['source']);
    } else {
        $objZip->addFile($element['source'], 'word/'.$element['target']);
        $this->_chkContentTypes($element['source']);
    }
}
}
?>
Apr 8, 2013 at 4:01 PM
File document.php in PHPWord/Writer/Word2007 directory. Here I can't post the entire file in one message because it exceeds the 10000 characters limit, so I will break it up in two parts (this and the following message).

Part 1 of document.php in PHPWord/Writer/Word2007 directory:

<?php
/**
  • PHPWord
    *
  • Copyright (c) 2011 PHPWord
    *
  • This library is free software; you can redistribute it and/or
  • modify it under the terms of the GNU Lesser General Public
  • License as published by the Free Software Foundation; either
  • version 2.1 of the License, or (at your option) any later version.
    *
  • This library is distributed in the hope that it will be useful,
  • but WITHOUT ANY WARRANTY; without even the implied warranty of
  • MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  • Lesser General Public License for more details.
    *
  • You should have received a copy of the GNU Lesser General Public
  • License along with this library; if not, write to the Free Software
  • Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
    *
  • @category PHPWord
  • @package PHPWord
  • @copyright Copyright (c) 010 PHPWord
  • @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  • @version Beta 0.6.3, 08.07.2011
    */
class PHPWord_Writer_Word2007_Document extends PHPWord_Writer_Word2007_Base {
public function writeDocument(PHPWord $pPHPWord = null) {
    // Create XML writer

    if($this->getParentWriter()->getUseDiskCaching()) {
        $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
    } else {
        $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_MEMORY);
    }

    // XML header
    $objWriter->startDocument('1.0','UTF-8','yes');

    // w:document
    $objWriter->startElement('w:document');

    $objWriter->writeAttribute('xmlns:ve', 'http://schemas.openxmlformats.org/markup-compatibility/2006');
    $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office');
    $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
    $objWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math');
    $objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml');
    $objWriter->writeAttribute('xmlns:wp', 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing');
    $objWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word');
    $objWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main');
    $objWriter->writeAttribute('xmlns:wne', 'http://schemas.microsoft.com/office/word/2006/wordml');

    $objWriter->startElement('w:body');

    $_sections = $pPHPWord->getSections();
    $countSections = count($_sections);
    $pSection = 0;

    if($countSections > 0) {
        foreach($_sections as $section) {
            $pSection++;

            $_elements = $section->getElements();

            foreach($_elements as $element) {
                if($element instanceof PHPWord_Section_Text) {
                    $this->_writeText($objWriter, $element);
                } elseif($element instanceof PHPWord_Section_TextRun) {
                    $this->_writeTextRun($objWriter, $element);
                } elseif($element instanceof PHPWord_Section_Link) {
                    $this->_writeLink($objWriter, $element);
                } elseif($element instanceof PHPWord_Section_Title) {
                    $this->_writeTitle($objWriter, $element);
                } elseif($element instanceof PHPWord_Section_TextBreak) {
                    $this->_writeTextBreak($objWriter);
                } elseif($element instanceof PHPWord_Section_PageBreak) {
                    $this->_writePageBreak($objWriter);
                } elseif($element instanceof PHPWord_Section_Table) {
                    $this->_writeTable($objWriter, $element);
                } elseif($element instanceof PHPWord_Section_ListItem) {
                    $this->_writeListItem($objWriter, $element);
                } elseif($element instanceof PHPWord_Section_Image ||
                         $element instanceof PHPWord_Section_MemoryImage) {
                    $this->_writeImage($objWriter, $element);
                } elseif($element instanceof PHPWord_Section_Object) {
                    $this->_writeObject($objWriter, $element);
                } elseif($element instanceof PHPWord_TOC) {
                    $this->_writeTOC($objWriter);
                }
            }

            if($pSection == $countSections) {
                $this->_writeEndSection($objWriter, $section);
            } else {
                $this->_writeSection($objWriter, $section);
            }
        }
    }

    $objWriter->endElement(); // End w:body
    $objWriter->endElement(); // End w:document

    // Return
    return $objWriter->getData();
}

private function _writeSection(PHPWord_Shared_XMLWriter $objWriter = null, PHPWord_Section $section) {
    $objWriter->startElement('w:p');
        $objWriter->startElement('w:pPr');
            $this->_writeEndSection($objWriter, $section, 3);
        $objWriter->endElement();
    $objWriter->endElement();
}

private function _writeEndSection(PHPWord_Shared_XMLWriter $objWriter = null, PHPWord_Section $section) {
    $_settings = $section->getSettings();
    $_header = $section->getHeader();
    $_footer = $section->getFooter();
    $pgSzW = $_settings->getPageSizeW();
    $pgSzH = $_settings->getPageSizeH();
    $orientation = $_settings->getOrientation();

    $marginTop = $_settings->getMarginTop();
    $marginLeft = $_settings->getMarginLeft();
    $marginRight = $_settings->getMarginRight();
    $marginBottom = $_settings->getMarginBottom();

    $borders = $_settings->getBorderSize();

    $objWriter->startElement('w:sectPr');

        if(!is_null($_header)) {
            $rId = $_header->getRelationId();
            $objWriter->startElement('w:headerReference');
                $objWriter->writeAttribute('w:type', 'default');
                $objWriter->writeAttribute('r:id', 'rId'.$rId);
            $objWriter->endElement();
        }

        if(!is_null($_footer)) {
            $rId = $_footer->getRelationId();
            $objWriter->startElement('w:footerReference');
                $objWriter->writeAttribute('w:type', 'default');
                $objWriter->writeAttribute('r:id', 'rId'.$rId);
            $objWriter->endElement();
        }

        $objWriter->startElement('w:pgSz');
            $objWriter->writeAttribute('w:w', $pgSzW);
            $objWriter->writeAttribute('w:h', $pgSzH);

            if(!is_null($orientation) && strtolower($orientation) != 'portrait') {
                $objWriter->writeAttribute('w:orient', $orientation);
            }

        $objWriter->endElement();

        $objWriter->startElement('w:pgMar');
            $objWriter->writeAttribute('w:top', $marginTop);
            $objWriter->writeAttribute('w:right', $marginRight);
            $objWriter->writeAttribute('w:bottom', $marginBottom);
            $objWriter->writeAttribute('w:left', $marginLeft);
            $objWriter->writeAttribute('w:header', '720');
            $objWriter->writeAttribute('w:footer', '720');
            $objWriter->writeAttribute('w:gutter', '0');
        $objWriter->endElement();


        if(!is_null($borders[0]) || !is_null($borders[1]) || !is_null($borders[2]) || !is_null($borders[3])) {
            $borderColor = $_settings->getBorderColor();

            $objWriter->startElement('w:pgBorders');
                $objWriter->writeAttribute('w:offsetFrom', 'page');

                if(!is_null($borders[0])) {
                    $objWriter->startElement('w:top');
                        $objWriter->writeAttribute('w:val', 'single');
                        $objWriter->writeAttribute('w:sz', $borders[0]);
                        $objWriter->writeAttribute('w:space', '24');
                        $objWriter->writeAttribute('w:color', $borderColor[0]);
                    $objWriter->endElement();
                }

                if(!is_null($borders[1])) {
                    $objWriter->startElement('w:left');
                        $objWriter->writeAttribute('w:val', 'single');
                        $objWriter->writeAttribute('w:sz', $borders[1]);
                        $objWriter->writeAttribute('w:space', '24');
                        $objWriter->writeAttribute('w:color', $borderColor[1]);
                    $objWriter->endElement();
                }

                if(!is_null($borders[2])) {
                    $objWriter->startElement('w:right');
                        $objWriter->writeAttribute('w:val', 'single');
                        $objWriter->writeAttribute('w:sz', $borders[2]);
                        $objWriter->writeAttribute('w:space', '24');
                        $objWriter->writeAttribute('w:color', $borderColor[2]);
                    $objWriter->endElement();
                }

                if(!is_null($borders[3])) {
                    $objWriter->startElement('w:bottom');
                        $objWriter->writeAttribute('w:val', 'single');
                        $objWriter->writeAttribute('w:sz', $borders[3]);
                        $objWriter->writeAttribute('w:space', '24');
                        $objWriter->writeAttribute('w:color', $borderColor[3]);
                    $objWriter->endElement();
                }
            $objWriter->endElement();
        }


        $objWriter->startElement('w:cols');
            $objWriter->writeAttribute('w:space', '720');
        $objWriter->endElement();


    $objWriter->endElement();
}

private function _writePageBreak(PHPWord_Shared_XMLWriter $objWriter = null) {
    $objWriter->startElement('w:p');
        $objWriter->startElement('w:r');
            $objWriter->startElement('w:br');
                $objWriter->writeAttribute('w:type', 'page');
            $objWriter->endElement();
        $objWriter->endElement();
    $objWriter->endElement();
}
Apr 8, 2013 at 4:02 PM
Part 2 of document.php in PHPWord/Writer/Word2007 directory:
private function _writeListItem(PHPWord_Shared_XMLWriter $objWriter = null, PHPWord_Section_ListItem $listItem) {
    $textObject = $listItem->getTextObject();
    $text = $textObject->getText();
    $styleParagraph = $textObject->getParagraphStyle();
    $SpIsObject = ($styleParagraph instanceof PHPWord_Style_Paragraph) ? true : false;

    $depth = $listItem->getDepth();
    $listType = $listItem->getStyle()->getListType();

    $objWriter->startElement('w:p');
        $objWriter->startElement('w:pPr');

            if($SpIsObject) {
                $this->_writeParagraphStyle($objWriter, $styleParagraph, true);
            } elseif(!$SpIsObject && !is_null($styleParagraph)) {
                $objWriter->startElement('w:pStyle');
                    $objWriter->writeAttribute('w:val', $styleParagraph);
                $objWriter->endElement();
            }

            $objWriter->startElement('w:numPr');

                $objWriter->startElement('w:ilvl');
                    $objWriter->writeAttribute('w:val', $depth);
                $objWriter->endElement();

                $objWriter->startElement('w:numId');
                    $objWriter->writeAttribute('w:val', $listType);
                $objWriter->endElement();

            $objWriter->endElement();
        $objWriter->endElement();

        $this->_writeText($objWriter, $textObject, true);

    $objWriter->endElement();
}

protected function _writeObject(PHPWord_Shared_XMLWriter $objWriter = null, PHPWord_Section_Object $object) {
    $rIdObject = $object->getRelationId();
    $rIdImage = $object->getImageRelationId();
    $shapeId = md5($rIdObject.'_'.$rIdImage);

    $objectId = $object->getObjectId();

    $style = $object->getStyle();
    $width = $style->getWidth();
    $height = $style->getHeight();
    $align = $style->getAlign();

    $progid = array ('xls' => 'Excel.Sheet.8', 'xlsx' => 'Excel.Sheet.12', 'doc' => 'Word.Document.8', 'docx' => 'Word.Document.12', 'ppt' => 'PowerPoint.Show.8', 'pptx' => 'PowerPoint.Show.12');
    $src = $object->getSource();
    $inf = pathinfo($src);
    $ext = strtolower($inf['extension']); 

    $objWriter->startElement('w:p');

        if(!is_null($align)) {
            $objWriter->startElement('w:pPr');
                $objWriter->startElement('w:jc');
                    $objWriter->writeAttribute('w:val', $align);
                $objWriter->endElement();
            $objWriter->endElement();
        }

        $objWriter->startElement('w:r');

            $objWriter->startElement('w:object');
            $objWriter->writeAttribute('w:dxaOrig', '249');
            $objWriter->writeAttribute('w:dyaOrig', '160');

                $objWriter->startElement('v:shape');
                $objWriter->writeAttribute('id', $shapeId);
                $objWriter->writeAttribute('type', '#_x0000_t75');
                $objWriter->writeAttribute('style', 'width:104px;height:67px');
                $objWriter->writeAttribute('o:ole', '');

                    $objWriter->startElement('v:imagedata');
                    $objWriter->writeAttribute('r:id', 'rId'.$rIdImage);
                    $objWriter->writeAttribute('o:title', '');
                    $objWriter->endElement();

                $objWriter->endElement();

                $objWriter->startElement('o:OLEObject');
                $objWriter->writeAttribute('Type', 'Embed');
                // $objWriter->writeAttribute('ProgID', 'Package');
                $objWriter->writeAttribute('ProgID', $progid[$ext]);
                $objWriter->writeAttribute('ShapeID', $shapeId);
                $objWriter->writeAttribute('DrawAspect', 'Icon');
                $objWriter->writeAttribute('ObjectID', '_'.$objectId);
                $objWriter->writeAttribute('r:id', 'rId'.$rIdObject);
                $objWriter->endElement();

            $objWriter->endElement();

        $objWriter->endElement(); // w:r

    $objWriter->endElement(); // w:p
}

private function _writeTOC(PHPWord_Shared_XMLWriter $objWriter = null) {
    $titles = PHPWord_TOC::getTitles();
    $styleFont = PHPWord_TOC::getStyleFont();

    $styleTOC = PHPWord_TOC::getStyleTOC();
    $fIndent = $styleTOC->getIndent();
    $tabLeader = $styleTOC->getTabLeader();
    $tabPos = $styleTOC->getTabPos();

    $isObject = ($styleFont instanceof PHPWord_Style_Font) ? true : false;

    for($i=0; $i<count($titles); $i++) {
        $title = $titles[$i];
        $indent = ($title['depth'] - 1) * $fIndent;

        $objWriter->startElement('w:p');

            $objWriter->startElement('w:pPr');

                if($isObject && !is_null($styleFont->getParagraphStyle())) {
                    $this->_writeParagraphStyle($objWriter, $styleFont->getParagraphStyle());
                }

                if($indent > 0) {
                    $objWriter->startElement('w:ind');
                        $objWriter->writeAttribute('w:left', $indent);
                    $objWriter->endElement();
                }

                if(!empty($styleFont) && !$isObject) {
                    $objWriter->startElement('w:pPr');
                        $objWriter->startElement('w:pStyle');
                            $objWriter->writeAttribute('w:val', $styleFont);
                        $objWriter->endElement();
                    $objWriter->endElement();
                }

                $objWriter->startElement('w:tabs');
                    $objWriter->startElement('w:tab');
                        $objWriter->writeAttribute('w:val', 'right');
                        if(!empty($tabLeader)) {
                            $objWriter->writeAttribute('w:leader', $tabLeader);
                        }
                        $objWriter->writeAttribute('w:pos', $tabPos);
                    $objWriter->endElement();
                $objWriter->endElement();

            $objWriter->endElement(); // w:pPr


            if($i == 0) {
                $objWriter->startElement('w:r');
                    $objWriter->startElement('w:fldChar');
                        $objWriter->writeAttribute('w:fldCharType', 'begin');
                    $objWriter->endElement();
                $objWriter->endElement();

                $objWriter->startElement('w:r');
                    $objWriter->startElement('w:instrText');
                        $objWriter->writeAttribute('xml:space', 'preserve');
                        $objWriter->writeRaw('TOC \o "1-9" \h \z \u');
                    $objWriter->endElement();
                $objWriter->endElement();

                $objWriter->startElement('w:r');
                    $objWriter->startElement('w:fldChar');
                        $objWriter->writeAttribute('w:fldCharType', 'separate');
                    $objWriter->endElement();
                $objWriter->endElement();
            }

            $objWriter->startElement('w:hyperlink');
                $objWriter->writeAttribute('w:anchor', $title['anchor']);
                $objWriter->writeAttribute('w:history', '1');

                $objWriter->startElement('w:r');

                    if($isObject) {
                        $this->_writeTextStyle($objWriter, $styleFont);
                    }

                    $objWriter->startElement('w:t');
                        $objWriter->writeRaw($title['text']);
                    $objWriter->endElement();
                $objWriter->endElement();

                $objWriter->startElement('w:r');
                    $objWriter->writeElement('w:tab', null);
                $objWriter->endElement();

                $objWriter->startElement('w:r');
                    $objWriter->startElement('w:fldChar');
                        $objWriter->writeAttribute('w:fldCharType', 'begin');
                    $objWriter->endElement();
                $objWriter->endElement();

                $objWriter->startElement('w:r');
                    $objWriter->startElement('w:instrText');
                        $objWriter->writeAttribute('xml:space', 'preserve');
                        $objWriter->writeRaw('PAGEREF '.$title['anchor'].' \h');
                    $objWriter->endElement();
                $objWriter->endElement();

                $objWriter->startElement('w:r');
                    $objWriter->startElement('w:fldChar');
                        $objWriter->writeAttribute('w:fldCharType', 'end');
                    $objWriter->endElement();
                $objWriter->endElement();

            $objWriter->endElement(); // w:hyperlink

        $objWriter->endElement(); // w:p
    }

    $objWriter->startElement('w:p');
        $objWriter->startElement('w:r');
            $objWriter->startElement('w:fldChar');
                $objWriter->writeAttribute('w:fldCharType', 'end');
            $objWriter->endElement();
        $objWriter->endElement();
    $objWriter->endElement();
}
}
Apr 8, 2013 at 4:03 PM
File DocumentRels.php in PHPWord/Writer/Word2007 directory:

<?php
/**
  • PHPWord
    *
  • Copyright (c) 2011 PHPWord
    *
  • This library is free software; you can redistribute it and/or
  • modify it under the terms of the GNU Lesser General Public
  • License as published by the Free Software Foundation; either
  • version 2.1 of the License, or (at your option) any later version.
    *
  • This library is distributed in the hope that it will be useful,
  • but WITHOUT ANY WARRANTY; without even the implied warranty of
  • MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  • Lesser General Public License for more details.
    *
  • You should have received a copy of the GNU Lesser General Public
  • License along with this library; if not, write to the Free Software
  • Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
    *
  • @category PHPWord
  • @package PHPWord
  • @copyright Copyright (c) 010 PHPWord
  • @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  • @version Beta 0.6.3, 08.07.2011
    */
class PHPWord_Writer_Word2007_DocumentRels extends PHPWord_Writer_Word2007_WriterPart {
public function writeDocumentRels($_relsCollection) {
    // Create XML writer
    $objWriter = null;
    if ($this->getParentWriter()->getUseDiskCaching()) {
        $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
    } else {
        $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_MEMORY);
    }

    // XML header
    $objWriter->startDocument('1.0','UTF-8','yes');

    // Relationships
    $objWriter->startElement('Relationships');
    $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');

        // Relationship word/document.xml
        $this->_writeRelationship(
            $objWriter,
            1,
            'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles',
            'styles.xml'
        );

        // Relationship word/numbering.xml
        $this->_writeRelationship(
            $objWriter,
            2,
            'http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering',
            'numbering.xml'
        );

        // Relationship word/settings.xml
        $this->_writeRelationship(
            $objWriter,
            3,
            'http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings',
            'settings.xml'
        );

        // Relationship word/settings.xml
        $this->_writeRelationship(
            $objWriter,
            4,
            'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme',
            'theme/theme1.xml'
        );

        // Relationship word/settings.xml
        $this->_writeRelationship(
            $objWriter,
            5,
            'http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings',
            'webSettings.xml'
        );

        // Relationship word/settings.xml
        $this->_writeRelationship(
            $objWriter,
            6,
            'http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable',
            'fontTable.xml'
        );

        // Relationships to Images / Embeddings / Headers / Footers
        foreach($_relsCollection as $relation) {
            $relationType = $relation['type'];
            $relationName = $relation['target'];
            $relationId = $relation['rID'];
            $targetMode = ($relationType == 'hyperlink') ? 'External' : '';
            if (in_array ($relationType, array ('xlsx', 'docx', 'pptx'))) $relationType = 'package';
            elseif (in_array ($relationType, array ('xls', 'doc', 'ppt'))) $relationType = 'oleObject';

            $this->_writeRelationship(
                $objWriter,
                $relationId,
                'http://schemas.openxmlformats.org/officeDocument/2006/relationships/'.$relationType,
                $relationName,
                $targetMode
            );
        }


    $objWriter->endElement();

    // Return
    return $objWriter->getData();
}

public function writeHeaderFooterRels($_relsCollection) {
    // Create XML writer
    $objWriter = null;
    if ($this->getParentWriter()->getUseDiskCaching()) {
        $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
    } else {
        $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_MEMORY);
    }

    // XML header
    $objWriter->startDocument('1.0','UTF-8','yes');

    // Relationships
    $objWriter->startElement('Relationships');
    $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships');

        // Relationships to Images / Embeddings / Headers / Footers
        foreach($_relsCollection as $relation) {
            $relationType = $relation['type'];
            $relationName = $relation['target'];
            $relationId = $relation['rID'];

            $this->_writeRelationship(
                $objWriter,
                $relationId,
                'http://schemas.openxmlformats.org/officeDocument/2006/relationships/'.$relationType,
                $relationName
            );
        }


    $objWriter->endElement();

    // Return
    return $objWriter->getData();
}

private function _writeRelationship(PHPWord_Shared_XMLWriter $objWriter = null, $pId = 1, $pType = '', $pTarget = '', $pTargetMode = '') {
    if($pType != '' && $pTarget != '') {
        if(strpos($pId, 'rId') === false) {
            $pId = 'rId' . $pId;
        }

        // Write relationship
        $objWriter->startElement('Relationship');
        $objWriter->writeAttribute('Id', $pId);
        $objWriter->writeAttribute('Type', $pType);
        $objWriter->writeAttribute('Target', $pTarget);

        if($pTargetMode != '') {
            $objWriter->writeAttribute('TargetMode', $pTargetMode);
        }

        $objWriter->endElement();
    } else {
        throw new Exception("Invalid parameters passed.");
    }
}
}
?>
Apr 8, 2013 at 4:04 PM
File ContentTypes.php in PHPWord/Writer/Word2007 directory:

<?php
/**
  • PHPWord
    *
  • Copyright (c) 2011 PHPWord
    *
  • This library is free software; you can redistribute it and/or
  • modify it under the terms of the GNU Lesser General Public
  • License as published by the Free Software Foundation; either
  • version 2.1 of the License, or (at your option) any later version.
    *
  • This library is distributed in the hope that it will be useful,
  • but WITHOUT ANY WARRANTY; without even the implied warranty of
  • MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  • Lesser General Public License for more details.
    *
  • You should have received a copy of the GNU Lesser General Public
  • License along with this library; if not, write to the Free Software
  • Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
    *
  • @category PHPWord
  • @package PHPWord
  • @copyright Copyright (c) 010 PHPWord
  • @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  • @version Beta 0.6.3, 08.07.2011
    */
class PHPWord_Writer_Word2007_ContentTypes extends PHPWord_Writer_Word2007_WriterPart {
public function writeContentTypes($_imageTypes, $_objectTypes, $_cHdrs, $_cFtrs) {
    // Create XML writer
    $objWriter = null;
    if ($this->getParentWriter()->getUseDiskCaching()) {
        $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory());
    } else {
        $objWriter = new PHPWord_Shared_XMLWriter(PHPWord_Shared_XMLWriter::STORAGE_MEMORY);
    }

    // XML header
    $objWriter->startDocument('1.0', 'UTF-8', 'yes');

    $cont_type = array ('xls' => 'application/vnd.ms-excel', 
                        'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 
                        'ppt' => 'application/vnd.ms-powerpoint', 
                        'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 
                        'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 
                        'doc' => 'application/msword');

    // Types
    $objWriter->startElement('Types');
    $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/content-types');

        // Rels
        $this->_writeDefaultContentType(
            $objWriter, 'rels', 'application/vnd.openxmlformats-package.relationships+xml'
        );

        // XML
        $this->_writeDefaultContentType(
            $objWriter, 'xml', 'application/xml'
        );

        // Add media content-types
        foreach($_imageTypes as $key => $value) {
            $this->_writeDefaultContentType($objWriter, $key, $value);
        }

        // Add embedding content-types
        // if(count($_objectTypes) > 0) {
        foreach ($_objectTypes as $obj) {
            if (isset($cont_type[$obj])) $this->_writeDefaultContentType($objWriter, $obj, $cont_type[$obj]);
            // $this->_writeDefaultContentType($objWriter, 'bin', 'application/vnd.openxmlformats-officedocument.oleObject');
        }

        // DocProps
        $this->_writeOverrideContentType(
            $objWriter, '/docProps/app.xml', 'application/vnd.openxmlformats-officedocument.extended-properties+xml'
        );

        $this->_writeOverrideContentType(
            $objWriter, '/docProps/core.xml', 'application/vnd.openxmlformats-package.core-properties+xml'
        );

        // Document
        $this->_writeOverrideContentType(
            $objWriter, '/word/document.xml', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml'
        );

        // Styles
        $this->_writeOverrideContentType(
            $objWriter, '/word/styles.xml', 'application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml'
        );

        // Numbering
        $this->_writeOverrideContentType(
            $objWriter, '/word/numbering.xml', 'application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml'
        );

        // Settings
        $this->_writeOverrideContentType(
            $objWriter, '/word/settings.xml', 'application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml'
        );

        // Theme1
        $this->_writeOverrideContentType(
            $objWriter, '/word/theme/theme1.xml', 'application/vnd.openxmlformats-officedocument.theme+xml'
        );

        // WebSettings
        $this->_writeOverrideContentType(
            $objWriter, '/word/webSettings.xml', 'application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml'
        );

        // Font Table
        $this->_writeOverrideContentType(
            $objWriter, '/word/fontTable.xml', 'application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml'
        );

        for($i=1; $i<=$_cHdrs; $i++) {
            $this->_writeOverrideContentType(
                $objWriter, '/word/header'.$i.'.xml', 'application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml'
            );
        }

        for($i=1; $i<=$_cFtrs; $i++) {
            $this->_writeOverrideContentType(
                $objWriter, '/word/footer'.$i.'.xml', 'application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml'
            );
        }


    $objWriter->endElement();

    // Return
    return $objWriter->getData();
}

/**
 * Get image mime type
 *
 * @param   string  $pFile  Filename
 * @return  string  Mime Type
 * @throws  Exception
 */
private function _getImageMimeType($pFile = '') {
    if(PHPWord_Shared_File::file_exists($pFile)) {
        $image = getimagesize($pFile);
        return image_type_to_mime_type($image[2]);
    } else {
        throw new Exception("File $pFile does not exist");
    }
}

/**
 * Write Default content type
 *
 * @param   PHPWord_Shared_XMLWriter    $objWriter      XML Writer
 * @param   string                      $pPartname      Part name
 * @param   string                      $pContentType   Content type
 * @throws  Exception
 */
private function _writeDefaultContentType(PHPWord_Shared_XMLWriter $objWriter = null, $pPartname = '', $pContentType = '') {
    if($pPartname != '' && $pContentType != '') {
        // Write content type
        $objWriter->startElement('Default');
        $objWriter->writeAttribute('Extension',     $pPartname);
        $objWriter->writeAttribute('ContentType',   $pContentType);
        $objWriter->endElement();
    } else {
        throw new Exception("Invalid parameters passed.");
    }
}

/**
 * Write Override content type
 *
 * @param   PHPPowerPoint_Shared_XMLWriter  $objWriter      XML Writer
 * @param   string                      $pPartname      Part name
 * @param   string                      $pContentType   Content type
 * @throws  Exception
 */
private function _writeOverrideContentType(PHPWord_Shared_XMLWriter $objWriter = null, $pPartname = '', $pContentType = '') {
    if($pPartname != '' && $pContentType != '') {
        // Write content type
        $objWriter->startElement('Override');
        $objWriter->writeAttribute('PartName',      $pPartname);
        $objWriter->writeAttribute('ContentType',   $pContentType);
        $objWriter->endElement();
    } else {
        throw new Exception("Invalid parameters passed.");
    }
}
}