Quantcast
Channel: PHPWord
Viewing all 450 articles
Browse latest View live

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

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

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

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

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

$
0
0
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.");
    }
}
}
?>

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

$
0
0
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.");
    }
}
}

New Post: FIXED: Table Height Problems

$
0
0
Hi all! I have modified a couple files to fully handle the configuration of tables and their row heights. All I added to the addRow() function was an additional parameter that indicated the hRule to be used in the document.xml file of the Word docx. Here is a before and after of the PHP usage.
Before:
$table->addRow(100);
After:
$table->addRow(100,"exact");
$table->addRow(100,null);
Using "exact" makes the row height adhere to the value. Using a null value will provide the current default behavior of giving you the "At least" property in Word. To glue all of this together, I modified the Table.php and Base.php scripts. This was added to the top of Table.php just behind the $_rowHeights = array(); statement:
    /**
     * Row height rule
     *
     * @var array
     */
    private $_rowHeightRules = array();
The addRow function was updated to be this:
    /**
    * Add a row
    *
    * @param int $height
    * @param string $hRule
    */
    public function addRow($height = null,$hRule) {
        $this->_rows[] = array();
        $this->_rowHeights[] = $height;
        $this->_rowHeightRules[] = $hRule;
    }
This was added near the bottom of Table.php just behind the getRowHeights() function:
    /**
     * Get all row height rules
     *
     * @return array
     */
    public function getRowHeightRules() {
            return $this->_rowHeightRules;
    }
And I modified the function in Base.php to handle the additional instructions:
protected function _writeTable(PHPWord_Shared_XMLWriter $objWriter = null, PHPWord_Section_Table $table) {
        $_rows = $table->getRows();
        $_cRows = count($_rows);
        
        if($_cRows > 0) {
            $objWriter->startElement('w:tbl');
                $tblStyle = $table->getStyle();
                if($tblStyle instanceof PHPWord_Style_Table) {
                    $this->_writeTableStyle($objWriter, $tblStyle);
                } else {
                    if(!empty($tblStyle)) {
                        $objWriter->startElement('w:tblPr');
                            $objWriter->startElement('w:tblStyle');
                                $objWriter->writeAttribute('w:val', $tblStyle);
                            $objWriter->endElement();
                        $objWriter->endElement();
                    }
                }

                $_heights = $table->getRowHeights();
                $_height_rule = $table->getRowHeightRules();
                for($i=0; $i<$_cRows; $i++) {
                    $row = $_rows[$i];
                    $height = $_heights[$i];
                    $rule = $_height_rule[$i];
                    
                    $objWriter->startElement('w:tr');
                    
                        if(!is_null($height)) {
                            $objWriter->startElement('w:trPr');
                                $objWriter->startElement('w:trHeight');
                                    if(!is_null($rule)) {
                                        $objWriter->startAttribute('w:hRule');
                                            $objWriter->text($rule);
                                        $objWriter->endAttribute();
                                    }
                                    $objWriter->startAttribute('w:val');
                                        $objWriter->text($height);
                                    $objWriter->endAttribute();
                                $objWriter->endElement();
                            $objWriter->endElement();
                        }
                        
                        foreach($row as $cell) {
                            $objWriter->startElement('w:tc');
                                
                                $cellStyle = $cell->getStyle();
                                $width = $cell->getWidth();
                                
                                $objWriter->startElement('w:tcPr');
                                    $objWriter->startElement('w:tcW');
                                        $objWriter->writeAttribute('w:w', $width);
                                        $objWriter->writeAttribute('w:type', 'dxa');
                                    $objWriter->endElement();
                                    
                                    if($cellStyle instanceof PHPWord_Style_Cell) {
                                        $this->_writeCellStyle($objWriter, $cellStyle);
                                    }
                                    
                                $objWriter->endElement();
                                
                                $_elements = $cell->getElements();
                                if(count($_elements) > 0) {
                                    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_TextBreak) {
                                            $this->_writeTextBreak($objWriter);
                                        } 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_Section_Footer_PreserveText) {
                                            $this->_writePreserveText($objWriter, $element);
                                        }
                                    }
                                } else {
                                    $this->_writeTextBreak($objWriter);
                                }
                                
                            $objWriter->endElement();
                        }
                    $objWriter->endElement();
                }
            $objWriter->endElement();
        }
    }
This all works well in my own usage and testing. Anyone needing a diff/patch/script should reply. Thanks!

Adam

New Post: FIXED: Table Height Problems

$
0
0
Thanks a lot it will be usefull for my project ;)!

New Post: Internal links

$
0
0
Hello,

I'm writing a tool in PHP to create a documentation with the help of PHPWord. But I can't figure out how to link inside the word document. I know that it is possible and PHPWord seems to be able to create external links. But how can create an internal link?

Best regards,
TrustSeg

New Post: Internal links

$
0
0
Ok, it seems that I can set bookmarks with addTitle() and get the (automatically generated?) name with getAnchor(). In a natively generated word document (saved directly with Word) the <w:hyperlink> nodes contain the attribute "w:anchor" which stores the name of the bookmark node. But I found no way to set this attribute through PHPWord. I tried to create a link with:

$section->addLink("_Toc252634155", "Title 3");

.. but this didn't work. PHPWord stores the target somewhere else but not in the file word\document.xml in the "w:anchor" attribute. Does anyone have an idea? Please help.

New Post: FIXED: Table Height Problems

$
0
0
I'm happy to troubleshoot if you can give examples. Ideally, you'd be able to pass along a ZIP of your library, a dataset, and your script.

New Post: FIXED: Table Height Problems

$
0
0
Hi Aburgett, would you be able to attach - or paste - a patch file for the changes?

New Post: FIXED: Table Height Problems

$
0
0
Sure thing, as soon as I return to the office tomorrow (EST). I have also updated the code base to allow column spanning in tables in Word, but that will be a new thread.

New Post: FIXED: Table Height Problems

New Post: FIXED: Table Height Problems

Commented Issue: Advanced string replace in setValue [49]

$
0
0
When started using Phpword it saved me a lot of time as i needed to replace a template in docx using php. I had a minor issue when started using the setValue method. I found that using Word, the program creates some tags that the str_replace couldn't detect.

I cracked a little bit the function, using some regular expressions in order to:
1. Find the regular expressions commencing with '${' and ending with '}' (in my case i dropped the $ sign cause i needed to use the $ sign in my word file)
2. With only that string, find and eliminate all the opening tags
3. find and eliminate the closing tags in that string
4. replace the old string (with garbage code) with the cleaned string
5. output the _documentXML

this is the piece of code I implemented if anyone is interested

Btw, great job with this tool it saved me a lot of time!

public function setValue($search, $replace) {
$pattern = '|\{([^\}]+)\}|U'; //if you need the $, use: '|\$\{([^\}]+)\}|U''
preg_match_all($pattern, $this->_documentXML, $matches);
$openedTagPattern= '/<[^>]+>/';
$closedTagPattern= '/<\/[^>]+>/';
foreach ($matches[0] as $value) {
$modificado = preg_replace($openedTagPattern, '', $value);
$modificado = preg_replace($closedTagPattern, '', $modificado);
$this->_documentXML = str_replace($value, $modificado, $this->_documentXML);
}

if(substr($search, 0, 1) !== '{' && substr($search, -1) !== '}') { //change to: substr($search, 0, 2) !== '${' if you need the $ character
$search = '{'.$search.'}'; //change to '${'.$search.'}' if $ needed
}

if(!is_array($replace)) {
$replace = utf8_encode($replace);
}

$this->_documentXML = str_replace($search, $replace, $this->_documentXML);
}
Comments: Thanks a lot . I wondering what is happens on the templates i have created. Word copied from demo template works , but word typed not works. I wondering about this and almost mad in those things. But here is the answer. Here is the answer. Thanks a lot....

Commented Issue: implementation of table - colspan [48]

$
0
0
It would be a huge improvement to be able to create cells that combine different collumns into 1.
Comments: I have added this feature along with the ability to set the rowheight to be "exact". Attached is a diff that includes both updates. The colspan functionality is included in the addCell method and the rowheight functionality is in the addRow method as below: Before: ``` $table->addRow(220); $cell = $table->addCell(1250)->addText('10410043',$cell_font_style); ``` After (same output as above): ``` $table->addRow(220,null); $cell = $table->addCell(1250,1)->addText('10425333',$cell_font_style); ``` After (displaying new output): ``` $table->addRow(220,"exact"); $cell = $table->addCell(5000,3)->addText('10425333',$cell_font_style); ```

New Post: FIXED: Table Height Problems

Commented Issue: How to bring value from webpage/html to PHP word code? [50]

$
0
0
I'm having a problem here which I don't know how to bring data that pass by url and send to PHPWord, so that the passed value can be use as data in my PHPWord..
My system will be accessed by lots of user, and I want to bring the current student info after I click "generate letter" that locate bottom of the queue list for each person..
The data that I want from webpage is :

fullname,
student_id,
ic_number,
course,

After clicking the "Generate Letter", the PHPWord will print the data according to the selected student in the list :

(example)
student name = Ezwan Abid
student_id = 05-201005-00018
ic_number = 12-121212-1212
course = IT - Software

and all those data above ( from the 'queue' list html page ) will bring the data to PHPWord and be printed.
Hope someone can help me ASAP. :)
I already upload the file that contain the code :


Comments: This is a basic PHP question and not an issue with PHPWord at all. Are you familiar with POST and GET functionality?

Commented Issue: AddRow method is not taking height less then to min height [36]

$
0
0
I am not able to set the height of a row in less then to min height, it always taking that min height.
Comments: This solution does not seem to be accurate (as "w:tcW" is the wrong element for this property of the document. Please see: [https://phpword.codeplex.com/workitem/48](https://phpword.codeplex.com/workitem/48) for a proper solution including another valuable addition.

New Post: delete number in front of ${Value1} in the template.

$
0
0
Hi all,

I have a bunch of data with numbering list in front of them in the word template.

For some of them is not a must when the file is being crated. I have the ${Value}... replaced to "". But with those number in front of them without any info following that looks ugly.

Is there a way to delete those unnecessary numbering lists when I don't use them?

Thanks

New Post: about phpword work in linux

$
0
0
Next code work in windows is ok !
but when I put it on the linux ,then tips me error 500,
when I notes $objWriter->save($filename);,there is no error ,but no data output,
Thankyou very much to give me an answer !!
(there is no change in dir PHPWord)
<?php
include './source/PHPWord.php';
$PHPWord = new PHPWord();
$section = $PHPWord->createSection();
$top_txt = iconv('utf-8','gbk','report output time:'.date('Y-m-d H:i:s'));
$section->addText($top_txt);    

// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$filename = 'T.docx';
header ( 'Content-Description: File Transfer' );
header("Content-type: application/vnd.ms-word");
header("Content-Disposition:attachment;filename=$filename");
header("Pragma: no-cache");
$objWriter->save($filename);
?>
Viewing all 450 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>