diff --git a/.gitignore b/.gitignore index 9fbc69f9..e5deb643 100644 --- a/.gitignore +++ b/.gitignore @@ -14,5 +14,6 @@ vendor /samples/resources /samples/results /.settings +phpword.ini /.buildpath /.project \ No newline at end of file diff --git a/.scrutinizer.yml b/.scrutinizer.yml new file mode 100644 index 00000000..6f982d8e --- /dev/null +++ b/.scrutinizer.yml @@ -0,0 +1,24 @@ +filter: + excluded_paths: [ 'vendor/*', 'tests/*', 'samples/*', 'src/PhpWord/Shared/PCLZip/*' ] + +before_commands: + - "composer install --prefer-source --dev" + +tools: + php_code_sniffer: + enabled: true + config: + standard: PSR2 + php_mess_detector: + enabled: true + config: + ruleset: phpmd.xml.dist + external_code_coverage: + enabled: true + timeout: 900 + php_cpd: true + # php_sim: # Temporarily disabled to allow focus on things other than duplicates + # min_mass: 40 + php_pdepend: true + php_analyzer: true + sensiolabs_security_checker: true diff --git a/.travis.yml b/.travis.yml index f322426d..d92e23b8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,49 +1,49 @@ language: php php: - - 5.3.3 - - 5.3 - - 5.4 - - 5.5 - - 5.6 - - hhvm + - 5.3.3 + - 5.3 + - 5.4 + - 5.5 + - 5.6 + - hhvm matrix: - allow_failures: - - php: 5.3.3 - - php: 5.6 - - php: hhvm + allow_failures: + - php: hhvm + +env: + global: + - secure: "Sq+6bVtnPsu0mWX8DWQ+9bGAjxMcGorksUiHc4YIXEJsuDfVmVlH8tTD547IeCjDAx9MxXerZ2Z4HSjxTB70VEnJPvZMHI/EZn4Ny31YLHEthdZbV5Gd1h0TGp8VOzPKGShvGrtGBX6MvMfgpK4zuieVWbSfdKeecm8ZNLMpUd4=" before_script: - ## Composer - # - curl -s http://getcomposer.org/installer | php - # - php composer.phar install --prefer-source - - composer install --prefer-source - - composer selfupdate --quiet - ## PHP_CodeSniffer - - pyrus install pear/PHP_CodeSniffer - - phpenv rehash - ## PHP Copy/Paste Detector - #- curl -o phpcpd.phar https://phar.phpunit.de/phpcpd.phar - ## PHP Mess Detector - #- pear config-set preferred_state beta - #- printf "\n" | pecl install imagick - #- pear channel-discover pear.phpmd.org - #- pear channel-discover pear.pdepend.org - #- pear install --alldeps phpmd/PHP_PMD - #- phpenv rehash - ## PHPLOC - #- curl -o phploc.phar https://phar.phpunit.de/phploc.phar + ## Packages + - sudo apt-get -qq update > /dev/null + - sudo apt-get -qq install graphviz > /dev/null + ## Composer + - composer self-update + - composer install --prefer-source --dev + ## PHPDocumentor + - mkdir -p build/docs + - mkdir -p build/coverage script: - ## PHP_CodeSniffer - - phpcs --standard=PSR2 -n src/ --ignore=src/PhpWord/Shared/PCLZip - - phpcs --standard=PSR2 -n tests/ - ## PHP Copy/Paste Detector - #- php phpcpd.phar --verbose src/ - ## PHP Mess Detector - #- phpmd src/ text unusedcode,naming,design - ## PHPLOC - #- php phploc.phar src/ - ## PHPUnit - - phpunit -c ./ --coverage-text + ## PHP_CodeSniffer + - ./vendor/bin/phpcs src/ tests/ --standard=PSR2 -n --ignore=src/PhpWord/Shared/PCLZip + ## PHP Copy/Paste Detector + - ./vendor/bin/phpcpd src/ tests/ --verbose + ## PHP Mess Detector + - ./vendor/bin/phpmd src/,tests/ text ./phpmd.xml.dist --exclude pclzip.lib.php + ## PHPUnit + - ./vendor/bin/phpunit -c ./ --coverage-text --coverage-html ./build/coverage + ## PHPLOC + - ./vendor/bin/phploc src/ + ## PHPDocumentor + - ./vendor/bin/phpdoc -q -d ./src -t ./build/docs --ignore "*/src/PhpWord/Shared/*/*" --template="responsive-twig" + +after_script: + ## PHPDocumentor + - bash .travis_shell_after_success.sh + ## Scrutinizer + - wget https://scrutinizer-ci.com/ocular.phar + - php ocular.phar code-coverage:upload --format=php-clover build/logs/clover.xml diff --git a/.travis_shell_after_success.sh b/.travis_shell_after_success.sh new file mode 100644 index 00000000..35c7a338 --- /dev/null +++ b/.travis_shell_after_success.sh @@ -0,0 +1,39 @@ +#!/bin/bash + +echo "--DEBUG--" +echo "TRAVIS_REPO_SLUG: $TRAVIS_REPO_SLUG" +echo "TRAVIS_PHP_VERSION: $TRAVIS_PHP_VERSION" +echo "TRAVIS_PULL_REQUEST: $TRAVIS_PULL_REQUEST" + +if [ "$TRAVIS_REPO_SLUG" == "PHPOffice/PHPWord" ] && [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$TRAVIS_PHP_VERSION" == "5.5" ]; then + + echo -e "Publishing PHPDoc...\n" + + cp -R build/docs $HOME/docs-latest + cp -R build/coverage $HOME/coverage-latest + + cd $HOME + git config --global user.email "travis@travis-ci.org" + git config --global user.name "travis-ci" + git clone --quiet --branch=gh-pages https://${GH_TOKEN}@github.com/PHPOffice/PHPWord gh-pages > /dev/null + + cd gh-pages + echo "--DEBUG : Suppression" + git rm -rf ./docs/$TRAVIS_BRANCH + + echo "--DEBUG : Dossier" + mkdir -p docs/$TRAVIS_BRANCH + mkdir -p coverage/$TRAVIS_BRANCH + + echo "--DEBUG : Copie" + cp -Rf $HOME/docs-latest/* ./docs/$TRAVIS_BRANCH/ + cp -Rf $HOME/coverage-latest/* ./coverage/$TRAVIS_BRANCH/ + + echo "--DEBUG : Git" + git add -f . + git commit -m "PHPDocumentor (Travis Build: $TRAVIS_BUILD_NUMBER - Branch: $TRAVIS_BRANCH)" + git push -fq origin gh-pages > /dev/null + + echo -e "Published PHPDoc to gh-pages.\n" + +fi diff --git a/CHANGELOG.md b/CHANGELOG.md old mode 100755 new mode 100644 index 6a932eda..6040c46e --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,9 +2,136 @@ This is the changelog between releases of PHPWord. Releases are listed in reverse chronological order with the latest version listed on top, while additions/changes in each release are listed in chronological order. Changes in each release are divided into three parts: added or change features, bugfixes, and miscellaneous improvements. Each line contains short information about the change made, the person who made it, and the related issue number(s) in GitHub. -## 0.10.0 - Not yet released +## 0.12.0 - Not yet released -This release marked heavy refactorings on internal code structure with the creation of some abstract classes to reduce code duplication. `Element` subnamespace is introduced in this release to replace `Section`. Word2007 reader capability is greatly enhanced. Endnote is introduced. List numbering is now customizable. +This release added form fields (textinput, checkbox, and dropdown), drawing shapes (arc, curve, line, polyline, rect, oval), and basic 2D chart (pie, doughnut, bar, line, area, scatter, radar) elements along with some new styles. + +### Features + +- Element: Ability to add drawing shapes (arc, curve, line, polyline, rect, oval) using new `Shape` element - @ivanlanin GH-123 +- Font: New `scale`, `spacing`, and `kerning` property of font style - @ivanlanin +- Paragraph: Added shading to the paragraph style for full width shading - @lrobert GH-264 +- RTF Writer: Support for sections, margins, and borders - @ivanlanin GH-249 +- Section: Ability to set paper size, e.g. A4, A3, and Legal - @ivanlanin GH-249 +- General: New `PhpWord::save()` method to encapsulate `IOFactory` - @ivanlanin +- General: New `Shared\Converter` static class - @ivanlanin +- Chart: Basic 2D chart (pie, doughnut, bar, line, area, scatter, radar) - @ivanlanin GH-278 +- Chart: 3D charts and ability to set width and height - @ivanlanin +- FormField: Ability to add textinput, checkbox, and dropdown form elements - @ivanlanin GH-266 +- Setting: Ability to define document protection (readOnly, comments, trackedChanges, forms) - @ivanlanin +- Setting: Ability to remove [Compatibility Mode] text in the MS Word title bar - @ivanlanin +- SDT: Ability to add structured document tag elements (comboBox, dropDownList, date) - @ivanlanin +- Paragraph: Support for paragraph with borders - @ivanlanin GH-294 +- Word2007 Writer : Support for RTL - @Progi1984 GH-331 + +### Bugfixes + +- Fix rare PclZip/realpath/PHP version problem - @andrew-kzoo GH-261 +- `addHTML` encoding and ampersand fixes for PHP 5.3 - @bskrtich GH-270 +- Page breaks on titles and tables - @ivanlanin GH-274 +- Table inside vertical border does not rendered properly - @ivanlanin GH-280 +- `add` of container should be case insensitive, e.g. `addToc` should be accepted, not only `addTOC` - @ivanlanin GH-294 +- Fix specific borders (and margins) were not written correctly in word2007 writer - @pscheit GH-327 + +### Deprecated + +- `Element\Link::getTarget()` replaced by `Element\Link::getSource()` +- `Element\Section::getSettings()` and `Element\Section::setSettings()` replaced by `Element\Section::getStyle()` and `Element\Section::setStyle()` +- `Shared\Drawing` and `Shared\Font` merged into `Shared\Converter` +- `DocumentProperties` replaced by `Metadata\DocInfo` + +### Miscellaneous + +- Docs: Add known issue on `README` about requirement for temporary folder to be writable and update `samples/index.php` for this requirement check - @ivanlanin GH-238 +- Docs: Correct elements.rst about Line - @chrissharkman GH-292 +- PclZip: Remove temporary file after used - @andrew-kzoo GH-265 +- Autoloader: Add the ability to set the autoloader options - @bskrtich GH-267 +- Element: Refactor elements to move set relation Id from container to element - @ivanlanin +- Introduced CreateTemporaryFileException, CopyFileException - @RomanSyroeshko +- Settings: added method to set user defined temporary directory - @RomanSyroeshko GH-310 + +## 0.11.1 - 2 June 2014 + +This is an immediate bugfix release for HTML reader. + +- HTML Reader: `

` and header tags puts no output - @canyildiz @ivanlanin GH-257 + +## 0.11.0 - 1 June 2014 + +This release marked the change of PHPWord license from LGPL 2.1 to LGPL 3. Four new elements were added: TextBox, ListItemRun, Field, and Line. Relative and absolute positioning for images and textboxes were added. Writer classes were refactored into parts, elements, and styles. ODT and RTF features were enhanced. Ability to add elements to PHPWord object via HTML were implemented. RTF and HTML reader were initiated. + +### Features + +- Image: Ability to define relative and absolute positioning - @basjan GH-217 +- Footer: Conform footer with header by adding firstPage, evenPage and by inheritance - @basjan @ivanlanin GH-219 +- Element: New `TextBox` element - @basjan @ivanlanin GH-228 GH-229 GH-231 +- HTML: Ability to add elements to PHPWord object via html - @basjan GH-231 +- Element: New `ListItemRun` element that can add a list item with inline formatting like a textrun - @basjan GH-235 +- Table: Ability to add table inside a cell (nested table) - @ivanlanin GH-149 +- RTF Writer: UTF8 support for RTF: Internal UTF8 text is converted to Unicode before writing - @ivanlanin GH-158 +- Table: Ability to define table width (in percent and twip) and position - @ivanlanin GH-237 +- RTF Writer: Ability to add links and page breaks in RTF - @ivanlanin GH-196 +- ListItemRun: Remove fontStyle parameter because ListItemRun is inherited from TextRun and TextRun doesn't have fontStyle - @ivanlanin +- Config: Ability to use a config file to store various common settings - @ivanlanin GH-200 +- ODT Writer: Enable inline font style in TextRun - @ivanlanin +- ODT Writer: Enable underline, strike/doublestrike, smallcaps/allcaps, superscript/subscript font style - @ivanlanin +- ODT Writer: Enable section and column - @ivanlanin +- PDF Writer: Add TCPDF and mPDF as optional PDF renderer library - @ivanlanin +- ODT Writer: Enable title element and custom document properties - @ivanlanin +- ODT Reader: Ability to read standard and custom document properties - @ivanlanin +- Word2007 Writer: Enable the missing custom document properties writer - @ivanlanin +- Image: Enable "image float left" - @ivanlanin GH-244 +- RTF Writer: Ability to write document properties - @ivanlanin +- RTF Writer: Ability to write image - @ivanlanin +- Element: New `Field` element - @basjan GH-251 +- RTF Reader: Basic RTF reader - @ivanlanin GH-72 GH-252 +- Element: New `Line` element - @basjan GH-253 +- Title: Ability to apply numbering in heading - @ivanlanin GH-193 +- HTML Reader: Basic HTML reader - @ivanlanin GH-80 GH-254 +- RTF Writer: Basic table writing - @ivanlanin GH-245 + +### Bugfixes + +- Header: All images added to the second header were assigned to the first header - @basjan GH-222 +- Conversion: Fix conversion from cm to pixel, pixel to cm, and pixel to point - @basjan GH-233 GH-234 +- PageBreak: Page break adds new line in the beginning of the new page - @ivanlanin GH-150 +- Image: `marginLeft` and `marginTop` cannot accept float value - @ivanlanin GH-248 +- Title: Orphan `w:fldChar` caused OpenOffice to crash when opening DOCX - @ivanlanin GH-236 + +### Deprecated + +- Static classes `Footnotes`, `Endnotes`, and `TOC` +- `Writer\Word2007\Part`: `Numbering::writeNumbering()`, `Settings::writeSettings()`, `WebSettings::writeWebSettings()`, `ContentTypes::writeContentTypes()`, `Styles::writeStyles()`, `Document::writeDocument()` all changed into `write()` +- `Writer\Word2007\Part\DocProps`: Split into `Writer\Word2007\Part\DocPropsCore` and `Writer\Word2007\Part\DocPropsApp` +- `Element\Title::getBookmarkId()` replaced by `Element\Title::getRelationId()` +- `Writer\HTML::writeDocument`: Replaced by `Writer\HTML::getContent` + +### Miscellaneous + +- License: Change the project license from LGPL 2.1 into LGPL 3.0 - GH-211 +- Word2007 Writer: New `Style\Image` class - @ivanlanin +- Refactor: Replace static classes `Footnotes`, `Endnotes`, and `TOC` with `Collections` - @ivanlanin GH-206 +- QA: Reactivate `phpcpd` and `phpmd` on Travis - @ivanlanin +- Refactor: PHPMD recommendation: Change all `get...` method that returns `boolean` into `is...` or `has...` - @ivanlanin +- Docs: Create gh-pages branch for API documentation - @Progi1984 GH-154 +- QA: Add `.scrutinizer.yml` and include `composer.lock` for preparation to Scrutinizer - @ivanlanin GH-186 +- Writer: Refactor writer parts using composite pattern - @ivanlanin +- Docs: Show code quality and test code coverage badge on README +- Style: Change behaviour of `set...` function of boolean properties; when none is defined, assumed true - @ivanlanin +- Shared: Unify PHP ZipArchive and PCLZip features into PhpWord ZipArchive - @ivanlanin +- Docs: Create VERSION file - @ivanlanin +- QA: Improve dan update requirement check in `samples` folder - @ivanlanin + + +## 0.10.1 - 21 May 2014 + +This is a bugfix release for `php-zip` requirement in Composer. + +- Change Composer requirements for php-zip from `require` to `suggest` - @bskrtich GH-246 + +## 0.10.0 - 4 May 2014 + +This release marked heavy refactorings on internal code structure with the creation of some abstract classes to reduce code duplication. `Element` subnamespace is introduced in this release to replace `Section`. Word2007 reader capability is greatly enhanced. Endnote is introduced. List numbering is now customizable. Basic HTML and PDF writing support is enabled. Basic ODText reader is introduced. ### Features @@ -26,16 +153,30 @@ This release marked heavy refactorings on internal code structure with the creat - Link: Ability to add link in header/footer - @ivanlanin GH-187 - Object: Ability to add object in header, footer, textrun, and footnote - @ivanlanin GH-187 - Media: Add `Media::resetElements()` to reset all media data - @juzi GH-19 -- General: Add `Style::resetStyles()`, `Footnote::resetElements()`, and `TOC::resetTitles()` - @ivanlanin GH-187 -- Reader: Ability to read header, footer, footnotes, link, preservetext, textbreak, pagebreak, table, and list - @ivanlanin +- General: Add `Style::resetStyles()` - @ivanlanin GH-187 +- DOCX Reader: Ability to read header, footer, footnotes, link, preservetext, textbreak, pagebreak, table, list, image, and title - @ivanlanin - Endnote: Ability to add endnotes - @ivanlanin - ListItem: Ability to create custom list and reset list number - @ivanlanin GH-10 GH-198 - ODT Writer: Basic table writing support - @ivanlanin +- Image: Keep image aspect ratio if only 1 dimension styled - @japonicus GH-194 +- HTML Writer: Basic HTML writer: text, textrun, link, title, textbreak, table, image (as Base64), footnote, endnote - @ivanlanin GH-203 GH-67 GH-147 +- PDF Writer: Basic PDF writer using DomPDF: All HTML element except image - @ivanlanin GH-68 +- DOCX Writer: Change `docProps/app.xml` `Application` to `PHPWord` - @ivanlanin +- DOCX Writer: Create `word/settings.xml` and `word/webSettings.xml` dynamically - @ivanlanin +- ODT Writer: Basic image writing - @ivanlanin +- ODT Writer: Link writing - @ivanlanin +- ODT Reader: Basic ODText Reader - @ivanlanin GH-71 +- Section: Ability to define gutter and line numbering - @ivanlanin +- Font: Small caps, all caps, and double strikethrough - @ivanlanin GH-151 +- Settings: Ability to use measurement unit other than twips with `setMeasurementUnit` - @ivanlanin GH-199 +- Style: Remove `bgColor` from `Font`, `Table`, and `Cell` and put it into the new `Shading` style - @ivanlanin +- Style: New `Indentation` and `Spacing` style - @ivanlanin +- Paragraph: Ability to define first line and right indentation - @ivanlanin ### Bugfixes - Footnote: Footnote content doesn't show footnote reference number - @ivanlanin GH-170 -- Documentation : Error in a fonction - @theBeerNut GH-195 +- Documentation: Error in a function - @theBeerNut GH-195 ### Deprecated @@ -49,6 +190,9 @@ This release marked heavy refactorings on internal code structure with the creat - `Footnote::addFootnoteLinkElement` replaced by `Media::addElement` - `Footnote::getFootnoteLinkElements` replaced by `Media::getElements` - All current methods on `Media` +- `Element\Link::getLinkSrc` replaced by `Element\Link::getTarget` +- `Element\Link::getLinkName` replaced by `Element\Link::getText` +- `Style\Cell::getDefaultBorderColor` ### Miscellaneous @@ -65,6 +209,11 @@ This release marked heavy refactorings on internal code structure with the creat - Writer: New 'ODText\Base` class - @ivanlanin GH-187 - General: Rename `Footnote` to `Footnotes` to reflect the nature of collection - @ivanlanin - General: Add some unit tests for Shared & Element (100%!) - @Progi1984 +- Test: Add some samples and tests for image wrapping style - @brunocasado GH-59 +- Refactor: Remove Style\Tabs - @ivanlanin +- Refactor: Apply composite pattern for writers - @ivanlanin +- Refactor: Split `AbstractContainer` from `AbstractElement` - @ivanlanin +- Refactor: Apply composite pattern for Word2007 reader - @ivanlanin ## 0.9.1 - 27 Mar 2014 diff --git a/COPYING b/COPYING new file mode 100644 index 00000000..94a9ed02 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/COPYING.LESSER b/COPYING.LESSER new file mode 100644 index 00000000..65c5ca88 --- /dev/null +++ b/COPYING.LESSER @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..3f6a8c38 --- /dev/null +++ b/LICENSE @@ -0,0 +1,15 @@ +PHPWord, a pure PHP library for reading and writing word processing documents. + +Copyright (c) 2010-2014 PHPWord. + +PHPWord is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License version 3 as published by +the Free Software Foundation. + +PHPWord 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 version 3 for more details. + +You should have received a copy of the GNU Lesser General Public License version 3 +along with PHPWord. If not, see . diff --git a/LICENSE.md b/LICENSE.md deleted file mode 100644 index 57b74d4c..00000000 --- a/LICENSE.md +++ /dev/null @@ -1,345 +0,0 @@ -GNU LESSER GENERAL PUBLIC LICENSE - - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - -NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - -END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/README.md b/README.md old mode 100755 new mode 100644 index 3a9a4615..841ab1a1 --- a/README.md +++ b/README.md @@ -1,112 +1,140 @@ -# ![PHPWord](https://raw.githubusercontent.com/PHPOffice/PHPWord/develop/docs/images/phpword.svg "PHPWord") - -[![Build Status](https://travis-ci.org/PHPOffice/PHPWord.svg?branch=master)](https://travis-ci.org/PHPOffice/PHPWord) -[![Latest Stable Version](https://poser.pugx.org/phpoffice/phpword/v/stable.png)](https://packagist.org/packages/phpoffice/phpword) -[![Total Downloads](https://poser.pugx.org/phpoffice/phpword/downloads.png)](https://packagist.org/packages/phpoffice/phpword) -[![Latest Unstable Version](https://poser.pugx.org/phpoffice/phpword/v/unstable.png)](https://packagist.org/packages/phpoffice/phpword) -[![License](https://poser.pugx.org/phpoffice/phpword/license.png)](https://packagist.org/packages/phpoffice/phpword) - - -PHPWord is a library written in pure PHP that provides a set of classes to write to and read from different document file formats. The current version of PHPWord supports Microsoft [Office Open XML](http://en.wikipedia.org/wiki/Office_Open_XML) (OOXML or OpenXML), OASIS [Open Document Format for Office Applications](http://en.wikipedia.org/wiki/OpenDocument) (OpenDocument or ODF), and [Rich Text Format](http://en.wikipedia.org/wiki/Rich_Text_Format) (RTF). - -With PHPWord, you can create DOCX, ODT, or RTF documents dynamically using your PHP 5.3+ scripts. Below are some of the things that you can do with PHPWord library: - -* Set document properties, e.g. title, subject, and creator. -* Create document sections with different settings, e.g. portrait/landscape, page size, and page numbering -* Create header and footer for each sections -* Set default font type, font size, and paragraph style -* Use UTF-8 and East Asia fonts/characters -* Define custom font styles (e.g. bold, italic, color) and paragraph styles (e.g. centered, multicolumns, spacing) either as named style or inline in text -* Insert paragraphs, either as a simple text or complex one (a text run) that contains other elements -* Insert titles (headers) and table of contents -* Insert text breaks and page breaks -* Insert and format images, either local, remote, or as page watermarks -* Insert binary OLE Objects such as Excel or Visio -* Insert and format table with customized properties for each rows (e.g. repeat as header row) and cells (e.g. background color, rowspan, colspan) -* Insert list items as bulleted, numbered, or multilevel -* Insert hyperlinks -* Insert footnotes and endnotes -* Create document from templates -* Use XSL 1.0 style sheets to transform main document part of OOXML template -* ... and many more features on progress - -__Want to contribute?__ [Fork us](https://github.com/PHPOffice/PHPWord/fork) or [submit](https://github.com/PHPOffice/PHPWord/issues) your bug reports or feature requests to us. - -## Requirements -* PHP 5.3+ -* PHP [Zip](http://php.net/manual/en/book.zip.php) extension -* PHP [XML Parser](http://www.php.net/manual/en/xml.installation.php) extension - -### Optional PHP extensions -* PHP [GD](http://php.net/manual/en/book.image.php) extension -* PHP [XMLWriter](http://php.net/manual/en/book.xmlwriter.php) extension -* PHP [XSL](http://php.net/manual/en/book.xsl.php) extension - -## Installation - -It is recommended that you install the PHPWord library [through composer](http://getcomposer.org/). To do so, add -the following lines to your ``composer.json``. - -```json -{ - "require": { - "phpoffice/phpword": "dev-master" - } -} -``` - -Alternatively, you can download the latest release from the [releases page](https://github.com/PHPOffice/PHPWord/releases). -In this case, you will have to register the autoloader. - -```php -require_once 'path/to/PhpWord/src/PhpWord/Autoloader.php'; -\PhpOffice\PhpWord\Autoloader::register(); -``` - -## Basic usage - -The following is a basic example of the PHPWord library. More examples are provided in the [samples folder](samples/). - -```php -$phpWord = new \PhpOffice\PhpWord\PhpWord(); - -// Every element you want to append to the word document is placed in a section. -// To create a basic section: -$section = $phpWord->addSection(); - -// After creating a section, you can append elements: -$section->addText('Hello world!'); - -// You can directly style your text by giving the addText function an array: -$section->addText('Hello world! I am formatted.', - array('name'=>'Tahoma', 'size'=>16, 'bold'=>true)); - -// If you often need the same style again you can create a user defined style -// to the word document and give the addText function the name of the style: -$phpWord->addFontStyle('myOwnStyle', - array('name'=>'Verdana', 'size'=>14, 'color'=>'1B2232')); -$section->addText('Hello world! I am formatted by a user defined style', - 'myOwnStyle'); - -// You can also put the appended element to local object like this: -$fontStyle = new \PhpOffice\PhpWord\Style\Font(); -$fontStyle->setBold(true); -$fontStyle->setName('Verdana'); -$fontStyle->setSize(22); -$myTextElement = $section->addText('Hello World!'); -$myTextElement->setFontStyle($fontStyle); - -// Finally, write the document: -$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); -$objWriter->save('helloWorld.docx'); - -$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'ODText'); -$objWriter->save('helloWorld.odt'); - -$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'RTF'); -$objWriter->save('helloWorld.rtf'); -``` - -## Documentation - -__Want to know more?__ Read the full documentation of PHPWord on [Read The Docs](http://phpword.readthedocs.org/). +# ![PHPWord](https://rawgit.com/PHPOffice/PHPWord/develop/docs/images/phpword.svg "PHPWord") + +[![Latest Stable Version](https://poser.pugx.org/phpoffice/phpword/v/stable.png)](https://packagist.org/packages/phpoffice/phpword) +[![Build Status](https://travis-ci.org/PHPOffice/PHPWord.svg?branch=master)](https://travis-ci.org/PHPOffice/PHPWord) +[![Code Quality](https://scrutinizer-ci.com/g/PHPOffice/PHPWord/badges/quality-score.png?s=b5997ce59ac2816b4514f3a38de9900f6d492c1d)](https://scrutinizer-ci.com/g/PHPOffice/PHPWord/) +[![Code Coverage](https://scrutinizer-ci.com/g/PHPOffice/PHPWord/badges/coverage.png?s=742a98745725c562955440edc8d2c39d7ff5ae25)](https://scrutinizer-ci.com/g/PHPOffice/PHPWord/) +[![Total Downloads](https://poser.pugx.org/phpoffice/phpword/downloads.png)](https://packagist.org/packages/phpoffice/phpword) +[![License](https://poser.pugx.org/phpoffice/phpword/license.png)](https://packagist.org/packages/phpoffice/phpword) + +PHPWord is a library written in pure PHP that provides a set of classes to write to and read from different document file formats. The current version of PHPWord supports Microsoft [Office Open XML](http://en.wikipedia.org/wiki/Office_Open_XML) (OOXML or OpenXML), OASIS [Open Document Format for Office Applications](http://en.wikipedia.org/wiki/OpenDocument) (OpenDocument or ODF), [Rich Text Format](http://en.wikipedia.org/wiki/Rich_Text_Format) (RTF), HTML, and PDF. + +PHPWord is an open source project licensed under the terms of [LGPL version 3](https://github.com/PHPOffice/PHPWord/blob/develop/COPYING.LESSER). PHPWord is aimed to be a high quality software product by incorporating [continuous integration](https://travis-ci.org/PHPOffice/PHPWord) and [unit testing](http://phpoffice.github.io/PHPWord/coverage/develop/). You can learn more about PHPWord by reading the [Developers' Documentation](http://phpword.readthedocs.org/) and the [API Documentation](http://phpoffice.github.io/PHPWord/docs/develop/). + +Read more about PHPWord: + +- [Features](#features) +- [Requirements](#requirements) +- [Installation](#installation) +- [Getting started](#getting-started) +- [Known issues](#known-issues) +- [Contributing](#contributing) +- [Developers' Documentation](http://phpword.readthedocs.org/) +- [API Documentation](http://phpoffice.github.io/PHPWord/docs/master/) + +## Features + +With PHPWord, you can create DOCX, ODT, or RTF documents dynamically using your PHP 5.3+ scripts. Below are some of the things that you can do with PHPWord library: + +- Set document properties, e.g. title, subject, and creator. +- Create document sections with different settings, e.g. portrait/landscape, page size, and page numbering +- Create header and footer for each sections +- Set default font type, font size, and paragraph style +- Use UTF-8 and East Asia fonts/characters +- Define custom font styles (e.g. bold, italic, color) and paragraph styles (e.g. centered, multicolumns, spacing) either as named style or inline in text +- Insert paragraphs, either as a simple text or complex one (a text run) that contains other elements +- Insert titles (headers) and table of contents +- Insert text breaks and page breaks +- Insert and format images, either local, remote, or as page watermarks +- Insert binary OLE Objects such as Excel or Visio +- Insert and format table with customized properties for each rows (e.g. repeat as header row) and cells (e.g. background color, rowspan, colspan) +- Insert list items as bulleted, numbered, or multilevel +- Insert hyperlinks +- Insert footnotes and endnotes +- Insert drawing shapes (arc, curve, line, polyline, rect, oval) +- Insert charts (pie, doughnut, bar, line, area, scatter, radar) +- Insert form fields (textinput, checkbox, and dropdown) +- Create document from templates +- Use XSL 1.0 style sheets to transform main document part of OOXML template +- ... and many more features on progress + +## Requirements + +PHPWord requires the following: + +- PHP 5.3+ +- [Zip extension](http://php.net/manual/en/book.zip.php) +- [XML Parser extension](http://www.php.net/manual/en/xml.installation.php) +- [GD extension](http://php.net/manual/en/book.image.php) (optional, used to add images) +- [XMLWriter extension](http://php.net/manual/en/book.xmlwriter.php) (optional, used to write DOCX and ODT) +- [XSL extension](http://php.net/manual/en/book.xsl.php) (optional, used to apply XSL style sheet to template ) +- [dompdf](https://github.com/dompdf/dompdf) (optional, used to write PDF) + +## Installation + +It is recommended that you install the PHPWord library [through composer](http://getcomposer.org/). To do so, add +the following lines to your ``composer.json``. + +```json +{ + "require": { + "phpoffice/phpword": "dev-master" + } +} +``` + +Alternatively, you can download the latest release from the [releases page](https://github.com/PHPOffice/PHPWord/releases). +In this case, you will have to register the autoloader. + +```php +require_once 'path/to/PhpWord/src/PhpWord/Autoloader.php'; +\PhpOffice\PhpWord\Autoloader::register(); +``` + +## Getting started + +The following is a basic usage example of the PHPWord library. + +```php +require_once 'src/PhpWord/Autoloader.php'; +\PhpOffice\PhpWord\Autoloader::register(); + +$phpWord = new \PhpOffice\PhpWord\PhpWord(); + +// Every element you want to append to the word document is placed in a section. +// To create a basic section: +$section = $phpWord->addSection(); + +// After creating a section, you can append elements: +$section->addText('Hello world!'); + +// You can directly style your text by giving the addText function an array: +$section->addText('Hello world! I am formatted.', + array('name'=>'Tahoma', 'size'=>16, 'bold'=>true)); + +// If you often need the same style again you can create a user defined style +// to the word document and give the addText function the name of the style: +$phpWord->addFontStyle('myOwnStyle', + array('name'=>'Verdana', 'size'=>14, 'color'=>'1B2232')); +$section->addText('Hello world! I am formatted by a user defined style', + 'myOwnStyle'); + +// You can also put the appended element to local object like this: +$fontStyle = array( + 'name' => 'Verdana', + 'size' => 22, + 'bold' => true, +); +$myTextElement = $section->addText('Hello World!'); +$myTextElement->setFontStyle($fontStyle); + +// Finally, save the document: +$phpWord->save('helloWorld.docx'); +$phpWord->save('helloWorld.odt', 'ODText'); +$phpWord->save('helloWorld.rtf', 'RTF'); +``` + +More examples are provided in the [samples folder](samples/). You can also read the [Developers' Documentation](http://phpword.readthedocs.org/) and the [API Documentation](http://phpoffice.github.io/PHPWord/docs/master/) for more detail. + +## Known issues + +- GH-238: PHPWord uses temporary folder with `sys_get_temp_dir()` extensively. The default setting on some systems (especially Windows) do not give appropriate read/write permission to this folder. Run `samples/index.php` either by CLI or by web browsers to check if you have this requirement fulfilled. + +## Contributing + +We welcome everyone to contribute to PHPWord. Below are some of the things that you can do to contribute: + +- Read [our contributing guide](https://github.com/PHPOffice/PHPWord/blob/master/CONTRIBUTING.md) +- [Fork us](https://github.com/PHPOffice/PHPWord/fork) and [request a pull](https://github.com/PHPOffice/PHPWord/pulls) to the [develop](https://github.com/PHPOffice/PHPWord/tree/develop) branch +- Submit [bug reports or feature requests](https://github.com/PHPOffice/PHPWord/issues) to GitHub +- Follow [@PHPWord](https://twitter.com/PHPWord) and [@PHPOffice](https://twitter.com/PHPOffice) on Twitter diff --git a/VERSION b/VERSION new file mode 100644 index 00000000..d33c3a21 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.12.0 \ No newline at end of file diff --git a/composer.json b/composer.json index 6a2d9573..74009e3a 100644 --- a/composer.json +++ b/composer.json @@ -1,14 +1,14 @@ { "name": "phpoffice/phpword", - "description": "PHPWord - Read, Create, and Write DOCX, ODT, and RTF documents in PHP", + "description": "PHPWord - A pure PHP library for reading and writing word processing documents (DOCX, ODT, RTF, HTML, PDF)", "keywords": [ "PHP", "PhpOffice", "office", "PhpWord", "word", "template", "reader", "writer", "docx", "OOXML", "OpenXML", "Office Open XML", "ISO IEC 29500", "WordprocessingML", - "RTF", "Rich Text Format", "doc", "odt", "OpenDocument" + "RTF", "Rich Text Format", "doc", "odt", "OpenDocument", "PDF", "HTML" ], "homepage": "http://phpoffice.github.io", "type": "library", - "license": "LGPL-3.0+", + "license": "LGPL-3.0", "authors": [ { "name": "Mark Baker" @@ -33,16 +33,25 @@ ], "require": { "php": ">=5.3.3", - "ext-xml": "*", - "ext-zip": "*" + "ext-xml": "*" }, "require-dev": { - "phpunit/phpunit": "3.7.*" + "phpunit/phpunit": "3.7.*", + "phpdocumentor/phpdocumentor":"2.*", + "squizlabs/php_codesniffer": "1.*", + "phpmd/phpmd": "2.*", + "sebastian/phpcpd": "2.*", + "phploc/phploc": "2.*", + "dompdf/dompdf":"0.6.*", + "tecnick.com/tcpdf": "6.*", + "mpdf/mpdf": "5.*" }, "suggest": { - "ext-gd2": "*", - "ext-xmlwriter": "*", - "ext-xsl": "*" + "ext-zip": "Used to write DOCX and ODT", + "ext-gd2": "Used to add images", + "ext-xmlwriter": "Used to write DOCX and ODT", + "ext-xsl": "Used to apply XSL style sheet to template part", + "dompdf/dompdf": "Used to write PDF" }, "autoload": { "psr-4": { diff --git a/composer.lock b/composer.lock new file mode 100644 index 00000000..122d7ab2 --- /dev/null +++ b/composer.lock @@ -0,0 +1,3634 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", + "This file is @generated automatically" + ], + "hash": "50bae1209285a67796556b7ec42f64fc", + "packages": [ + + ], + "packages-dev": [ + { + "name": "cilex/cilex", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/Cilex/Cilex.git", + "reference": "7acd965a609a56d0345e8b6071c261fbdb926cb5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Cilex/Cilex/zipball/7acd965a609a56d0345e8b6071c261fbdb926cb5", + "reference": "7acd965a609a56d0345e8b6071c261fbdb926cb5", + "shasum": "" + }, + "require": { + "cilex/console-service-provider": "1.*", + "php": ">=5.3.3", + "pimple/pimple": "~1.0", + "symfony/finder": "~2.1", + "symfony/process": "~2.1" + }, + "require-dev": { + "phpunit/phpunit": "3.7.*", + "symfony/validator": "~2.1" + }, + "suggest": { + "monolog/monolog": ">=1.0.0", + "symfony/validator": ">=1.0.0", + "symfony/yaml": ">=1.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "psr-0": { + "Cilex": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mike van Riel", + "email": "mike.vanriel@naenius.com" + } + ], + "description": "The PHP micro-framework for Command line tools based on the Symfony2 Components", + "homepage": "http://cilex.github.com", + "keywords": [ + "cli", + "microframework" + ], + "time": "2014-03-29 14:03:13" + }, + { + "name": "cilex/console-service-provider", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/Cilex/console-service-provider.git", + "reference": "25ee3d1875243d38e1a3448ff94bdf944f70d24e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Cilex/console-service-provider/zipball/25ee3d1875243d38e1a3448ff94bdf944f70d24e", + "reference": "25ee3d1875243d38e1a3448ff94bdf944f70d24e", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "pimple/pimple": "1.*@dev", + "symfony/console": "~2.1" + }, + "require-dev": { + "cilex/cilex": "1.*@dev", + "silex/silex": "1.*@dev" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "psr-0": { + "Cilex\\Provider\\Console": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Beau Simensen", + "email": "beau@dflydev.com", + "homepage": "http://beausimensen.com" + }, + { + "name": "Mike van Riel", + "email": "mike.vanriel@naenius.com" + } + ], + "description": "Console Service Provider", + "keywords": [ + "cilex", + "console", + "pimple", + "service-provider", + "silex" + ], + "time": "2012-12-19 10:50:58" + }, + { + "name": "doctrine/annotations", + "version": "v1.1.2", + "source": { + "type": "git", + "url": "https://github.com/doctrine/annotations.git", + "reference": "40db0c96985aab2822edbc4848b3bd2429e02670" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/annotations/zipball/40db0c96985aab2822edbc4848b3bd2429e02670", + "reference": "40db0c96985aab2822edbc4848b3bd2429e02670", + "shasum": "" + }, + "require": { + "doctrine/lexer": "1.*", + "php": ">=5.3.2" + }, + "require-dev": { + "doctrine/cache": "1.*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-0": { + "Doctrine\\Common\\Annotations\\": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jonathan H. Wage", + "email": "jonwage@gmail.com", + "homepage": "http://www.jwage.com/", + "role": "Creator" + }, + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com", + "homepage": "http://www.instaclick.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Johannes M. Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "http://jmsyst.com", + "role": "Developer of wrapped JMSSerializerBundle" + } + ], + "description": "Docblock Annotations Parser", + "homepage": "http://www.doctrine-project.org", + "keywords": [ + "annotations", + "docblock", + "parser" + ], + "time": "2013-06-16 21:33:03" + }, + { + "name": "doctrine/lexer", + "version": "v1.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/lexer.git", + "reference": "2f708a85bb3aab5d99dab8be435abd73e0b18acb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/lexer/zipball/2f708a85bb3aab5d99dab8be435abd73e0b18acb", + "reference": "2f708a85bb3aab5d99dab8be435abd73e0b18acb", + "shasum": "" + }, + "require": { + "php": ">=5.3.2" + }, + "type": "library", + "autoload": { + "psr-0": { + "Doctrine\\Common\\Lexer\\": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com", + "homepage": "http://www.instaclick.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "http://jmsyst.com", + "role": "Developer of wrapped JMSSerializerBundle" + } + ], + "description": "Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers.", + "homepage": "http://www.doctrine-project.org", + "keywords": [ + "lexer", + "parser" + ], + "time": "2013-01-12 18:59:04" + }, + { + "name": "dompdf/dompdf", + "version": "v0.6.1", + "source": { + "type": "git", + "url": "https://github.com/dompdf/dompdf.git", + "reference": "cf7d8a0a27270418850cc7d7ea532159e5eeb3eb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/dompdf/dompdf/zipball/cf7d8a0a27270418850cc7d7ea532159e5eeb3eb", + "reference": "cf7d8a0a27270418850cc7d7ea532159e5eeb3eb", + "shasum": "" + }, + "require": { + "phenx/php-font-lib": "0.2.*" + }, + "type": "library", + "autoload": { + "classmap": [ + "include/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL" + ], + "authors": [ + { + "name": "Fabien Ménager", + "email": "fabien.menager@gmail.com" + }, + { + "name": "Brian Sweeney", + "email": "eclecticgeek@gmail.com" + } + ], + "description": "DOMPDF is a CSS 2.1 compliant HTML to PDF converter", + "homepage": "https://github.com/dompdf/dompdf", + "time": "2014-03-11 01:59:52" + }, + { + "name": "erusev/parsedown", + "version": "0.9.4", + "source": { + "type": "git", + "url": "https://github.com/erusev/parsedown.git", + "reference": "d29ff18299210b52a75a631a70963e7c8b35b04f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/erusev/parsedown/zipball/d29ff18299210b52a75a631a70963e7c8b35b04f", + "reference": "d29ff18299210b52a75a631a70963e7c8b35b04f", + "shasum": "" + }, + "type": "library", + "autoload": { + "psr-0": { + "Parsedown": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Emanuil Rusev", + "email": "hello@erusev.com", + "homepage": "http://erusev.com" + } + ], + "description": "Parser for Markdown.", + "homepage": "http://parsedown.org", + "keywords": [ + "markdown", + "parser" + ], + "time": "2014-02-06 12:16:14" + }, + { + "name": "jms/metadata", + "version": "1.5.0", + "source": { + "type": "git", + "url": "https://github.com/schmittjoh/metadata.git", + "reference": "88ffa28bc987e4c26229fc84a2e541b6ed4e1459" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/schmittjoh/metadata/zipball/88ffa28bc987e4c26229fc84a2e541b6ed4e1459", + "reference": "88ffa28bc987e4c26229fc84a2e541b6ed4e1459", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "doctrine/cache": "~1.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.5.x-dev" + } + }, + "autoload": { + "psr-0": { + "Metadata\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache" + ], + "authors": [ + { + "name": "Johannes M. Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "http://jmsyst.com", + "role": "Developer of wrapped JMSSerializerBundle" + } + ], + "description": "Class/method/property metadata management in PHP", + "keywords": [ + "annotations", + "metadata", + "xml", + "yaml" + ], + "time": "2013-11-05 23:02:36" + }, + { + "name": "jms/parser-lib", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/schmittjoh/parser-lib.git", + "reference": "c509473bc1b4866415627af0e1c6cc8ac97fa51d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/schmittjoh/parser-lib/zipball/c509473bc1b4866415627af0e1c6cc8ac97fa51d", + "reference": "c509473bc1b4866415627af0e1c6cc8ac97fa51d", + "shasum": "" + }, + "require": { + "phpoption/phpoption": ">=0.9,<2.0-dev" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "autoload": { + "psr-0": { + "JMS\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache2" + ], + "description": "A library for easily creating recursive-descent parsers.", + "time": "2012-11-18 18:08:43" + }, + { + "name": "jms/serializer", + "version": "0.16.0", + "source": { + "type": "git", + "url": "https://github.com/schmittjoh/serializer.git", + "reference": "c8a171357ca92b6706e395c757f334902d430ea9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/schmittjoh/serializer/zipball/c8a171357ca92b6706e395c757f334902d430ea9", + "reference": "c8a171357ca92b6706e395c757f334902d430ea9", + "shasum": "" + }, + "require": { + "doctrine/annotations": "1.*", + "jms/metadata": "~1.1", + "jms/parser-lib": "1.*", + "php": ">=5.3.2", + "phpcollection/phpcollection": "~0.1" + }, + "require-dev": { + "doctrine/orm": "~2.1", + "doctrine/phpcr-odm": "~1.0.1", + "jackalope/jackalope-doctrine-dbal": "1.0.*", + "propel/propel1": "~1.7", + "symfony/filesystem": "2.*", + "symfony/form": "~2.1", + "symfony/translation": "~2.0", + "symfony/validator": "~2.0", + "symfony/yaml": "2.*", + "twig/twig": ">=1.8,<2.0-dev" + }, + "suggest": { + "symfony/yaml": "Required if you'd like to serialize data to YAML format." + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "0.15-dev" + } + }, + "autoload": { + "psr-0": { + "JMS\\Serializer": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache2" + ], + "authors": [ + { + "name": "Johannes M. Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "http://jmsyst.com", + "role": "Developer of wrapped JMSSerializerBundle" + } + ], + "description": "Library for (de-)serializing data of any complexity; supports XML, JSON, and YAML.", + "homepage": "http://jmsyst.com/libs/serializer", + "keywords": [ + "deserialization", + "jaxb", + "json", + "serialization", + "xml" + ], + "time": "2014-03-18 08:39:00" + }, + { + "name": "knplabs/knp-menu", + "version": "v1.1.2", + "source": { + "type": "git", + "url": "https://github.com/KnpLabs/KnpMenu.git", + "reference": "f8e867268f63f561c1adadd6cbb5d8524f921873" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/KnpLabs/KnpMenu/zipball/f8e867268f63f561c1adadd6cbb5d8524f921873", + "reference": "f8e867268f63f561c1adadd6cbb5d8524f921873", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "pimple/pimple": "*", + "silex/silex": "1.0.*", + "twig/twig": ">=1.2,<2.0-dev" + }, + "suggest": { + "pimple/pimple": "for the built-in implementations of the menu provider and renderer provider", + "silex/silex": "for the integration with your silex application", + "twig/twig": "for the TwigRenderer and the integration with your templates" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1.x-dev" + } + }, + "autoload": { + "psr-0": { + "Knp\\Menu\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christophe Coevoet", + "email": "stof@notk.org" + }, + { + "name": "KnpLabs", + "homepage": "http://knplabs.com" + }, + { + "name": "Symfony Community", + "homepage": "https://github.com/KnpLabs/KnpMenu/contributors" + } + ], + "description": "An object oriented menu library", + "homepage": "http://knplabs.com", + "keywords": [ + "menu", + "tree" + ], + "time": "2012-06-10 16:20:40" + }, + { + "name": "monolog/monolog", + "version": "1.10.0", + "source": { + "type": "git", + "url": "https://github.com/Seldaek/monolog.git", + "reference": "25b16e801979098cb2f120e697bfce454b18bf23" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Seldaek/monolog/zipball/25b16e801979098cb2f120e697bfce454b18bf23", + "reference": "25b16e801979098cb2f120e697bfce454b18bf23", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "psr/log": "~1.0" + }, + "require-dev": { + "aws/aws-sdk-php": "~2.4, >2.4.8", + "doctrine/couchdb": "~1.0@dev", + "graylog2/gelf-php": "~1.0", + "phpunit/phpunit": "~3.7.0", + "raven/raven": "~0.5", + "ruflin/elastica": "0.90.*" + }, + "suggest": { + "aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB", + "doctrine/couchdb": "Allow sending log messages to a CouchDB server", + "ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)", + "ext-mongo": "Allow sending log messages to a MongoDB server", + "graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server", + "raven/raven": "Allow sending log messages to a Sentry server", + "rollbar/rollbar": "Allow sending log messages to Rollbar", + "ruflin/elastica": "Allow sending log messages to an Elastic Search server" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.10.x-dev" + } + }, + "autoload": { + "psr-4": { + "Monolog\\": "src/Monolog" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http://seld.be", + "role": "Developer" + } + ], + "description": "Sends your logs to files, sockets, inboxes, databases and various web services", + "homepage": "http://github.com/Seldaek/monolog", + "keywords": [ + "log", + "logging", + "psr-3" + ], + "time": "2014-06-04 16:30:04" + }, + { + "name": "mpdf/mpdf", + "version": "v5.7.2", + "source": { + "type": "git", + "url": "https://github.com/finwe/mpdf.git", + "reference": "1627f9e7d2ef0f635a886f611079216ed2929717" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/finwe/mpdf/zipball/1627f9e7d2ef0f635a886f611079216ed2929717", + "reference": "1627f9e7d2ef0f635a886f611079216ed2929717", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": ">=4.3.10" + }, + "type": "library", + "autoload": { + "classmap": [ + "mpdf.php", + "classes" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "GPL-1.0+" + ], + "authors": [ + { + "name": "Ian Back" + } + ], + "description": "A PHP class to generate PDF files from HTML with Unicode/UTF-8 and CJK support", + "homepage": "http://www.mpdf1.com/mpdf/index.php", + "keywords": [ + "pdf", + "php", + "utf-8" + ], + "time": "2014-05-16 07:18:10" + }, + { + "name": "nikic/php-parser", + "version": "v0.9.4", + "source": { + "type": "git", + "url": "https://github.com/nikic/PHP-Parser.git", + "reference": "1e5e280ae88a27effa2ae4aa2bd088494ed8594f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/1e5e280ae88a27effa2ae4aa2bd088494ed8594f", + "reference": "1e5e280ae88a27effa2ae4aa2bd088494ed8594f", + "shasum": "" + }, + "require": { + "php": ">=5.2" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "0.9-dev" + } + }, + "autoload": { + "psr-0": { + "PHPParser": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Nikita Popov" + } + ], + "description": "A PHP parser written in PHP", + "keywords": [ + "parser", + "php" + ], + "time": "2013-08-25 17:11:40" + }, + { + "name": "pdepend/pdepend", + "version": "2.0.0", + "source": { + "type": "git", + "url": "https://github.com/pdepend/pdepend.git", + "reference": "b74f2bb68e86104cd97dfb8d74209692c9b465ce" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/pdepend/pdepend/zipball/b74f2bb68e86104cd97dfb8d74209692c9b465ce", + "reference": "b74f2bb68e86104cd97dfb8d74209692c9b465ce", + "shasum": "" + }, + "require": { + "symfony/config": "@stable", + "symfony/dependency-injection": "@stable", + "symfony/filesystem": "@stable" + }, + "require-dev": { + "phpunit/phpunit": "3.*@stable", + "squizlabs/php_codesniffer": "@stable" + }, + "bin": [ + "src/bin/pdepend" + ], + "type": "library", + "autoload": { + "psr-0": { + "PDepend\\": "src/main/php/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "Official version of pdepend to be handled with Composer", + "time": "2014-05-21 09:48:10" + }, + { + "name": "phenx/php-font-lib", + "version": "0.2.2", + "source": { + "type": "git", + "url": "https://github.com/PhenX/php-font-lib.git", + "reference": "c30c7fc00a6b0d863e9bb4c5d5dd015298b2dc82" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PhenX/php-font-lib/zipball/c30c7fc00a6b0d863e9bb4c5d5dd015298b2dc82", + "reference": "c30c7fc00a6b0d863e9bb4c5d5dd015298b2dc82", + "shasum": "" + }, + "type": "library", + "autoload": { + "classmap": [ + "classes/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL" + ], + "authors": [ + { + "name": "Fabien Ménager", + "email": "fabien.menager@gmail.com" + } + ], + "description": "A library to read, parse, export and make subsets of different types of font files.", + "homepage": "https://github.com/PhenX/php-font-lib", + "time": "2014-02-01 15:22:28" + }, + { + "name": "phpcollection/phpcollection", + "version": "0.4.0", + "source": { + "type": "git", + "url": "https://github.com/schmittjoh/php-collection.git", + "reference": "b8bf55a0a929ca43b01232b36719f176f86c7e83" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/schmittjoh/php-collection/zipball/b8bf55a0a929ca43b01232b36719f176f86c7e83", + "reference": "b8bf55a0a929ca43b01232b36719f176f86c7e83", + "shasum": "" + }, + "require": { + "phpoption/phpoption": "1.*" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "0.3-dev" + } + }, + "autoload": { + "psr-0": { + "PhpCollection": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache2" + ], + "authors": [ + { + "name": "Johannes M. Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "http://jmsyst.com", + "role": "Developer of wrapped JMSSerializerBundle" + } + ], + "description": "General-Purpose Collection Library for PHP", + "keywords": [ + "collection", + "list", + "map", + "sequence", + "set" + ], + "time": "2014-03-11 13:46:42" + }, + { + "name": "phpdocumentor/fileset", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/Fileset.git", + "reference": "bfa78d8fa9763dfce6d0e5d3730c1d8ab25d34b0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/Fileset/zipball/bfa78d8fa9763dfce6d0e5d3730c1d8ab25d34b0", + "reference": "bfa78d8fa9763dfce6d0e5d3730c1d8ab25d34b0", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "symfony/finder": "~2.1" + }, + "require-dev": { + "phpunit/phpunit": "~3.7" + }, + "type": "library", + "autoload": { + "psr-0": { + "phpDocumentor": [ + "src/", + "tests/unit/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Fileset component for collecting a set of files given directories and file paths", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "files", + "fileset", + "phpdoc" + ], + "time": "2013-08-06 21:07:42" + }, + { + "name": "phpdocumentor/graphviz", + "version": "1.0.2", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/GraphViz.git", + "reference": "13595130b9bc185109f40f1b70f0b231f490f5fc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/GraphViz/zipball/13595130b9bc185109f40f1b70f0b231f490f5fc", + "reference": "13595130b9bc185109f40f1b70f0b231f490f5fc", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "phpunit/phpunit": "~3.7" + }, + "type": "library", + "autoload": { + "psr-0": { + "phpDocumentor": [ + "src/", + "tests/unit" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mike van Riel", + "email": "mike.vanriel@naenius.com" + } + ], + "time": "2014-02-26 17:45:01" + }, + { + "name": "phpdocumentor/phpdocumentor", + "version": "v2.5.0", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/phpDocumentor2.git", + "reference": "bf9fa40f6d00412410025b2e16eb16c315eb0216" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/phpDocumentor2/zipball/bf9fa40f6d00412410025b2e16eb16c315eb0216", + "reference": "bf9fa40f6d00412410025b2e16eb16c315eb0216", + "shasum": "" + }, + "require": { + "cilex/cilex": "~1.0", + "dompdf/dompdf": "~0.6", + "erusev/parsedown": "~0.7", + "jms/serializer": "~0.12", + "knplabs/knp-menu": "~1.1", + "monolog/monolog": "~1.6", + "php": ">=5.3.3", + "phpdocumentor/fileset": "~1.0", + "phpdocumentor/graphviz": "~1.0", + "phpdocumentor/reflection": "~1.0", + "phpdocumentor/reflection-docblock": "~2.0", + "phpdocumentor/template-abstract": "~1.2", + "phpdocumentor/template-checkstyle": "~1.2", + "phpdocumentor/template-clean": "~1.0", + "phpdocumentor/template-new-black": "~1.3", + "phpdocumentor/template-old-ocean": "~1.3", + "phpdocumentor/template-responsive": "~1.3", + "phpdocumentor/template-responsive-twig": "~1.2", + "phpdocumentor/template-xml": "~1.0", + "phpdocumentor/template-zend": "~1.3", + "symfony/config": "~2.3", + "symfony/console": "~2.3", + "symfony/event-dispatcher": "~2.1", + "symfony/process": "~2.0", + "symfony/stopwatch": "~2.3", + "symfony/validator": "~2.2", + "twig/twig": "~1.3", + "zendframework/zend-cache": "2.1.*", + "zendframework/zend-config": "2.1.*", + "zendframework/zend-filter": "2.1.*", + "zendframework/zend-i18n": "2.1.*", + "zendframework/zend-serializer": "2.1.*", + "zendframework/zend-servicemanager": "2.1.*", + "zendframework/zend-stdlib": "2.1.*", + "zetacomponents/document": ">=1.3.1" + }, + "require-dev": { + "behat/behat": "~2.4", + "mikey179/vfsstream": "~1.2", + "mockery/mockery": ">=0.8.0", + "phpunit/phpunit": "~3.7", + "squizlabs/php_codesniffer": "~1.4", + "symfony/expression-language": "~2.4" + }, + "suggest": { + "ext-twig": "Enabling the twig extension improves the generation of twig based templates.", + "ext-xslcache": "Enabling the XSLCache extension improves the generation of xml based templates." + }, + "bin": [ + "bin/phpdoc.php", + "bin/phpdoc" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-develop": "2.5-dev" + } + }, + "autoload": { + "psr-0": { + "phpDocumentor": [ + "src/", + "tests/unit/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Documentation Generator for PHP", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "api", + "application", + "dga", + "documentation", + "phpdoc" + ], + "time": "2014-05-17 12:25:35" + }, + { + "name": "phpdocumentor/reflection", + "version": "1.0.5", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/Reflection.git", + "reference": "df82db631acd60739c8796b3c6d5e4da970808f3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/Reflection/zipball/df82db631acd60739c8796b3c6d5e4da970808f3", + "reference": "df82db631acd60739c8796b3c6d5e4da970808f3", + "shasum": "" + }, + "require": { + "nikic/php-parser": "0.9.4", + "php": ">=5.3.3", + "phpdocumentor/reflection-docblock": "2.*", + "psr/log": "~1.0" + }, + "require-dev": { + "behat/behat": "~2.4", + "mockery/mockery": ">=0.7.0", + "phpunit/phpunit": "~3.7" + }, + "type": "library", + "autoload": { + "psr-0": { + "phpDocumentor": [ + "src/", + "tests/unit/", + "tests/mocks/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Reflection library to do Static Analysis for PHP Projects", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "phpDocumentor", + "phpdoc", + "reflection", + "static analysis" + ], + "time": "2014-03-28 11:20:22" + }, + { + "name": "phpdocumentor/reflection-docblock", + "version": "2.0.2", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git", + "reference": "0bca477a34baea39add016af90046f002a175619" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/0bca477a34baea39add016af90046f002a175619", + "reference": "0bca477a34baea39add016af90046f002a175619", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "phpunit/phpunit": "3.7.*@stable" + }, + "suggest": { + "dflydev/markdown": "1.0.*", + "erusev/parsedown": "~0.7" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-0": { + "phpDocumentor": [ + "src/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mike van Riel", + "email": "mike.vanriel@naenius.com" + } + ], + "time": "2014-03-28 09:21:30" + }, + { + "name": "phpdocumentor/template-abstract", + "version": "1.2.1", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/template.abstract.git", + "reference": "43fa2db351d7a150803397721e778f9dd8a20b47" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/template.abstract/zipball/43fa2db351d7a150803397721e778f9dd8a20b47", + "reference": "43fa2db351d7a150803397721e778f9dd8a20b47", + "shasum": "" + }, + "require": { + "ext-xsl": "*", + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Simple bright template for phpDocumentor", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "documentation", + "phpdoc", + "template" + ], + "time": "2013-08-02 06:11:13" + }, + { + "name": "phpdocumentor/template-checkstyle", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/template.checkstyle.git", + "reference": "22a45684e737c8c3ec3f1a12edb7743b7a82ac8b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/template.checkstyle/zipball/22a45684e737c8c3ec3f1a12edb7743b7a82ac8b", + "reference": "22a45684e737c8c3ec3f1a12edb7743b7a82ac8b", + "shasum": "" + }, + "require": { + "ext-xsl": "*", + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Checkstyle XML output template for phpDocumentor2", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "documentation", + "phpdoc", + "template" + ], + "time": "2013-08-01 19:43:19" + }, + { + "name": "phpdocumentor/template-clean", + "version": "1.0.4", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/template.clean.git", + "reference": "78f2048c5ecd62f0b79dbac093687d78a66d1806" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/template.clean/zipball/78f2048c5ecd62f0b79dbac093687d78a66d1806", + "reference": "78f2048c5ecd62f0b79dbac093687d78a66d1806", + "shasum": "" + }, + "require": { + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A clean, responsive modern template for phpDocumentor for Twig aimed at usability", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "documentation", + "phpdoc", + "responsive", + "template" + ], + "time": "2014-03-29 08:22:15" + }, + { + "name": "phpdocumentor/template-new-black", + "version": "1.3.1", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/template.new_black.git", + "reference": "be38beba2b2674be292f32f88efe8a60c658a139" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/template.new_black/zipball/be38beba2b2674be292f32f88efe8a60c658a139", + "reference": "be38beba2b2674be292f32f88efe8a60c658a139", + "shasum": "" + }, + "require": { + "ext-xsl": "*", + "phpdocumentor/template-abstract": "1.*", + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Web 2.0 template with dark sidebar for phpDocumentor", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "documentation", + "phpdoc", + "template" + ], + "time": "2013-08-02 06:16:30" + }, + { + "name": "phpdocumentor/template-old-ocean", + "version": "1.3.1", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/template.old_ocean.git", + "reference": "3a0e2bcced4045a694d53b4607aad04e99d78489" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/template.old_ocean/zipball/3a0e2bcced4045a694d53b4607aad04e99d78489", + "reference": "3a0e2bcced4045a694d53b4607aad04e99d78489", + "shasum": "" + }, + "require": { + "ext-xsl": "*", + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Blue template with high contrast for the foreground", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "documentation", + "phpdoc", + "template" + ], + "time": "2013-08-02 06:21:07" + }, + { + "name": "phpdocumentor/template-responsive", + "version": "1.3.3", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/template.responsive.git", + "reference": "26f895a2ed3148e1686ae4d802f65a3ef04c04e1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/template.responsive/zipball/26f895a2ed3148e1686ae4d802f65a3ef04c04e1", + "reference": "26f895a2ed3148e1686ae4d802f65a3ef04c04e1", + "shasum": "" + }, + "require": { + "ext-xsl": "*", + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Responsive modern template for phpDocumentor", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "documentation", + "phpdoc", + "template" + ], + "time": "2014-03-29 08:55:54" + }, + { + "name": "phpdocumentor/template-responsive-twig", + "version": "1.2.3", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/template.responsive-twig.git", + "reference": "cd6d82be6a4626d865fd01d40aad170cea08db0a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/template.responsive-twig/zipball/cd6d82be6a4626d865fd01d40aad170cea08db0a", + "reference": "cd6d82be6a4626d865fd01d40aad170cea08db0a", + "shasum": "" + }, + "require": { + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Responsive modern template for phpDocumentor for Twig", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "documentation", + "phpdoc", + "template" + ], + "time": "2014-03-30 21:02:00" + }, + { + "name": "phpdocumentor/template-xml", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/mvriel/template.xml.git", + "reference": "a372713be8ee99b16497e2580592e474ff51190c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/mvriel/template.xml/zipball/a372713be8ee99b16497e2580592e474ff51190c", + "reference": "a372713be8ee99b16497e2580592e474ff51190c", + "shasum": "" + }, + "require": { + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Generates an XML representation of the project's structure", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "documentation", + "phpdoc", + "template" + ], + "time": "2013-08-01 20:23:32" + }, + { + "name": "phpdocumentor/template-zend", + "version": "1.3.2", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/template.zend.git", + "reference": "75913288bfd73d3bf4c1b1179c3963f3431e7a9d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/template.zend/zipball/75913288bfd73d3bf4c1b1179c3963f3431e7a9d", + "reference": "75913288bfd73d3bf4c1b1179c3963f3431e7a9d", + "shasum": "" + }, + "require": { + "ext-xsl": "*", + "phpdocumentor/template-abstract": "1.*", + "phpdocumentor/unified-asset-installer": "~1.1" + }, + "type": "phpdocumentor-template", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Official Zend Framework Template for phpDocumentor2", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "ZendFramework", + "documentation", + "phpdoc", + "template", + "zend", + "zf" + ], + "time": "2013-12-05 08:51:57" + }, + { + "name": "phpdocumentor/unified-asset-installer", + "version": "1.1.2", + "source": { + "type": "git", + "url": "https://github.com/phpDocumentor/UnifiedAssetInstaller.git", + "reference": "241fb036268cd9da7d76da3db66e3eda66259c52" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpDocumentor/UnifiedAssetInstaller/zipball/241fb036268cd9da7d76da3db66e3eda66259c52", + "reference": "241fb036268cd9da7d76da3db66e3eda66259c52", + "shasum": "" + }, + "require": { + "composer-plugin-api": "1.0.0" + }, + "require-dev": { + "composer/composer": "~1.0@dev", + "phpunit/phpunit": "~3.7" + }, + "type": "composer-installer", + "extra": { + "class": "\\phpDocumentor\\Composer\\UnifiedAssetInstaller" + }, + "autoload": { + "psr-0": { + "phpDocumentor\\Composer": [ + "src/", + "test/unit/" + ] + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Asset installer for phpDocumentor", + "homepage": "http://www.phpdoc.org", + "keywords": [ + "assets", + "installer", + "plugins", + "templates" + ], + "time": "2013-09-09 06:13:02" + }, + { + "name": "phploc/phploc", + "version": "2.0.5", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/phploc.git", + "reference": "d177c22e2a08e448f7bdfa762045f7bd086834d7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/phploc/zipball/d177c22e2a08e448f7bdfa762045f7bd086834d7", + "reference": "d177c22e2a08e448f7bdfa762045f7bd086834d7", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "sebastian/finder-facade": ">=1.1.0", + "sebastian/git": ">=1.0.0", + "sebastian/version": ">=1.0.3", + "symfony/console": ">=2.2.0" + }, + "bin": [ + "phploc" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "A tool for quickly measuring the size of a PHP project.", + "homepage": "https://github.com/sebastianbergmann/phploc", + "time": "2014-04-27 06:47:27" + }, + { + "name": "phpmd/phpmd", + "version": "2.0.0", + "source": { + "type": "git", + "url": "https://github.com/phpmd/phpmd.git", + "reference": "68ced5452910d3555a38720bd87f5f2356c5a003" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpmd/phpmd/zipball/68ced5452910d3555a38720bd87f5f2356c5a003", + "reference": "68ced5452910d3555a38720bd87f5f2356c5a003", + "shasum": "" + }, + "require": { + "pdepend/pdepend": "2.0.*", + "php": ">=5.3.0", + "symfony/config": "@stable", + "symfony/dependency-injection": "@stable", + "symfony/filesystem": "@stable" + }, + "bin": [ + "src/bin/phpmd" + ], + "type": "library", + "autoload": { + "psr-0": { + "PHPMD\\": "src/main/php", + "PDepend\\": "vendor/pdepend/pdepend/src/main/php/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "../../pdepend/pdepend/src/main/php", + "src/main/php" + ], + "license": [ + "BSD-3-Clause" + ], + "description": "Official version of PHPMD handled with Composer.", + "time": "2014-05-21 12:45:23" + }, + { + "name": "phpoption/phpoption", + "version": "1.4.0", + "source": { + "type": "git", + "url": "https://github.com/schmittjoh/php-option.git", + "reference": "5d099bcf0393908bf4ad69cc47dafb785d51f7f5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/schmittjoh/php-option/zipball/5d099bcf0393908bf4ad69cc47dafb785d51f7f5", + "reference": "5d099bcf0393908bf4ad69cc47dafb785d51f7f5", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.3-dev" + } + }, + "autoload": { + "psr-0": { + "PhpOption\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache2" + ], + "authors": [ + { + "name": "Johannes M. Schmitt", + "email": "schmittjoh@gmail.com", + "homepage": "http://jmsyst.com", + "role": "Developer of wrapped JMSSerializerBundle" + } + ], + "description": "Option Type for PHP", + "keywords": [ + "language", + "option", + "php", + "type" + ], + "time": "2014-01-09 22:37:17" + }, + { + "name": "phpunit/php-code-coverage", + "version": "1.2.17", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-code-coverage.git", + "reference": "6ef2bf3a1c47eca07ea95f0d8a902a6340390b34" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/6ef2bf3a1c47eca07ea95f0d8a902a6340390b34", + "reference": "6ef2bf3a1c47eca07ea95f0d8a902a6340390b34", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "phpunit/php-file-iterator": ">=1.3.0@stable", + "phpunit/php-text-template": ">=1.2.0@stable", + "phpunit/php-token-stream": ">=1.1.3@stable" + }, + "require-dev": { + "phpunit/phpunit": "3.7.*@dev" + }, + "suggest": { + "ext-dom": "*", + "ext-xdebug": ">=2.0.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.2.x-dev" + } + }, + "autoload": { + "classmap": [ + "PHP/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "" + ], + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sb@sebastian-bergmann.de", + "role": "lead" + } + ], + "description": "Library that provides collection, processing, and rendering functionality for PHP code coverage information.", + "homepage": "https://github.com/sebastianbergmann/php-code-coverage", + "keywords": [ + "coverage", + "testing", + "xunit" + ], + "time": "2014-03-28 10:53:45" + }, + { + "name": "phpunit/php-file-iterator", + "version": "1.3.4", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-file-iterator.git", + "reference": "acd690379117b042d1c8af1fafd61bde001bf6bb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/acd690379117b042d1c8af1fafd61bde001bf6bb", + "reference": "acd690379117b042d1c8af1fafd61bde001bf6bb", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "autoload": { + "classmap": [ + "File/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "" + ], + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sb@sebastian-bergmann.de", + "role": "lead" + } + ], + "description": "FilterIterator implementation that filters files based on a list of suffixes.", + "homepage": "https://github.com/sebastianbergmann/php-file-iterator/", + "keywords": [ + "filesystem", + "iterator" + ], + "time": "2013-10-10 15:34:57" + }, + { + "name": "phpunit/php-text-template", + "version": "1.2.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-text-template.git", + "reference": "206dfefc0ffe9cebf65c413e3d0e809c82fbf00a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/206dfefc0ffe9cebf65c413e3d0e809c82fbf00a", + "reference": "206dfefc0ffe9cebf65c413e3d0e809c82fbf00a", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "autoload": { + "classmap": [ + "Text/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "" + ], + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sb@sebastian-bergmann.de", + "role": "lead" + } + ], + "description": "Simple template engine.", + "homepage": "https://github.com/sebastianbergmann/php-text-template/", + "keywords": [ + "template" + ], + "time": "2014-01-30 17:20:04" + }, + { + "name": "phpunit/php-timer", + "version": "1.0.5", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-timer.git", + "reference": "19689d4354b295ee3d8c54b4f42c3efb69cbc17c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-timer/zipball/19689d4354b295ee3d8c54b4f42c3efb69cbc17c", + "reference": "19689d4354b295ee3d8c54b4f42c3efb69cbc17c", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "autoload": { + "classmap": [ + "PHP/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "" + ], + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sb@sebastian-bergmann.de", + "role": "lead" + } + ], + "description": "Utility class for timing", + "homepage": "https://github.com/sebastianbergmann/php-timer/", + "keywords": [ + "timer" + ], + "time": "2013-08-02 07:42:54" + }, + { + "name": "phpunit/php-token-stream", + "version": "1.2.2", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/php-token-stream.git", + "reference": "ad4e1e23ae01b483c16f600ff1bebec184588e32" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/ad4e1e23ae01b483c16f600ff1bebec184588e32", + "reference": "ad4e1e23ae01b483c16f600ff1bebec184588e32", + "shasum": "" + }, + "require": { + "ext-tokenizer": "*", + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.2-dev" + } + }, + "autoload": { + "classmap": [ + "PHP/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "" + ], + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sb@sebastian-bergmann.de", + "role": "lead" + } + ], + "description": "Wrapper around PHP's tokenizer extension.", + "homepage": "https://github.com/sebastianbergmann/php-token-stream/", + "keywords": [ + "tokenizer" + ], + "time": "2014-03-03 05:10:30" + }, + { + "name": "phpunit/phpunit", + "version": "3.7.37", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/phpunit.git", + "reference": "ae6cefd7cc84586a5ef27e04bae11ee940ec63dc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/ae6cefd7cc84586a5ef27e04bae11ee940ec63dc", + "reference": "ae6cefd7cc84586a5ef27e04bae11ee940ec63dc", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "ext-dom": "*", + "ext-json": "*", + "ext-pcre": "*", + "ext-reflection": "*", + "ext-spl": "*", + "php": ">=5.3.3", + "phpunit/php-code-coverage": "~1.2", + "phpunit/php-file-iterator": "~1.3", + "phpunit/php-text-template": "~1.1", + "phpunit/php-timer": "~1.0", + "phpunit/phpunit-mock-objects": "~1.2", + "symfony/yaml": "~2.0" + }, + "require-dev": { + "pear-pear.php.net/pear": "1.9.4" + }, + "suggest": { + "phpunit/php-invoker": "~1.1" + }, + "bin": [ + "composer/bin/phpunit" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.7.x-dev" + } + }, + "autoload": { + "classmap": [ + "PHPUnit/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "", + "../../symfony/yaml/" + ], + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "The PHP Unit Testing framework.", + "homepage": "http://www.phpunit.de/", + "keywords": [ + "phpunit", + "testing", + "xunit" + ], + "time": "2014-04-30 12:24:19" + }, + { + "name": "phpunit/phpunit-mock-objects", + "version": "1.2.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/phpunit-mock-objects.git", + "reference": "5794e3c5c5ba0fb037b11d8151add2a07fa82875" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/5794e3c5c5ba0fb037b11d8151add2a07fa82875", + "reference": "5794e3c5c5ba0fb037b11d8151add2a07fa82875", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "phpunit/php-text-template": ">=1.1.1@stable" + }, + "suggest": { + "ext-soap": "*" + }, + "type": "library", + "autoload": { + "classmap": [ + "PHPUnit/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "include-path": [ + "" + ], + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sb@sebastian-bergmann.de", + "role": "lead" + } + ], + "description": "Mock Object library for PHPUnit", + "homepage": "https://github.com/sebastianbergmann/phpunit-mock-objects/", + "keywords": [ + "mock", + "xunit" + ], + "time": "2013-01-13 10:24:48" + }, + { + "name": "pimple/pimple", + "version": "v1.1.1", + "source": { + "type": "git", + "url": "https://github.com/fabpot/Pimple.git", + "reference": "2019c145fe393923f3441b23f29bbdfaa5c58c4d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/fabpot/Pimple/zipball/2019c145fe393923f3441b23f29bbdfaa5c58c4d", + "reference": "2019c145fe393923f3441b23f29bbdfaa5c58c4d", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.1.x-dev" + } + }, + "autoload": { + "psr-0": { + "Pimple": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + } + ], + "description": "Pimple is a simple Dependency Injection Container for PHP 5.3", + "homepage": "http://pimple.sensiolabs.org", + "keywords": [ + "container", + "dependency injection" + ], + "time": "2013-11-22 08:30:29" + }, + { + "name": "psr/log", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "fe0936ee26643249e916849d48e3a51d5f5e278b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/fe0936ee26643249e916849d48e3a51d5f5e278b", + "reference": "fe0936ee26643249e916849d48e3a51d5f5e278b", + "shasum": "" + }, + "type": "library", + "autoload": { + "psr-0": { + "Psr\\Log\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "time": "2012-12-21 11:40:51" + }, + { + "name": "sebastian/finder-facade", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/finder-facade.git", + "reference": "1e396fda3449fce9df032749fa4fa2619e0347e0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/finder-facade/zipball/1e396fda3449fce9df032749fa4fa2619e0347e0", + "reference": "1e396fda3449fce9df032749fa4fa2619e0347e0", + "shasum": "" + }, + "require": { + "symfony/finder": ">=2.2.0", + "theseer/fdomdocument": ">=1.3.1" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "FinderFacade is a convenience wrapper for Symfony's Finder component.", + "homepage": "https://github.com/sebastianbergmann/finder-facade", + "time": "2013-05-28 06:10:03" + }, + { + "name": "sebastian/git", + "version": "2.0.0", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/git.git", + "reference": "572c35353fefcc8607d6fef0e362a9f3a5e84d96" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/git/zipball/572c35353fefcc8607d6fef0e362a9f3a5e84d96", + "reference": "572c35353fefcc8607d6fef0e362a9f3a5e84d96", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Simple wrapper for Git", + "homepage": "http://www.github.com/sebastianbergmann/git", + "keywords": [ + "git" + ], + "time": "2014-06-14 07:12:53" + }, + { + "name": "sebastian/phpcpd", + "version": "2.0.1", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/phpcpd.git", + "reference": "a9462153f2dd90466a010179901d31fbff598365" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/phpcpd/zipball/a9462153f2dd90466a010179901d31fbff598365", + "reference": "a9462153f2dd90466a010179901d31fbff598365", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "phpunit/php-timer": ">=1.0.4", + "sebastian/finder-facade": ">=1.1.0", + "sebastian/version": ">=1.0.3", + "symfony/console": ">=2.2.0", + "theseer/fdomdocument": "~1.4" + }, + "bin": [ + "phpcpd" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0-dev" + } + }, + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Copy/Paste Detector (CPD) for PHP code.", + "homepage": "https://github.com/sebastianbergmann/phpcpd", + "time": "2014-03-31 09:25:30" + }, + { + "name": "sebastian/version", + "version": "1.0.3", + "source": { + "type": "git", + "url": "https://github.com/sebastianbergmann/version.git", + "reference": "b6e1f0cf6b9e1ec409a0d3e2f2a5fb0998e36b43" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/sebastianbergmann/version/zipball/b6e1f0cf6b9e1ec409a0d3e2f2a5fb0998e36b43", + "reference": "b6e1f0cf6b9e1ec409a0d3e2f2a5fb0998e36b43", + "shasum": "" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de", + "role": "lead" + } + ], + "description": "Library that helps with managing the version number of Git-hosted PHP projects", + "homepage": "https://github.com/sebastianbergmann/version", + "time": "2014-03-07 15:35:33" + }, + { + "name": "squizlabs/php_codesniffer", + "version": "1.5.3", + "source": { + "type": "git", + "url": "https://github.com/squizlabs/PHP_CodeSniffer.git", + "reference": "396178ada8499ec492363587f037125bf7b07fcc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/396178ada8499ec492363587f037125bf7b07fcc", + "reference": "396178ada8499ec492363587f037125bf7b07fcc", + "shasum": "" + }, + "require": { + "ext-tokenizer": "*", + "php": ">=5.1.2" + }, + "suggest": { + "phpunit/php-timer": "dev-master" + }, + "bin": [ + "scripts/phpcs" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-phpcs-fixer": "2.0.x-dev" + } + }, + "autoload": { + "classmap": [ + "CodeSniffer.php", + "CodeSniffer/CLI.php", + "CodeSniffer/Exception.php", + "CodeSniffer/File.php", + "CodeSniffer/Report.php", + "CodeSniffer/Reporting.php", + "CodeSniffer/Sniff.php", + "CodeSniffer/Tokens.php", + "CodeSniffer/Reports/", + "CodeSniffer/CommentParser/", + "CodeSniffer/Tokenizers/", + "CodeSniffer/DocGenerators/", + "CodeSniffer/Standards/AbstractPatternSniff.php", + "CodeSniffer/Standards/AbstractScopeSniff.php", + "CodeSniffer/Standards/AbstractVariableSniff.php", + "CodeSniffer/Standards/IncorrectPatternException.php", + "CodeSniffer/Standards/Generic/Sniffs/", + "CodeSniffer/Standards/MySource/Sniffs/", + "CodeSniffer/Standards/PEAR/Sniffs/", + "CodeSniffer/Standards/PSR1/Sniffs/", + "CodeSniffer/Standards/PSR2/Sniffs/", + "CodeSniffer/Standards/Squiz/Sniffs/", + "CodeSniffer/Standards/Zend/Sniffs/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Greg Sherwood", + "role": "lead" + } + ], + "description": "PHP_CodeSniffer tokenises PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.", + "homepage": "http://www.squizlabs.com/php-codesniffer", + "keywords": [ + "phpcs", + "standards" + ], + "time": "2014-05-01 03:07:07" + }, + { + "name": "symfony/config", + "version": "v2.5.0", + "target-dir": "Symfony/Component/Config", + "source": { + "type": "git", + "url": "https://github.com/symfony/Config.git", + "reference": "9c8caadb38ecc69ac35ab31af4d1996944b5a09f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Config/zipball/9c8caadb38ecc69ac35ab31af4d1996944b5a09f", + "reference": "9c8caadb38ecc69ac35ab31af4d1996944b5a09f", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "symfony/filesystem": "~2.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.5-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Config\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Config Component", + "homepage": "http://symfony.com", + "time": "2014-04-22 08:11:23" + }, + { + "name": "symfony/console", + "version": "v2.5.0", + "target-dir": "Symfony/Component/Console", + "source": { + "type": "git", + "url": "https://github.com/symfony/Console.git", + "reference": "ef4ca73b0b3a10cbac653d3ca482d0cdd4502b2c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Console/zipball/ef4ca73b0b3a10cbac653d3ca482d0cdd4502b2c", + "reference": "ef4ca73b0b3a10cbac653d3ca482d0cdd4502b2c", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "psr/log": "~1.0", + "symfony/event-dispatcher": "~2.1" + }, + "suggest": { + "psr/log": "For using the console logger", + "symfony/event-dispatcher": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.5-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Console\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Console Component", + "homepage": "http://symfony.com", + "time": "2014-05-22 08:54:24" + }, + { + "name": "symfony/dependency-injection", + "version": "v2.5.0", + "target-dir": "Symfony/Component/DependencyInjection", + "source": { + "type": "git", + "url": "https://github.com/symfony/DependencyInjection.git", + "reference": "5dfb4c2b74c4976efe1efa783370da656a2dd742" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/DependencyInjection/zipball/5dfb4c2b74c4976efe1efa783370da656a2dd742", + "reference": "5dfb4c2b74c4976efe1efa783370da656a2dd742", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "symfony/config": "~2.2", + "symfony/expression-language": "~2.4", + "symfony/yaml": "~2.0" + }, + "suggest": { + "symfony/config": "", + "symfony/proxy-manager-bridge": "Generate service proxies to lazy load them", + "symfony/yaml": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.5-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\DependencyInjection\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony DependencyInjection Component", + "homepage": "http://symfony.com", + "time": "2014-05-12 09:28:39" + }, + { + "name": "symfony/event-dispatcher", + "version": "v2.5.0", + "target-dir": "Symfony/Component/EventDispatcher", + "source": { + "type": "git", + "url": "https://github.com/symfony/EventDispatcher.git", + "reference": "cb62ec8dd05893fc8e4f0e6e21e326e1fc731fe8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/EventDispatcher/zipball/cb62ec8dd05893fc8e4f0e6e21e326e1fc731fe8", + "reference": "cb62ec8dd05893fc8e4f0e6e21e326e1fc731fe8", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "psr/log": "~1.0", + "symfony/config": "~2.0", + "symfony/dependency-injection": "~2.0", + "symfony/stopwatch": "~2.2" + }, + "suggest": { + "symfony/dependency-injection": "", + "symfony/http-kernel": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.5-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\EventDispatcher\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony EventDispatcher Component", + "homepage": "http://symfony.com", + "time": "2014-04-29 10:13:57" + }, + { + "name": "symfony/filesystem", + "version": "v2.5.0", + "target-dir": "Symfony/Component/Filesystem", + "source": { + "type": "git", + "url": "https://github.com/symfony/Filesystem.git", + "reference": "98e831eac836a0a5911626ce82684155f21d0e4d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Filesystem/zipball/98e831eac836a0a5911626ce82684155f21d0e4d", + "reference": "98e831eac836a0a5911626ce82684155f21d0e4d", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.5-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Filesystem\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Filesystem Component", + "homepage": "http://symfony.com", + "time": "2014-04-16 10:36:21" + }, + { + "name": "symfony/finder", + "version": "v2.5.0", + "target-dir": "Symfony/Component/Finder", + "source": { + "type": "git", + "url": "https://github.com/symfony/Finder.git", + "reference": "307aad2c541bbdf43183043645e186ef2cd6b973" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Finder/zipball/307aad2c541bbdf43183043645e186ef2cd6b973", + "reference": "307aad2c541bbdf43183043645e186ef2cd6b973", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.5-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Finder\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Finder Component", + "homepage": "http://symfony.com", + "time": "2014-05-22 13:47:45" + }, + { + "name": "symfony/process", + "version": "v2.5.0", + "target-dir": "Symfony/Component/Process", + "source": { + "type": "git", + "url": "https://github.com/symfony/Process.git", + "reference": "5d7d78e23894544740219e006320678cfa4cd45b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Process/zipball/5d7d78e23894544740219e006320678cfa4cd45b", + "reference": "5d7d78e23894544740219e006320678cfa4cd45b", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.5-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Process\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Process Component", + "homepage": "http://symfony.com", + "time": "2014-05-23 09:02:52" + }, + { + "name": "symfony/stopwatch", + "version": "v2.5.0", + "target-dir": "Symfony/Component/Stopwatch", + "source": { + "type": "git", + "url": "https://github.com/symfony/Stopwatch.git", + "reference": "724d73604ebe6c1c9bdf36533b556123bd9075a1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Stopwatch/zipball/724d73604ebe6c1c9bdf36533b556123bd9075a1", + "reference": "724d73604ebe6c1c9bdf36533b556123bd9075a1", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.5-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Stopwatch\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Stopwatch Component", + "homepage": "http://symfony.com", + "time": "2014-04-18 20:40:13" + }, + { + "name": "symfony/translation", + "version": "v2.5.0", + "target-dir": "Symfony/Component/Translation", + "source": { + "type": "git", + "url": "https://github.com/symfony/Translation.git", + "reference": "5f23265dcf8927a84be832608069c9edca3cf5f4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Translation/zipball/5f23265dcf8927a84be832608069c9edca3cf5f4", + "reference": "5f23265dcf8927a84be832608069c9edca3cf5f4", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "require-dev": { + "symfony/config": "~2.0", + "symfony/yaml": "~2.2" + }, + "suggest": { + "symfony/config": "", + "symfony/yaml": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.5-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Translation\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Translation Component", + "homepage": "http://symfony.com", + "time": "2014-05-22 13:47:45" + }, + { + "name": "symfony/validator", + "version": "v2.5.0", + "target-dir": "Symfony/Component/Validator", + "source": { + "type": "git", + "url": "https://github.com/symfony/Validator.git", + "reference": "62f6f7735fbd3897b9347ae60fda4a40d0122640" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Validator/zipball/62f6f7735fbd3897b9347ae60fda4a40d0122640", + "reference": "62f6f7735fbd3897b9347ae60fda4a40d0122640", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "symfony/translation": "~2.0" + }, + "require-dev": { + "doctrine/annotations": "~1.0", + "doctrine/cache": "~1.0", + "egulias/email-validator": "~1.0", + "symfony/config": "~2.2", + "symfony/expression-language": "~2.4", + "symfony/http-foundation": "~2.1", + "symfony/intl": "~2.3", + "symfony/property-access": "~2.2", + "symfony/yaml": "~2.0" + }, + "suggest": { + "doctrine/annotations": "For using the annotation mapping. You will also need doctrine/cache.", + "doctrine/cache": "For using the default cached annotation reader and metadata cache.", + "egulias/email-validator": "Strict (RFC compliant) email validation", + "symfony/config": "", + "symfony/expression-language": "For using the 2.4 Expression validator", + "symfony/http-foundation": "", + "symfony/intl": "", + "symfony/property-access": "For using the 2.4 Validator API", + "symfony/yaml": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.5-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Validator\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Validator Component", + "homepage": "http://symfony.com", + "time": "2014-05-31 02:02:56" + }, + { + "name": "symfony/yaml", + "version": "v2.5.0", + "target-dir": "Symfony/Component/Yaml", + "source": { + "type": "git", + "url": "https://github.com/symfony/Yaml.git", + "reference": "b4b09c68ec2f2727574544ef0173684281a5033c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/Yaml/zipball/b4b09c68ec2f2727574544ef0173684281a5033c", + "reference": "b4b09c68ec2f2727574544ef0173684281a5033c", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.5-dev" + } + }, + "autoload": { + "psr-0": { + "Symfony\\Component\\Yaml\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Symfony Community", + "homepage": "http://symfony.com/contributors" + } + ], + "description": "Symfony Yaml Component", + "homepage": "http://symfony.com", + "time": "2014-05-16 14:25:18" + }, + { + "name": "tecnick.com/tcpdf", + "version": "6.0.086", + "source": { + "type": "git", + "url": "git://git.code.sf.net/p/tcpdf/code", + "reference": "b1c0cc74a84948029d8c9824736d9021871a63a7" + }, + "require": { + "php": ">=5.3.0" + }, + "type": "library", + "autoload": { + "classmap": [ + "fonts", + "config", + "include", + "tcpdf.php", + "tcpdf_parser.php", + "tcpdf_import.php", + "tcpdf_barcodes_1d.php", + "tcpdf_barcodes_2d.php", + "include/tcpdf_colors.php", + "include/tcpdf_filters.php", + "include/tcpdf_font_data.php", + "include/tcpdf_fonts.php", + "include/tcpdf_images.php", + "include/tcpdf_static.php", + "include/barcodes/datamatrix.php", + "include/barcodes/pdf417.php", + "include/barcodes/qrcode.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPLv3" + ], + "authors": [ + { + "name": "Nicola Asuni", + "email": "info@tecnick.com", + "homepage": "http://nicolaasuni.tecnick.com" + } + ], + "description": "TCPDF is a PHP class for generating PDF documents.", + "homepage": "http://www.tcpdf.org/", + "keywords": [ + "PDFD32000-2008", + "TCPDF", + "barcodes", + "datamatrix", + "pdf", + "pdf417", + "qrcode" + ], + "time": "2014-06-20 15:28:34" + }, + { + "name": "theseer/fdomdocument", + "version": "1.5.0", + "source": { + "type": "git", + "url": "https://github.com/theseer/fDOMDocument.git", + "reference": "137aa3b13bef05b4e301899cbabdaf7d501847d2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/theseer/fDOMDocument/zipball/137aa3b13bef05b4e301899cbabdaf7d501847d2", + "reference": "137aa3b13bef05b4e301899cbabdaf7d501847d2", + "shasum": "" + }, + "require": { + "ext-dom": "*", + "lib-libxml": "*", + "php": ">=5.3.3" + }, + "type": "library", + "autoload": { + "classmap": [ + "src/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Arne Blankerts", + "email": "arne@blankerts.de", + "role": "lead" + } + ], + "description": "The classes contained within this repository extend the standard DOM to use exceptions at all occasions of errors instead of PHP warnings or notices. They also add various custom methods and shortcuts for convenience and to simplify the usage of DOM.", + "homepage": "https://github.com/theseer/fDOMDocument", + "time": "2014-02-19 00:20:43" + }, + { + "name": "twig/twig", + "version": "v1.15.1", + "source": { + "type": "git", + "url": "https://github.com/fabpot/Twig.git", + "reference": "1fb5784662f438d7d96a541e305e28b812e2eeed" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/fabpot/Twig/zipball/1fb5784662f438d7d96a541e305e28b812e2eeed", + "reference": "1fb5784662f438d7d96a541e305e28b812e2eeed", + "shasum": "" + }, + "require": { + "php": ">=5.2.4" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.15-dev" + } + }, + "autoload": { + "psr-0": { + "Twig_": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Armin Ronacher2", + "email": "armin.ronacher@active-4.com", + "role": "Project Founder" + }, + { + "name": "Twig Team", + "homepage": "https://github.com/fabpot/Twig/graphs/contributors", + "role": "Contributors" + } + ], + "description": "Twig, the flexible, fast, and secure template language for PHP", + "homepage": "http://twig.sensiolabs.org", + "keywords": [ + "templating" + ], + "time": "2014-02-13 10:19:29" + }, + { + "name": "zendframework/zend-cache", + "version": "2.1.6", + "target-dir": "Zend/Cache", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendCache.git", + "reference": "560355160f06cdc3ef549a7eef843af3bead7e39" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendCache/zipball/560355160f06cdc3ef549a7eef843af3bead7e39", + "reference": "560355160f06cdc3ef549a7eef843af3bead7e39", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "zendframework/zend-eventmanager": "self.version", + "zendframework/zend-servicemanager": "self.version", + "zendframework/zend-stdlib": "self.version" + }, + "require-dev": { + "zendframework/zend-serializer": "self.version" + }, + "suggest": { + "ext-apc": "APC >= 3.1.6 to use the APC storage adapter", + "ext-dba": "DBA, to use the DBA storage adapter", + "ext-memcached": "Memcached >= 1.0.0 to use the Memcached storage adapter", + "ext-wincache": "WinCache, to use the WinCache storage adapter", + "zendframework/zend-serializer": "Zend\\Serializer component", + "zendframework/zend-session": "Zend\\Session component" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\Cache\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "provides a generic way to cache any data", + "keywords": [ + "cache", + "zf2" + ], + "time": "2014-03-03 23:00:17" + }, + { + "name": "zendframework/zend-config", + "version": "2.1.6", + "target-dir": "Zend/Config", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendConfig.git", + "reference": "a31c3980cf7ec88418a931e9cf4ba21079f47a08" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendConfig/zipball/a31c3980cf7ec88418a931e9cf4ba21079f47a08", + "reference": "a31c3980cf7ec88418a931e9cf4ba21079f47a08", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "zendframework/zend-stdlib": "self.version" + }, + "suggest": { + "zendframework/zend-json": "Zend\\Json to use the Json reader or writer classes", + "zendframework/zend-servicemanager": "Zend\\ServiceManager for use with the Config Factory to retrieve reader and writer instances" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\Config\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "provides a nested object property based user interface for accessing this configuration data within application code", + "keywords": [ + "config", + "zf2" + ], + "time": "2014-01-02 18:00:10" + }, + { + "name": "zendframework/zend-eventmanager", + "version": "2.1.6", + "target-dir": "Zend/EventManager", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendEventManager.git", + "reference": "89368704bb37303fba64c3ddd6bce0506aa7187c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendEventManager/zipball/89368704bb37303fba64c3ddd6bce0506aa7187c", + "reference": "89368704bb37303fba64c3ddd6bce0506aa7187c", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "zendframework/zend-stdlib": "self.version" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\EventManager\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "keywords": [ + "eventmanager", + "zf2" + ], + "time": "2014-01-04 13:00:14" + }, + { + "name": "zendframework/zend-filter", + "version": "2.1.6", + "target-dir": "Zend/Filter", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendFilter.git", + "reference": "8ceece474b29d079e86976dbd3efffe6064b3d72" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendFilter/zipball/8ceece474b29d079e86976dbd3efffe6064b3d72", + "reference": "8ceece474b29d079e86976dbd3efffe6064b3d72", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "zendframework/zend-stdlib": "self.version" + }, + "require-dev": { + "zendframework/zend-crypt": "self.version" + }, + "suggest": { + "zendframework/zend-crypt": "Zend\\Crypt component", + "zendframework/zend-i18n": "Zend\\I18n component", + "zendframework/zend-uri": "Zend\\Uri component for UriNormalize filter", + "zendframework/zend-validator": "Zend\\Validator component" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\Filter\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "provides a set of commonly needed data filters", + "keywords": [ + "filter", + "zf2" + ], + "time": "2014-03-03 21:00:06" + }, + { + "name": "zendframework/zend-i18n", + "version": "2.1.6", + "target-dir": "Zend/I18n", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendI18n.git", + "reference": "10f56e0869761d62699782e4dd04eb77262cc353" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendI18n/zipball/10f56e0869761d62699782e4dd04eb77262cc353", + "reference": "10f56e0869761d62699782e4dd04eb77262cc353", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "zendframework/zend-stdlib": "self.version" + }, + "suggest": { + "ext-intl": "Required for most features of Zend\\I18n; included in default builds of PHP", + "zendframework/zend-eventmanager": "You should install this package to use the events in the translator", + "zendframework/zend-filter": "You should install this package to use the provided filters", + "zendframework/zend-resources": "Translation resources", + "zendframework/zend-validator": "You should install this package to use the provided validators", + "zendframework/zend-view": "You should install this package to use the provided view helpers" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\I18n\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "keywords": [ + "i18n", + "zf2" + ], + "time": "2014-01-04 13:00:19" + }, + { + "name": "zendframework/zend-json", + "version": "2.1.6", + "target-dir": "Zend/Json", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendJson.git", + "reference": "dd8a8239a7c08c7449a6ea219da3e2369bd90d92" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendJson/zipball/dd8a8239a7c08c7449a6ea219da3e2369bd90d92", + "reference": "dd8a8239a7c08c7449a6ea219da3e2369bd90d92", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "zendframework/zend-stdlib": "self.version" + }, + "suggest": { + "zendframework/zend-server": "Zend\\Server component" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\Json\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "provides convenience methods for serializing native PHP to JSON and decoding JSON to native PHP", + "keywords": [ + "json", + "zf2" + ], + "time": "2014-03-06 18:00:05" + }, + { + "name": "zendframework/zend-math", + "version": "2.1.6", + "target-dir": "Zend/Math", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendMath.git", + "reference": "b982ee2edafd4075b22372596ab2e2fdd0f6424e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendMath/zipball/b982ee2edafd4075b22372596ab2e2fdd0f6424e", + "reference": "b982ee2edafd4075b22372596ab2e2fdd0f6424e", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "ext-bcmath": "If using the bcmath functionality", + "ext-gmp": "If using the gmp functionality", + "ircmaxell/random-lib": "Fallback random byte generator for Zend\\Math\\Rand if OpenSSL/Mcrypt extensions are unavailable", + "zendframework/zend-servicemanager": ">= current version, if using the BigInteger::factory functionality" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\Math\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "keywords": [ + "math", + "zf2" + ], + "time": "2014-03-05 18:00:06" + }, + { + "name": "zendframework/zend-serializer", + "version": "2.1.6", + "target-dir": "Zend/Serializer", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendSerializer.git", + "reference": "d76b931d3ffa842a496c9fa319bbe285b5ddfade" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendSerializer/zipball/d76b931d3ffa842a496c9fa319bbe285b5ddfade", + "reference": "d76b931d3ffa842a496c9fa319bbe285b5ddfade", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "zendframework/zend-json": "self.version", + "zendframework/zend-math": "self.version", + "zendframework/zend-stdlib": "self.version" + }, + "suggest": { + "zendframework/zend-servicemanager": "To support plugin manager support" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\Serializer\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "description": "provides an adapter based interface to simply generate storable representation of PHP types by different facilities, and recover", + "keywords": [ + "serializer", + "zf2" + ], + "time": "2014-01-02 18:00:26" + }, + { + "name": "zendframework/zend-servicemanager", + "version": "2.1.6", + "target-dir": "Zend/ServiceManager", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendServiceManager.git", + "reference": "de182a20dfdcf978c49570514103c7477ef16e4f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendServiceManager/zipball/de182a20dfdcf978c49570514103c7477ef16e4f", + "reference": "de182a20dfdcf978c49570514103c7477ef16e4f", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "zendframework/zend-di": "Zend\\Di component" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\ServiceManager\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "keywords": [ + "servicemanager", + "zf2" + ], + "time": "2014-03-03 21:00:04" + }, + { + "name": "zendframework/zend-stdlib", + "version": "2.1.6", + "target-dir": "Zend/Stdlib", + "source": { + "type": "git", + "url": "https://github.com/zendframework/Component_ZendStdlib.git", + "reference": "e646729f2274f4552b6a92e38d8e458efe08ebc5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zendframework/Component_ZendStdlib/zipball/e646729f2274f4552b6a92e38d8e458efe08ebc5", + "reference": "e646729f2274f4552b6a92e38d8e458efe08ebc5", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "zendframework/zend-eventmanager": "To support aggregate hydrator usage", + "zendframework/zend-servicemanager": "To support hydrator plugin manager usage" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.2-dev", + "dev-develop": "2.3-dev" + } + }, + "autoload": { + "psr-0": { + "Zend\\Stdlib\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "keywords": [ + "stdlib", + "zf2" + ], + "time": "2014-01-04 13:00:28" + }, + { + "name": "zetacomponents/base", + "version": "1.8", + "source": { + "type": "git", + "url": "https://github.com/zetacomponents/Base.git", + "reference": "52ca69c1de55f3fa4f595779e5bc831da7ee176c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zetacomponents/Base/zipball/52ca69c1de55f3fa4f595779e5bc831da7ee176c", + "reference": "52ca69c1de55f3fa4f595779e5bc831da7ee176c", + "shasum": "" + }, + "type": "library", + "autoload": { + "classmap": [ + "src" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "apache2" + ], + "authors": [ + { + "name": "Sergey Alexeev" + }, + { + "name": "Sebastian Bergmann" + }, + { + "name": "Jan Borsodi" + }, + { + "name": "Raymond Bosman" + }, + { + "name": "Frederik Holljen" + }, + { + "name": "Kore Nordmann" + }, + { + "name": "Derick Rethans" + }, + { + "name": "Vadym Savchuk" + }, + { + "name": "Tobias Schlitt" + }, + { + "name": "Alexandru Stanoi" + } + ], + "description": "The Base package provides the basic infrastructure that all packages rely on. Therefore every component relies on this package.", + "homepage": "https://github.com/zetacomponents", + "time": "2009-12-21 12:14:16" + }, + { + "name": "zetacomponents/document", + "version": "1.3.1", + "source": { + "type": "git", + "url": "https://github.com/zetacomponents/Document.git", + "reference": "688abfde573cf3fe0730f82538fbd7aa9fc95bc8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/zetacomponents/Document/zipball/688abfde573cf3fe0730f82538fbd7aa9fc95bc8", + "reference": "688abfde573cf3fe0730f82538fbd7aa9fc95bc8", + "shasum": "" + }, + "require": { + "zetacomponents/base": "*" + }, + "require-dev": { + "zetacomponents/unit-test": "dev-master" + }, + "type": "library", + "autoload": { + "classmap": [ + "src" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "Sebastian Bergmann" + }, + { + "name": "Kore Nordmann" + }, + { + "name": "Derick Rethans" + }, + { + "name": "Tobias Schlitt" + }, + { + "name": "Alexandru Stanoi" + } + ], + "description": "The Document components provides a general conversion framework for different semantic document markup languages like XHTML, Docbook, RST and similar.", + "homepage": "https://github.com/zetacomponents", + "time": "2013-12-19 11:40:00" + } + ], + "aliases": [ + + ], + "minimum-stability": "stable", + "stability-flags": [ + + ], + "platform": { + "php": ">=5.3.3", + "ext-xml": "*" + }, + "platform-dev": [ + + ] +} diff --git a/docs/conf.py b/docs/conf.py index f5c38581..de645350 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -41,14 +41,14 @@ master_doc = 'index' # General information about the project. project = u'PhpWord' -copyright = u'2014, Progi1984' +copyright = u'2014, PHPWord Contributors' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = '0.9.0' +version = '0.12.0' # The full version, including alpha/beta/rc tags. release = version diff --git a/docs/containers.rst b/docs/containers.rst index 53579537..f165a589 100644 --- a/docs/containers.rst +++ b/docs/containers.rst @@ -16,56 +16,24 @@ section, use the following code: .. code-block:: php - $section = $phpWord->addSection($sectionSettings); + $section = $phpWord->addSection($sectionStyle); -The ``$sectionSettings`` is an optional associative array that sets the +The ``$sectionStyle`` is an optional associative array that sets the section. Example: .. code-block:: php - $sectionSettings = array( + $sectionStyle = array( 'orientation' => 'landscape', 'marginTop' => 600, 'colsNum' => 2, ); -Section settings -~~~~~~~~~~~~~~~~ - -Below are the available settings for section: - -- ``orientation`` Page orientation, i.e. 'portrait' (default) or - 'landscape' -- ``marginTop`` Page margin top in twips -- ``marginLeft`` Page margin left in twips -- ``marginRight`` Page margin right in twips -- ``marginBottom`` Page margin bottom in twips -- ``borderTopSize`` Border top size in twips -- ``borderTopColor`` Border top color -- ``borderLeftSize`` Border left size in twips -- ``borderLeftColor`` Border left color -- ``borderRightSize`` Border right size in twips -- ``borderRightColor`` Border right color -- ``borderBottomSize`` Border bottom size in twips -- ``borderBottomColor`` Border bottom color -- ``headerHeight`` Spacing to top of header -- ``footerHeight`` Spacing to bottom of footer -- ``colsNum`` Number of columns -- ``colsSpace`` Spacing between columns -- ``breakType`` Section break type (nextPage, nextColumn, continuous, - evenPage, oddPage) - -The following two settings are automatically set by the use of the -``orientation`` setting. You can alter them but that's not recommended. - -- ``pageSizeW`` Page width in twips -- ``pageSizeH`` Page height in twips - Page number ~~~~~~~~~~~ You can change a section page number by using the ``pageNumberingStart`` -property of the section. +style of the section. .. code-block:: php @@ -74,13 +42,13 @@ property of the section. // Method 2 $section = $phpWord->addSection(); - $section->getSettings()->setPageNumberingStart(1); + $section->getStyle()->setPageNumberingStart(1); Multicolumn ~~~~~~~~~~~ You can change a section layout to multicolumn (like in a newspaper) by -using the ``breakType`` and ``colsNum`` property of the section. +using the ``breakType`` and ``colsNum`` style of the section. .. code-block:: php @@ -89,8 +57,31 @@ using the ``breakType`` and ``colsNum`` property of the section. // Method 2 $section = $phpWord->addSection(); - $section->getSettings()->setBreakType('continuous'); - $section->getSettings()->setColsNum(2); + $section->getStyle()->setBreakType('continuous'); + $section->getStyle()->setColsNum(2); + +Line numbering +~~~~~~~~~~~~~~ + +You can apply line numbering to a section by using the ``lineNumbering`` +style of the section. + +.. code-block:: php + + // Method 1 + $section = $phpWord->addSection(array('lineNumbering' => array())); + + // Method 2 + $section = $phpWord->addSection(); + $section->getStyle()->setLineNumbering(array()); + +Below are the properties of the line numbering style. + +- ``start`` Line numbering starting value +- ``increment`` Line number increments +- ``distance`` Distance between text and line numbering in twip +- ``restart`` Line numbering restart setting + continuous\|newPage\|newSection Headers ------- diff --git a/docs/elements.rst b/docs/elements.rst index b6842b65..eae23c9d 100644 --- a/docs/elements.rst +++ b/docs/elements.rst @@ -3,71 +3,82 @@ Elements ======== -Below are the matrix of element availability in each container. The column shows -the containers while the rows lists the elements. +Below are the matrix of element availability in each container. The +column shows the containers while the rows lists the elements. -+-----+---------------+---------+--------+--------+------+----------+----------+ -| Num | Element | Section | Header | Footer | Cell | Text Run | Footnote | -+=====+===============+=========+========+========+======+==========+==========+ -| 1 | Text | v | v | v | v | v | v | -+-----+---------------+---------+--------+--------+------+----------+----------+ -| 2 | Text Run | v | v | v | v | \- | \- | -+-----+---------------+---------+--------+--------+------+----------+----------+ -| 3 | Link | v | v | v | v | v | v | -+-----+---------------+---------+--------+--------+------+----------+----------+ -| 4 | Title | v | ? | ? | ? | ? | ? | -+-----+---------------+---------+--------+--------+------+----------+----------+ -| 5 | Preserve Text | ? | v | v | v\* | ? | ? | -+-----+---------------+---------+--------+--------+------+----------+----------+ -| 6 | Text Break | v | v | v | v | v | v | -+-----+---------------+---------+--------+--------+------+----------+----------+ -| 7 | Page Break | v | \- | \- | \- | \- | \- | -+-----+---------------+---------+--------+--------+------+----------+----------+ -| 8 | List | v | v | v | v | \- | \- | -+-----+---------------+---------+--------+--------+------+----------+----------+ -| 9 | Table | v | v | v | ? | \- | \- | -+-----+---------------+---------+--------+--------+------+----------+----------+ -| 10 | Image | v | v | v | v | v | v | -+-----+---------------+---------+--------+--------+------+----------+----------+ -| 11 | Watermark | \- | v | \- | \- | \- | \- | -+-----+---------------+---------+--------+--------+------+----------+----------+ -| 12 | Object | v | v | v | v | v | v | -+-----+---------------+---------+--------+--------+------+----------+----------+ -| 13 | TOC | v | \- | \- | \- | \- | \- | -+-----+---------------+---------+--------+--------+------+----------+----------+ -| 14 | Footnote | v | \- | \- | v\*\*| v\*\* | \- | -+-----+---------------+---------+--------+--------+------+----------+----------+ -| 15 | Endnote | v | \- | \- | v\*\*| v\*\* | \- | -+-----+---------------+---------+--------+--------+------+----------+----------+ -| 16 | CheckBox | v | v | v | v | ? | ? | -+-----+---------------+---------+--------+--------+------+----------+----------+ ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| Num | Element | Section | Header | Footer | Cell | Text Run | Footnote | ++=======+=================+===========+==========+==========+=========+============+============+ +| 1 | Text | v | v | v | v | v | v | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 2 | Text Run | v | v | v | v | - | - | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 3 | Link | v | v | v | v | v | v | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 4 | Title | v | ? | ? | ? | ? | ? | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 5 | Preserve Text | ? | v | v | v\* | - | - | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 6 | Text Break | v | v | v | v | v | v | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 7 | Page Break | v | - | - | - | - | - | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 8 | List | v | v | v | v | - | - | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 9 | Table | v | v | v | v | - | - | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 10 | Image | v | v | v | v | v | v | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 11 | Watermark | - | v | - | - | - | - | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 12 | Object | v | v | v | v | v | v | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 13 | TOC | v | - | - | - | - | - | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 14 | Footnote | v | - | - | v\*\* | v\*\* | - | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 15 | Endnote | v | - | - | v\*\* | v\*\* | - | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 16 | CheckBox | v | v | v | v | - | - | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 17 | TextBox | v | v | v | v | - | - | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 18 | Field | v | v | v | v | v | v | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 19 | Line | v | v | v | v | v | v | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 20 | Shape | v | v | v | v | v | v | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 21 | Chart | v | - | - | - | - | - | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 22 | Form fields | v | v | v | v | v | v | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ +| 23 | Bookmarks | v | - | - | v | v | - | ++-------+-----------------+-----------+----------+----------+---------+------------+------------+ Legend: -- ``v`` Available -- ``v*`` Available only when inside header/footer -- ``v**`` Available only when inside section -- ``-`` Not available -- ``?`` Should be available +- ``v`` Available +- ``v*`` Available only when inside header/footer +- ``v**`` Available only when inside section +- ``-`` Not available +- ``?`` Should be available Texts ----- Text can be added by using ``addText`` and ``addTextRun`` method. ``addText`` is used for creating simple paragraphs that only contain -texts with the same style. ``addTextRun`` is used for creating -complex paragraphs that contain text with different style (some bold, -other italics, etc) or other elements, e.g. images or links. The -syntaxes are as follow: +texts with the same style. ``addTextRun`` is used for creating complex +paragraphs that contain text with different style (some bold, other +italics, etc) or other elements, e.g. images or links. The syntaxes are +as follow: .. code-block:: php $section->addText($text, [$fontStyle], [$paragraphStyle]); $textrun = $section->addTextRun([$paragraphStyle]); -Text styles -~~~~~~~~~~~ - You can use the ``$fontStyle`` and ``$paragraphStyle`` variable to define text formatting. There are 2 options to style the inserted text elements, i.e. inline style by using array or defined style by adding @@ -84,7 +95,7 @@ Inline style examples: $textrun = $section->addTextRun(); $textrun->addText('I am bold', array('bold' => true)); $textrun->addText('I am italic', array('italic' => true)); - $textrun->addText('I am colored, array('color' => 'AACC00')); + $textrun->addText('I am colored', array('color' => 'AACC00')); Defined style examples: @@ -98,44 +109,6 @@ Defined style examples: $phpWord->addParagraphStyle('pStyle', $paragraphStyle); $text = $section->addText('Hello world!', 'pStyle'); -Font style -^^^^^^^^^^ - -Available font styles: - -- ``name`` Font name, e.g. *Arial* -- ``size`` Font size, e.g. *20*, *22*, -- ``hint`` Font content type, *default*, *eastAsia*, or *cs* -- ``bold`` Bold, *true* or *false* -- ``italic`` Italic, *true* or *false* -- ``superScript`` Superscript, *true* or *false* -- ``subScript`` Subscript, *true* or *false* -- ``underline`` Underline, *dash*, *dotted*, etc. -- ``strikethrough`` Strikethrough, *true* or *false* -- ``color`` Font color, e.g. *FF0000* -- ``fgColor`` Font highlight color, e.g. *yellow*, *green*, *blue* -- ``bgColor`` Font background color, e.g. *FF0000* - -Paragraph style -^^^^^^^^^^^^^^^ - -Available paragraph styles: - -- ``align`` Paragraph alignment, *left*, *right* or *center* -- ``spaceBefore`` Space before paragraph -- ``spaceAfter`` Space after paragraph -- ``indent`` Indent by how much -- ``hanging`` Hanging by how much -- ``basedOn`` Parent style -- ``next`` Style for next paragraph -- ``widowControl`` Allow first/last line to display on a separate page, - *true* or *false* -- ``keepNext`` Keep paragraph with next paragraph, *true* or *false* -- ``keepLines`` Keep all lines on one page, *true* or *false* -- ``pageBreakBefore`` Start paragraph on next page, *true* or *false* -- ``lineHeight`` text line height, e.g. *1.0*, *1.5*, ect... -- ``tabs`` Set of custom tab stops - Titles ~~~~~~ @@ -158,12 +131,13 @@ You can add Hyperlinks to the document by using the function addLink: .. code-block:: php - $section->addLink($linkSrc, [$linkName], [$fontStyle], [$paragraphStyle]); + $section->addLink($linkSrc, [$linkName], [$fontStyle], [$paragraphStyle], [$isInternal]); - ``$linkSrc`` The URL of the link. - ``$linkName`` Placeholder of the URL that appears in the document. - ``$fontStyle`` See "Font style" section. - ``$paragraphStyle`` See "Paragraph style" section. +- ``$isInternal`` Set to true, if the link points to a bookmark inside the document Preserve texts ~~~~~~~~~~~~~~ @@ -198,7 +172,7 @@ Page breaks There are two ways to insert a page breaks, using the ``addPageBreak`` method or using the ``pageBreakBefore`` style of paragraph. -:: code-block:: php +.. code-block:: php $section->addPageBreak(); @@ -225,8 +199,8 @@ Parameters: Advanced usage: -You can also create your own numbering style by changing the ``$listStyle`` parameter -with the name of your numbering style. +You can also create your own numbering style by changing the +``$listStyle`` parameter with the name of your numbering style. .. code-block:: php @@ -243,20 +217,6 @@ with the name of your numbering style. $section->addListItem('List Item I.b', 1, null, 'multilevel'); $section->addListItem('List Item II', 0, null, 'multilevel'); -Level styles: - -- ``start`` Starting value -- ``format`` Numbering format bullet|decimal|upperRoman|lowerRoman|upperLetter|lowerLetter -- ``restart`` Restart numbering level symbol -- ``suffix`` Content between numbering symbol and paragraph text tab|space|nothing -- ``text`` Numbering level text e.g. %1 for nonbullet or bullet character -- ``align`` Numbering symbol align left|center|right|both -- ``left`` See paragraph style -- ``hanging`` See paragraph style -- ``tabPos`` See paragraph style -- ``font`` Font name -- ``hint`` See font style - Tables ------ @@ -282,34 +242,6 @@ Table style can be defined with ``addTableStyle``: $phpWord->addTableStyle('myTable', $tableStyle, $firstRowStyle); $table = $section->addTable('myTable'); -Table, row, and cell styles -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Table styles: - -- ``width`` Table width in percent -- ``bgColor`` Background color, e.g. '9966CC' -- ``border(Top|Right|Bottom|Left)Size`` Border size in twips -- ``border(Top|Right|Bottom|Left)Color`` Border color, e.g. '9966CC' -- ``cellMargin(Top|Right|Bottom|Left)`` Cell margin in twips - -Row styles: - -- ``tblHeader`` Repeat table row on every new page, *true* or *false* -- ``cantSplit`` Table row cannot break across pages, *true* or *false* -- ``exactHeight`` Row height is exact or at least - -Cell styles: - -- ``width`` Cell width in twips -- ``valign`` Vertical alignment, *top*, *center*, *both*, *bottom* -- ``textDirection`` Direction of text -- ``bgColor`` Background color, e.g. '9966CC' -- ``border(Top|Right|Bottom|Left)Size`` Border size in twips -- ``border(Top|Right|Bottom|Left)Color`` Border color, e.g. '9966CC' -- ``gridSpan`` Number of columns spanned -- ``vMerge`` *restart* or *continue* - Cell span ~~~~~~~~~ @@ -326,15 +258,15 @@ See ``Sample_09_Tables.php`` for more code sample. Images ------ -To add an image, use the ``addImage`` method to sections, headers, footers, -textruns, or table cells. +To add an image, use the ``addImage`` method to sections, headers, +footers, textruns, or table cells. .. code-block:: php $section->addImage($src, [$style]); -- `source` String path to a local image or URL of a remote image -- `styles` Array fo styles for the image. See below. +- source String path to a local image or URL of a remote image +- styles Array fo styles for the image. See below. Examples: @@ -356,19 +288,6 @@ Examples: $textrun = $section->addTextRun(); $textrun->addImage('http://php.net/logo.jpg'); -Image styles -~~~~~~~~~~~~ - -Available image styles: - -- ``width`` Width in pixels -- ``height`` Height in pixels -- ``align`` Image alignment, *left*, *right*, or *center* -- ``marginTop`` Top margin in inches, can be negative -- ``marginLeft`` Left margin in inches, can be negative -- ``wrappingStyle`` Wrapping style, *inline*, *square*, *tight*, - *behind*, or *infront* - Watermarks ~~~~~~~~~~ @@ -419,10 +338,10 @@ Options for ``$tocStyle``: Footnotes & endnotes -------------------- -You can create footnotes with ``addFootnote`` and endnotes with ``addEndnote`` -in texts or textruns, but it's recommended to use textrun to have better layout. -You can use ``addText``, ``addLink``, ``addTextBreak``, ``addImage``, -``addObject`` on footnotes and endnotes. +You can create footnotes with ``addFootnote`` and endnotes with +``addEndnote`` in texts or textruns, but it's recommended to use textrun +to have better layout. You can use ``addText``, ``addLink``, +``addTextBreak``, ``addImage``, ``addObject`` on footnotes and endnotes. On textrun: @@ -448,9 +367,9 @@ On text: $footnote = $section->addFootnote(); $footnote->addText('Footnote text.'); -The footnote reference number will be displayed with decimal number starting -from 1. This number use ``FooterReference`` style which you can redefine by -``addFontStyle`` method. Default value for this style is +The footnote reference number will be displayed with decimal number +starting from 1. This number use ``FooterReference`` style which you can +redefine by ``addFontStyle`` method. Default value for this style is ``array('superScript' => true)``; Checkboxes @@ -467,3 +386,60 @@ Checkbox elements can be added to sections or table cells by using - ``$text`` Text following the check box - ``$fontStyle`` See "Font style" section. - ``$paragraphStyle`` See "Paragraph style" section. + +Textboxes +--------- + +To be completed. + +Fields +------ + +To be completed. + +Lines +----- + +Line elements can be added to sections by using ``addLine``. + +.. code-block:: php + + $linestyle = array('weight' => 1, 'width' => 100, 'height' => 0, 'color' => '#b2a68b'); + $section->addLine($lineStyle) + +Available line style attributes: + +- ``weight`` Line width in twips +- ``color`` Defines the color of stroke. The hex value must be introduced with #. +- ``dash`` Line types: dash, rounddot, squaredot, dashdot, longdash, longdashdot, longdashdotdot +- ``beginArrow`` Start type of arrow: block, open, classic, diamond, oval +- ``endArrow`` End type of arrow: block, open, classic, diamond, ovel +- ``width`` Line-object width in pt +- ``height`` Line-object height in pt +- ``flip`` Flip the line element: true, false + +Shapes +------ + +To be completed. + +Charts +------ + +To be completed. + +Form fields +----------- + +To be completed. + +Bookmarks +~~~~~ + +You can add Bookmarks to the document by using the function addBookmark: + +.. code-block:: php + + $section->addBookmark($name); + +- ``$name`` The name of the bookmark which can be referenced in the addLink-Function as target. Should obviously be unique throughout the document. \ No newline at end of file diff --git a/docs/general.rst b/docs/general.rst index c7e55d5a..8fc7130e 100644 --- a/docs/general.rst +++ b/docs/general.rst @@ -36,22 +36,18 @@ folder `__. 'myOwnStyle'); // You can also put the appended element to local object like this: - $fontStyle = new \PhpOffice\PhpWord\Style\Font(); - $fontStyle->setBold(true); - $fontStyle->setName('Verdana'); - $fontStyle->setSize(22); + $fontStyle = array( + 'name' => 'Verdana', + 'size' => 22, + 'bold' => true, + ); $myTextElement = $section->addText('Hello World!'); $myTextElement->setFontStyle($fontStyle); - // Finally, write the document: - $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); - $objWriter->save('helloWorld.docx'); - - $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'ODText'); - $objWriter->save('helloWorld.odt'); - - $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'RTF'); - $objWriter->save('helloWorld.rtf'); + // Finally, save the document: + $phpWord->save('helloWorld.docx'); + $phpWord->save('helloWorld.odt', 'ODText'); + $phpWord->save('helloWorld.rtf', 'RTF'); Settings -------- @@ -67,7 +63,8 @@ This option sets and `XMLWriter::setIndentString `__. The default value of this option is ``true`` (compatible), which is -`required for OpenOffice `__ to +`required for +OpenOffice `__ to render OOXML document correctly. You can set this option to ``false`` during development to make the resulting XML file easier to read. @@ -78,11 +75,10 @@ during development to make the resulting XML file easier to read. Zip class ~~~~~~~~~ -By default, PHPWord uses PHP -`ZipArchive `__ to read or write -ZIP compressed archive and the files inside them. If you can't have -ZipArchive installed on your server, you can use pure PHP library -alternative, `PCLZip `__, which +By default, PHPWord uses `Zip extension `__ +to deal with ZIP compressed archives and files inside them. If you can't have +Zip extension installed on your server, you can use pure PHP library +alternative, `PclZip `__, which included with PHPWord. .. code-block:: php @@ -100,15 +96,15 @@ default font by using the following two functions: $phpWord->setDefaultFontName('Times New Roman'); $phpWord->setDefaultFontSize(12); -Document properties -------------------- +Document information +-------------------- -You can set the document properties such as title, creator, and company +You can set the document information such as title, creator, and company name. Use the following functions: .. code-block:: php - $properties = $phpWord->getDocumentProperties(); + $properties = $phpWord->getDocInfo(); $properties->setCreator('My name'); $properties->setCompany('My factory'); $properties->setTitle('My title'); @@ -133,13 +129,13 @@ points to twips. // Paragraph with 6 points space after $phpWord->addParagraphStyle('My Style', array( - 'spaceAfter' => \PhpOffice\PhpWord\Shared\Font::pointSizeToTwips(6)) + 'spaceAfter' => \PhpOffice\PhpWord\Shared\Converter::pointToTwip(6)) ); $section = $phpWord->addSection(); - $sectionStyle = $section->getSettings(); + $sectionStyle = $section->getStyle(); // half inch left margin - $sectionStyle->setMarginLeft(\PhpOffice\PhpWord\Shared\Font::inchSizeToTwips(.5)); + $sectionStyle->setMarginLeft(\PhpOffice\PhpWord\Shared\Converter::inchToTwip(.5)); // 2 cm right margin - $sectionStyle->setMarginRight(\PhpOffice\PhpWord\Shared\Font::centimeterSizeToTwips(2)); + $sectionStyle->setMarginRight(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(2)); diff --git a/docs/index.rst b/docs/index.rst index 700694a5..4f200cca 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -18,11 +18,13 @@ Format (RTF). :maxdepth: 2 intro - setup + installing general containers elements + styles templates + writersreaders recipes faq credits diff --git a/docs/setup.rst b/docs/installing.rst similarity index 98% rename from docs/setup.rst rename to docs/installing.rst index 3c01eb94..e5d61b4e 100644 --- a/docs/setup.rst +++ b/docs/installing.rst @@ -1,6 +1,6 @@ .. _setup: -Installing/Configuring +Installing/configuring ====================== Requirements diff --git a/docs/intro.rst b/docs/intro.rst index 0f1f3d74..03821c91 100644 --- a/docs/intro.rst +++ b/docs/intro.rst @@ -12,18 +12,14 @@ Applications `__ (OpenDocument or ODF), and `Rich Text Format `__ (RTF). -No Windows operating system is needed for usage because the resulting -DOCX, ODT, or RTF files can be opened by all major `word processing -softwares `__. - -PHPWord is an open source project licensed under LGPL. -PHPWord is `unit tested `__ to -make sure that the released versions are stable. - -**Want to contribute?** `Fork -us `__ or -`submit `__ your bug -reports or feature requests to us. +PHPWord is an open source project licensed under the terms of `LGPL +version 3 `__. +PHPWord is aimed to be a high quality software product by incorporating +`continuous integration `__ and +`unit testing `__. +You can learn more about PHPWord by reading this Developers' +Documentation and the `API +Documentation `__. Features -------- @@ -41,6 +37,7 @@ Features run) that contains other elements - Insert titles (headers) and table of contents - Insert text breaks and page breaks +- Insert right-to-left text - Insert and format images, either local, remote, or as page watermarks - Insert binary OLE Objects such as Excel or Visio - Insert and format table with customized properties for each rows @@ -49,6 +46,9 @@ Features - Insert list items as bulleted, numbered, or multilevel - Insert hyperlinks - Insert footnotes and endnotes +- Insert drawing shapes (arc, curve, line, polyline, rect, oval) +- Insert charts (pie, doughnut, bar, line, area, scatter, radar) +- Insert form fields (textinput, checkbox, and dropdown) - Create document from templates - Use XSL 1.0 style sheets to transform main document part of OOXML template @@ -62,122 +62,134 @@ Below are the supported features for each file formats. Writers ~~~~~~~ -+-------------------------------------------------+--------+-------+-------+ -| Features | DOCX | ODT | RTF | -+=========================+=======================+========+=======+=======+ -| **Document Properties** | Standard | | | | -+ +-----------------------+--------+-------+-------+ -| | Extended | | | | -+ +-----------------------+--------+-------+-------+ -| | UserDefined | | | | -+-------------------------+-----------------------+--------+-------+-------+ -| **Element Type** | Text | ✓ | ✓ | ✓ | -+ +-----------------------+--------+-------+-------+ -| | Text Run | ✓ | ✓ | ✓ | -+ +-----------------------+--------+-------+-------+ -| | Title | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Link | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Preserve Text | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Text Break | ✓ | ✓ | ✓ | -+ +-----------------------+--------+-------+-------+ -| | Page Break | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | List | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Table | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Image | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Object | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Watermark | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Table of Contents | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Header | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Footer | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Footnote | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Endnote | ✓ | | | -+-------------------------+-----------------------+--------+-------+-------+ -| **Graphs** | 2D basic graphs | | | | -+ +-----------------------+--------+-------+-------+ -| | 2D advanced graphs | | | | -+ +-----------------------+--------+-------+-------+ -| | 3D graphs | | | | -+-------------------------+-----------------------+--------+-------+-------+ -| **Math** | OMML support | | | | -+ +-----------------------+--------+-------+-------+ -| | MathML support | | | | -+-------------------------+-----------------------+--------+-------+-------+ -| **Bonus** | Encryption | | | | -+ +-----------------------+--------+-------+-------+ -| | Protection | | | | -+-------------------------+-----------------------+--------+-------+-------+ - ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| Features | | DOCX | ODT | RTF | HTML | PDF | ++===========================+======================+========+=======+=======+========+=======+ +| **Document Properties** | Standard | ✓ | ✓ | ✓ | ✓ | ✓ | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | Custom | ✓ | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| **Element Type** | Text | ✓ | ✓ | ✓ | ✓ | ✓ | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | Text Run | ✓ | ✓ | ✓ | ✓ | ✓ | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | Title | ✓ | ✓ | | ✓ | ✓ | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | Link | ✓ | ✓ | ✓ | ✓ | ✓ | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | Preserve Text | ✓ | | | | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | Text Break | ✓ | ✓ | ✓ | ✓ | ✓ | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | Page Break | ✓ | | ✓ | | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | List | ✓ | | | | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | Table | ✓ | ✓ | ✓ | ✓ | ✓ | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | Image | ✓ | ✓ | ✓ | ✓ | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | Object | ✓ | | | | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | Watermark | ✓ | | | | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | Table of Contents | ✓ | | | | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | Header | ✓ | | | | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | Footer | ✓ | | | | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | Footnote | ✓ | | | ✓ | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | Endnote | ✓ | | | ✓ | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| **Graphs** | 2D basic graphs | ✓ | | | | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | 2D advanced graphs | | | | | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | 3D graphs | ✓ | | | | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| **Math** | OMML support | | | | | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | MathML support | | | | | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| **Bonus** | Encryption | | | | | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ +| | Protection | | | | | | ++---------------------------+----------------------+--------+-------+-------+--------+-------+ Readers ~~~~~~~ -+-------------------------------------------------+--------+-------+-------+ -| Features | DOCX | ODT | RTF | -+=========================+=======================+========+=======+=======+ -| **Document Properties** | Standard | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Extended | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | UserDefined | ✓ | | | -+-------------------------+-----------------------+--------+-------+-------+ -| **Element Type** | Text | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Text Run | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Title | | | | -+ +-----------------------+--------+-------+-------+ -| | Link | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Preserve Text | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Text Break | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Page Break | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | List | | | | -+ +-----------------------+--------+-------+-------+ -| | Table | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Image | | | | -+ +-----------------------+--------+-------+-------+ -| | Object | | | | -+ +-----------------------+--------+-------+-------+ -| | Watermark | | | | -+ +-----------------------+--------+-------+-------+ -| | Table of Contents | | | | -+ +-----------------------+--------+-------+-------+ -| | Header | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Footer | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Footnote | ✓ | | | -+ +-----------------------+--------+-------+-------+ -| | Endnote | ✓ | | | -+-------------------------+-----------------------+--------+-------+-------+ -| **Graphs** | 2D basic graphs | | | | -+ +-----------------------+--------+-------+-------+ -| | 2D advanced graphs | | | | -+ +-----------------------+--------+-------+-------+ -| | 3D graphs | | | | -+-------------------------+-----------------------+--------+-------+-------+ -| **Math** | OMML support | | | | -+ +-----------------------+--------+-------+-------+ -| | MathML support | | | | -+-------------------------+-----------------------+--------+-------+-------+ -| **Bonus** | Encryption | | | | -+ +-----------------------+--------+-------+-------+ -| | Protection | | | | -+-------------------------+-----------------------+--------+-------+-------+ ++---------------------------+----------------------+--------+-------+-------+-------+ +| Features | | DOCX | ODT | RTF | HTML | ++===========================+======================+========+=======+=======+=======+ +| **Document Properties** | Standard | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Custom | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| **Element Type** | Text | ✓ | ✓ | ✓ | ✓ | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Text Run | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Title | ✓ | ✓ | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Link | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Preserve Text | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Text Break | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Page Break | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | List | ✓ | ✓ | | ✓ | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Table | ✓ | | | ✓ | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Image | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Object | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Watermark | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Table of Contents | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Header | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Footer | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Footnote | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Endnote | ✓ | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| **Graphs** | 2D basic graphs | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | 2D advanced graphs | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | 3D graphs | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| **Math** | OMML support | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | MathML support | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| **Bonus** | Encryption | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ +| | Protection | | | | | ++---------------------------+----------------------+--------+-------+-------+-------+ + +Contributing +------------ + +We welcome everyone to contribute to PHPWord. Below are some of the +things that you can do to contribute: + +- Read `our contributing + guide `__ +- `Fork us `__ and `request + a pull `__ to the + `develop `__ + branch +- Submit `bug reports or feature + requests `__ to GitHub +- Follow `@PHPWord `__ and + `@PHPOffice `__ on Twitter diff --git a/docs/recipes.rst b/docs/recipes.rst index 033452b3..0be6b4e0 100644 --- a/docs/recipes.rst +++ b/docs/recipes.rst @@ -2,3 +2,97 @@ Recipes ======= + +Create float left image +----------------------- + +Use absolute positioning relative to margin horizontally and to line +vertically. + +.. code-block:: php + + $imageStyle = array( + 'width' => 40, + 'height' => 40, + 'wrappingStyle' => 'square', + 'positioning' => 'absolute', + 'posHorizontalRel' => 'margin', + 'posVerticalRel' => 'line', + ); + $textrun->addImage('resources/_earth.jpg', $imageStyle); + $textrun->addText($lipsumText); + +Download the produced file automatically +---------------------------------------- + +Use ``php://output`` as the filename. + +.. code-block:: php + + $phpWord = new \PhpOffice\PhpWord\PhpWord(); + $section = $phpWord->createSection(); + $section->addText('Hello World!'); + $file = 'HelloWorld.docx'; + header("Content-Description: File Transfer"); + header('Content-Disposition: attachment; filename="' . $file . '"'); + header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); + header('Content-Transfer-Encoding: binary'); + header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); + header('Expires: 0'); + $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); + $xmlWriter->save("php://output"); + +Create numbered headings +------------------------ + +Define a numbering style and title styles, and match the two styles (with ``pStyle`` and ``numStyle``) like below. + +.. code-block:: php + + $phpWord->addNumberingStyle( + 'hNum', + array('type' => 'multilevel', 'levels' => array( + array('pStyle' => 'Heading1', 'format' => 'decimal', 'text' => '%1'), + array('pStyle' => 'Heading2', 'format' => 'decimal', 'text' => '%1.%2'), + array('pStyle' => 'Heading3', 'format' => 'decimal', 'text' => '%1.%2.%3'), + ) + ) + ); + $phpWord->addTitleStyle(1, array('size' => 16), array('numStyle' => 'hNum', 'numLevel' => 0)); + $phpWord->addTitleStyle(2, array('size' => 14), array('numStyle' => 'hNum', 'numLevel' => 1)); + $phpWord->addTitleStyle(3, array('size' => 12), array('numStyle' => 'hNum', 'numLevel' => 2)); + + $section->addTitle('Heading 1', 1); + $section->addTitle('Heading 2', 2); + $section->addTitle('Heading 3', 3); + +Add a link within a title +------------------------- + +Apply 'HeadingN' paragraph style to TextRun or Link. Sample code: + +.. code-block:: php + + $phpWord = new \PhpOffice\PhpWord\PhpWord(); + $phpWord->addTitleStyle(1, array('size' => 16, 'bold' => true)); + $phpWord->addTitleStyle(2, array('size' => 14, 'bold' => true)); + $phpWord->addFontStyle('Link', array('color' => '0000FF', 'underline' => 'single')); + + $section = $phpWord->addSection(); + + // Textrun + $textrun = $section->addTextRun('Heading1'); + $textrun->addText('The '); + $textrun->addLink('https://github.com/PHPOffice/PHPWord', 'PHPWord', 'Link'); + + // Link + $section->addLink('https://github.com/', 'GitHub', 'Link', 'Heading2'); + +Remove [Compatibility Mode] text in the MS Word title bar +--------------------------------------------------------- + +Use the ``Metadata\Compatibility\setOoxmlVersion(n)`` method with ``n`` is the version of Office (14 = Office 2010, 15 = Office 2013). + +.. code-block:: php + + $phpWord->getCompatibility()->setOoxmlVersion(15); diff --git a/docs/references.rst b/docs/references.rst index 4f19a817..20aa1ed0 100644 --- a/docs/references.rst +++ b/docs/references.rst @@ -3,11 +3,21 @@ References ========== +ISO/IEC 29500, Third edition, 2012-09-01 +--------------------- + +- `Part 1: Fundamentals and Markup Language Reference + `__ +- `Part 2: Open Packaging Conventions + `__ +- `Part 3: Markup Compatibility and Extensibility + `__ +- `Part 4: Transitional Migration Features + `__ + Formal specifications --------------------- -- `Office Open XML (OOXML) (ECMA-376) - Schema `__ - `Oasis OpenDocument Standard Version 1.2 `__ - `Rich Text Format (RTF) Specification, version diff --git a/docs/src/documentation.md b/docs/src/documentation.md new file mode 100644 index 00000000..9c0c865b --- /dev/null +++ b/docs/src/documentation.md @@ -0,0 +1,1090 @@ + +# Contents + +- [Introduction](#introduction) + - [Features](#features) + - [File formats](#file-formats) +- [Installing/configuring](#installing-configuring) + - [Requirements](#requirements) + - [Installation](#installation) + - [Using samples](#using-samples) +- [General usage](#general-usage) + - [Basic example](#basic-example) + - [Settings](#settings) + - [Default font](#default-font) + - [Document properties](#document-properties) + - [Measurement units](#measurement-units) +- [Containers](#containers) + - [Sections](#sections) + - [Headers](#headers) + - [Footers](#footers) + - [Other containers](#other-containers) +- [Elements](#elements) + - [Texts](#texts) + - [Breaks](#breaks) + - [Lists](#lists) + - [Tables](#tables) + - [Images](#images) + - [Objects](#objects) + - [Table of contents](#table-of-contents) + - [Footnotes & endnotes](#footnotes-endnotes) + - [Checkboxes](#checkboxes) + - [Textboxes](#textboxes) + - [Fields](#fields) + - [Lines](#lines) + - [Shapes](#shapes) + - [Charts](#charts) + - [FormFields](#form-fields) +- [Styles](#styles) + - [Section](#section) + - [Font](#font) + - [Paragraph](#paragraph) + - [Table](#table) +- [Templates](#templates) +- [Writers & readers](#writers-readers) + - [OOXML](#ooxml) + - [OpenDocument](#opendocument) + - [RTF](#rtf) + - [HTML](#html) + - [PDF](#pdf) +- [Recipes](#recipes) +- [Frequently asked questions](#frequently-asked-questions) +- [References](#references) + +# Introduction + +PHPWord is a library written in pure PHP that provides a set of classes to write to and read from different document file formats. The current version of PHPWord supports Microsoft [Office Open XML](http://en.wikipedia.org/wiki/Office_Open_XML) (OOXML or OpenXML), OASIS [Open Document Format for Office Applications](http://en.wikipedia.org/wiki/OpenDocument) (OpenDocument or ODF), and [Rich Text Format](http://en.wikipedia.org/wiki/Rich_Text_Format) (RTF). + +PHPWord is an open source project licensed under the terms of [LGPL version 3](https://github.com/PHPOffice/PHPWord/blob/develop/COPYING.LESSER). PHPWord is aimed to be a high quality software product by incorporating [continuous integration](https://travis-ci.org/PHPOffice/PHPWord) and [unit testing](http://phpoffice.github.io/PHPWord/coverage/develop/). You can learn more about PHPWord by reading this Developers' Documentation and the [API Documentation](http://phpoffice.github.io/PHPWord/docs/develop/). + +## Features + +- Set document properties, e.g. title, subject, and creator. +- Create document sections with different settings, e.g. portrait/landscape, page size, and page numbering +- Create header and footer for each sections +- Set default font type, font size, and paragraph style +- Use UTF-8 and East Asia fonts/characters +- Define custom font styles (e.g. bold, italic, color) and paragraph styles (e.g. centered, multicolumns, spacing) either as named style or inline in text +- Insert paragraphs, either as a simple text or complex one (a text run) that contains other elements +- Insert titles (headers) and table of contents +- Insert text breaks and page breaks +- Insert and format images, either local, remote, or as page watermarks +- Insert binary OLE Objects such as Excel or Visio +- Insert and format table with customized properties for each rows (e.g. repeat as header row) and cells (e.g. background color, rowspan, colspan) +- Insert list items as bulleted, numbered, or multilevel +- Insert hyperlinks +- Insert footnotes and endnotes +- Insert drawing shapes (arc, curve, line, polyline, rect, oval) +- Insert charts (pie, doughnut, bar, line, area, scatter, radar) +- Insert form fields (textinput, checkbox, and dropdown) +- Create document from templates +- Use XSL 1.0 style sheets to transform main document part of OOXML template +- ... and many more features on progress + +## File formats + +Below are the supported features for each file formats. + +### Writers + +| Features | | DOCX | ODT | RTF | HTML | PDF | +|-------------------------|--------------------|------|-----|-----|------|-----| +| **Document Properties** | Standard | ✓ | ✓ | ✓ | ✓ | | +| | Custom | ✓ | ✓ | | | | +| **Element Type** | Text | ✓ | ✓ | ✓ | ✓ | ✓ | +| | Text Run | ✓ | ✓ | ✓ | ✓ | ✓ | +| | Title | ✓ | ✓ | | ✓ | ✓ | +| | Link | ✓ | ✓ | ✓ | ✓ | ✓ | +| | Preserve Text | ✓ | | | | | +| | Text Break | ✓ | ✓ | ✓ | ✓ | ✓ | +| | Page Break | ✓ | | ✓ | | | +| | List | ✓ | | | | | +| | Table | ✓ | ✓ | ✓ | ✓ | ✓ | +| | Image | ✓ | ✓ | ✓ | ✓ | | +| | Object | ✓ | | | | | +| | Watermark | ✓ | | | | | +| | Table of Contents | ✓ | | | | | +| | Header | ✓ | | | | | +| | Footer | ✓ | | | | | +| | Footnote | ✓ | | | ✓ | | +| | Endnote | ✓ | | | ✓ | | +| **Graphs** | 2D basic graphs | ✓ | | | | | +| | 2D advanced graphs | | | | | | +| | 3D graphs | ✓ | | | | | +| **Math** | OMML support | | | | | | +| | MathML support | | | | | | +| **Bonus** | Encryption | | | | | | +| | Protection | | | | | | + +### Readers + +| Features | | DOCX | ODT | RTF | HTML| +|-------------------------|--------------------|------|-----|-----|-----| +| **Document Properties** | Standard | ✓ | | | | +| | Custom | ✓ | | | | +| **Element Type** | Text | ✓ | ✓ | ✓ | ✓ | +| | Text Run | ✓ | | | | +| | Title | ✓ | ✓ | | | +| | Link | ✓ | | | | +| | Preserve Text | ✓ | | | | +| | Text Break | ✓ | | | | +| | Page Break | ✓ | | | | +| | List | ✓ | ✓ | | ✓ | +| | Table | ✓ | | | ✓ | +| | Image | ✓ | | | | +| | Object | | | | | +| | Watermark | | | | | +| | Table of Contents | | | | | +| | Header | ✓ | | | | +| | Footer | ✓ | | | | +| | Footnote | ✓ | | | | +| | Endnote | ✓ | | | | +| **Graphs** | 2D basic graphs | | | | | +| | 2D advanced graphs | | | | | +| | 3D graphs | | | | | +| **Math** | OMML support | | | | | +| | MathML support | | | | | +| **Bonus** | Encryption | | | | | +| | Protection | | | | | + +## Contributing + +We welcome everyone to contribute to PHPWord. Below are some of the things that you can do to contribute: + +- Read [our contributing guide](https://github.com/PHPOffice/PHPWord/blob/master/CONTRIBUTING.md) +- [Fork us](https://github.com/PHPOffice/PHPWord/fork) and [request a pull](https://github.com/PHPOffice/PHPWord/pulls) to the [develop](https://github.com/PHPOffice/PHPWord/tree/develop) branch +- Submit [bug reports or feature requests](https://github.com/PHPOffice/PHPWord/issues) to GitHub +- Follow [@PHPWord](https://twitter.com/PHPWord) and [@PHPOffice](https://twitter.com/PHPOffice) on Twitter + +# Installing/configuring + +## Requirements + +Mandatory: + +- PHP 5.3+ +- PHP [Zip](http://php.net/manual/en/book.zip.php) extension +- PHP [XML Parser](http://www.php.net/manual/en/xml.installation.php) extension + +Optional PHP extensions: + +- [GD](http://php.net/manual/en/book.image.php) +- [XMLWriter](http://php.net/manual/en/book.xmlwriter.php) +- [XSL](http://php.net/manual/en/book.xsl.php) + +## Installation + +There are two ways to install PHPWord, i.e. via [Composer](http://getcomposer.org/) or manually by downloading the library. + +### Using Composer + +To install via Composer, add the following lines to your `composer.json`: + +```json +{ + "require": { + "phpoffice/phpword": "dev-master" + } +} +``` + +### Manual install + +To install manually, [download PHPWord package from github](https://github.com/PHPOffice/PHPWord/archive/master.zip). Extract the package and put the contents to your machine. To use the library, include `src/PhpWord/Autoloader.php` in your script and invoke `Autoloader::register`. + +```php +require_once '/path/to/src/PhpWord/Autoloader.php'; +\PhpOffice\PhpWord\Autoloader::register(); +``` + +## Using samples + +After installation, you can browse and use the samples that we've provided, either by command line or using browser. If you can access your PHPWord library folder using browser, point your browser to the `samples` folder, e.g. `http://localhost/PhpWord/samples/`. + +# General usage + +## Basic example + +The following is a basic example of the PHPWord library. More examples are provided in the [samples folder](https://github.com/PHPOffice/PHPWord/tree/master/samples/). + +```php +require_once 'src/PhpWord/Autoloader.php'; +\PhpOffice\PhpWord\Autoloader::register(); + +$phpWord = new \PhpOffice\PhpWord\PhpWord(); + +// Every element you want to append to the word document is placed in a section. +// To create a basic section: +$section = $phpWord->addSection(); + +// After creating a section, you can append elements: +$section->addText('Hello world!'); + +// You can directly style your text by giving the addText function an array: +$section->addText('Hello world! I am formatted.', + array('name'=>'Tahoma', 'size'=>16, 'bold'=>true)); + +// If you often need the same style again you can create a user defined style +// to the word document and give the addText function the name of the style: +$phpWord->addFontStyle('myOwnStyle', + array('name'=>'Verdana', 'size'=>14, 'color'=>'1B2232')); +$section->addText('Hello world! I am formatted by a user defined style', + 'myOwnStyle'); + +// You can also put the appended element to local object like this: +$fontStyle = array( + 'name' => 'Verdana', + 'size' => 22, + 'bold' => true, +); +$myTextElement = $section->addText('Hello World!'); +$myTextElement->setFontStyle($fontStyle); + +// Finally, save the document: +$phpWord->save('helloWorld.docx'); +$phpWord->save('helloWorld.odt', 'ODText'); +$phpWord->save('helloWorld.rtf', 'RTF'); +``` + +## Settings + +The `PhpOffice\PhpWord\Settings` class provides some options that will affect the behavior of PHPWord. Below are the options. + +### XML Writer compatibility + +This option sets [XMLWriter::setIndent](http://www.php.net/manual/en/function.xmlwriter-set-indent.php) and [XMLWriter::setIndentString](http://www.php.net/manual/en/function.xmlwriter-set-indent-string.php). The default value of this option is `true` (compatible), which is [required for OpenOffice](https://github.com/PHPOffice/PHPWord/issues/103) to render OOXML document correctly. You can set this option to `false` during development to make the resulting XML file easier to read. + +```php +\PhpOffice\PhpWord\Settings::setCompatibility(false); +``` + +### Zip class + +By default, PHPWord uses PHP [ZipArchive](http://php.net/manual/en/book.zip.php) to read or write ZIP compressed archive and the files inside them. If you can't have ZipArchive installed on your server, you can use pure PHP library alternative, [PCLZip](http://www.phpconcept.net/pclzip/), which included with PHPWord. + +```php +\PhpOffice\PhpWord\Settings::setZipClass(\PhpOffice\PhpWord\Settings::PCLZIP); +``` + +## Default font + +By default, every text appears in Arial 10 point. You can alter the default font by using the following two functions: + +```php +$phpWord->setDefaultFontName('Times New Roman'); +$phpWord->setDefaultFontSize(12); +``` + +## Document information + +You can set the document information such as title, creator, and company name. Use the following functions: + +```php +$properties = $phpWord->getDocInfo(); +$properties->setCreator('My name'); +$properties->setCompany('My factory'); +$properties->setTitle('My title'); +$properties->setDescription('My description'); +$properties->setCategory('My category'); +$properties->setLastModifiedBy('My name'); +$properties->setCreated(mktime(0, 0, 0, 3, 12, 2014)); +$properties->setModified(mktime(0, 0, 0, 3, 14, 2014)); +$properties->setSubject('My subject'); +$properties->setKeywords('my, key, word'); +``` + +## Measurement units + +The base length unit in Open Office XML is twip. Twip means "TWentieth of an Inch Point", i.e. 1 twip = 1/1440 inch. + +You can use PHPWord helper functions to convert inches, centimeters, or points to twips. + +```php +// Paragraph with 6 points space after +$phpWord->addParagraphStyle('My Style', array( + 'spaceAfter' => \PhpOffice\PhpWord\Shared\Converter::pointToTwip(6)) +); + +$section = $phpWord->addSection(); +$sectionStyle = $section->getStyle(); +// half inch left margin +$sectionStyle->setMarginLeft(\PhpOffice\PhpWord\Shared\Converter::inchToTwip(.5)); +// 2 cm right margin +$sectionStyle->setMarginRight(\PhpOffice\PhpWord\Shared\Converter::cmToTwip(2)); +``` + +# Containers + +Containers are objects where you can put elements (texts, lists, tables, etc). There are 3 main containers, i.e. sections, headers, and footers. There are 3 elements that can also act as containers, i.e. textruns, table cells, and footnotes. + +## Sections + +Every visible element in word is placed inside of a section. To create a section, use the following code: + +```php +$section = $phpWord->addSection($sectionStyle); +``` + +The `$sectionStyle` is an optional associative array that sets the section. Example: + +```php +$sectionStyle = array( + 'orientation' => 'landscape', + 'marginTop' => 600, + 'colsNum' => 2, +); +``` + + +### Page number + +You can change a section page number by using the `pageNumberingStart` style of the section. + +```php +// Method 1 +$section = $phpWord->addSection(array('pageNumberingStart' => 1)); + +// Method 2 +$section = $phpWord->addSection(); +$section->getStyle()->setPageNumberingStart(1); +``` + +### Multicolumn + +You can change a section layout to multicolumn (like in a newspaper) by using the `breakType` and `colsNum` style of the section. + +```php +// Method 1 +$section = $phpWord->addSection(array('breakType' => 'continuous', 'colsNum' => 2)); + +// Method 2 +$section = $phpWord->addSection(); +$section->getStyle()->setBreakType('continuous'); +$section->getStyle()->setColsNum(2); +``` + +### Line numbering + +You can apply line numbering to a section by using the `lineNumbering` style of the section. + +```php +// Method 1 +$section = $phpWord->addSection(array('lineNumbering' => array())); + +// Method 2 +$section = $phpWord->addSection(); +$section->getStyle()->setLineNumbering(array()); +``` + +Below are the properties of the line numbering style. + +- `start` Line numbering starting value +- `increment` Line number increments +- `distance` Distance between text and line numbering in twip +- `restart` Line numbering restart setting continuous|newPage|newSection + +## Headers + +Each section can have its own header reference. To create a header use the `addHeader` method: + +```php +$header = $section->addHeader(); +``` + +Be sure to save the result in a local object. You can use all elements that are available for the footer. See "Footer" section for detail. Additionally, only inside of the header reference you can add watermarks or background pictures. See "Watermarks" section. + +## Footers + +Each section can have its own footer reference. To create a footer, use the `addFooter` method: + +```php +$footer = $section->addFooter(); +``` + +Be sure to save the result in a local object to add elements to a footer. You can add the following elements to footers: + +- Texts `addText` and `createTextrun` +- Text breaks +- Images +- Tables +- Preserve text + +See the "Elements" section for the detail of each elements. + +## Other containers + +Textruns, table cells, and footnotes are elements that can also act as containers. See the corresponding "Elements" section for the detail of each elements. + +# Elements + +Below are the matrix of element availability in each container. The column shows the containers while the rows lists the elements. + +| Num | Element | Section | Header | Footer | Cell | Text Run | Footnote | +|-----|---------------|---------|--------|--------|------|----------|----------| +| 1 | Text | v | v | v | v | v | v | +| 2 | Text Run | v | v | v | v | - | - | +| 3 | Link | v | v | v | v | v | v | +| 4 | Title | v | ? | ? | ? | ? | ? | +| 5 | Preserve Text | ? | v | v | v* | - | - | +| 6 | Text Break | v | v | v | v | v | v | +| 7 | Page Break | v | - | - | - | - | - | +| 8 | List | v | v | v | v | - | - | +| 9 | Table | v | v | v | v | - | - | +| 10 | Image | v | v | v | v | v | v | +| 11 | Watermark | - | v | - | - | - | - | +| 12 | Object | v | v | v | v | v | v | +| 13 | TOC | v | - | - | - | - | - | +| 14 | Footnote | v | - | - | v** | v** | - | +| 15 | Endnote | v | - | - | v** | v** | - | +| 16 | CheckBox | v | v | v | v | - | - | +| 17 | TextBox | v | v | v | v | - | - | +| 18 | Field | v | v | v | v | v | v | +| 19 | Line | v | v | v | v | v | v | +| 20 | Shape | v | v | v | v | v | v | +| 21 | Chart | v | - | - | - | - | - | +| 22 | Form Fields | v | v | v | v | v | v | + +Legend: + +- `v` Available +- `v*` Available only when inside header/footer +- `v**` Available only when inside section +- `-` Not available +- `?` Should be available + +## Texts + +Text can be added by using `addText` and `addTextRun` method. `addText` is used for creating simple paragraphs that only contain texts with the same style. `addTextRun` is used for creating complex paragraphs that contain text with different style (some bold, other italics, etc) or other elements, e.g. images or links. The syntaxes are as follow: + +```php +$section->addText($text, [$fontStyle], [$paragraphStyle]); +$textrun = $section->addTextRun([$paragraphStyle]); +``` + +You can use the `$fontStyle` and `$paragraphStyle` variable to define text formatting. There are 2 options to style the inserted text elements, i.e. inline style by using array or defined style by adding style definition. + +Inline style examples: + +```php +$fontStyle = array('name' => 'Times New Roman', 'size' => 9); +$paragraphStyle = array('align' => 'both'); +$section->addText('I am simple paragraph', $fontStyle, $paragraphStyle); + +$textrun = $section->addTextRun(); +$textrun->addText('I am bold', array('bold' => true)); +$textrun->addText('I am italic', array('italic' => true)); +$textrun->addText('I am colored', array('color' => 'AACC00')); +``` + +Defined style examples: + +```php +$fontStyle = array('color' => '006699', 'size' => 18, 'bold' => true); +$phpWord->addFontStyle('fStyle', $fontStyle); +$text = $section->addText('Hello world!', 'fStyle'); + +$paragraphStyle = array('align' => 'center'); +$phpWord->addParagraphStyle('pStyle', $paragraphStyle); +$text = $section->addText('Hello world!', 'pStyle'); +``` + +### Titles + +If you want to structure your document or build table of contents, you need titles or headings. To add a title to the document, use the `addTitleStyle` and `addTitle` method. + +```php +$phpWord->addTitleStyle($depth, [$fontStyle], [$paragraphStyle]); +$section->addTitle($text, [$depth]); +``` + +Its necessary to add a title style to your document because otherwise the title won't be detected as a real title. + +### Links + +You can add Hyperlinks to the document by using the function addLink: + +```php +$section->addLink($linkSrc, [$linkName], [$fontStyle], [$paragraphStyle]); +``` + +- `$linkSrc` The URL of the link. +- `$linkName` Placeholder of the URL that appears in the document. +- `$fontStyle` See "Font style" section. +- `$paragraphStyle` See "Paragraph style" section. + +### Preserve texts + +The `addPreserveText` method is used to add a page number or page count to headers or footers. + +```php +$footer->addPreserveText('Page {PAGE} of {NUMPAGES}.'); +``` + +## Breaks + +### Text breaks + +Text breaks are empty new lines. To add text breaks, use the following syntax. All paramaters are optional. + +```php +$section->addTextBreak([$breakCount], [$fontStyle], [$paragraphStyle]); +``` + +- `$breakCount` How many lines +- `$fontStyle` See "Font style" section. +- `$paragraphStyle` See "Paragraph style" section. + +### Page breaks + +There are two ways to insert a page breaks, using the `addPageBreak` method or using the `pageBreakBefore` style of paragraph. + +```php +$section->addPageBreak(); +``` + +## Lists + +To add a list item use the function `addListItem`. + +Basic usage: + +```php +$section->addListItem($text, [$depth], [$fontStyle], [$listStyle], [$paragraphStyle]); +``` + +Parameters: + +- `$text` Text that appears in the document. +- `$depth` Depth of list item. +- `$fontStyle` See "Font style" section. +- `$listStyle` List style of the current element TYPE\_NUMBER, TYPE\_ALPHANUM, TYPE\_BULLET\_FILLED, etc. See list of constants in PHPWord\_Style\_ListItem. +- `$paragraphStyle` See "Paragraph style" section. + +Advanced usage: + +You can also create your own numbering style by changing the `$listStyle` parameter with the name of your numbering style. + +```php +$phpWord->addNumberingStyle( + 'multilevel', + array('type' => 'multilevel', 'levels' => array( + array('format' => 'decimal', 'text' => '%1.', 'left' => 360, 'hanging' => 360, 'tabPos' => 360), + array('format' => 'upperLetter', 'text' => '%2.', 'left' => 720, 'hanging' => 360, 'tabPos' => 720), + ) + ) +); +$section->addListItem('List Item I', 0, null, 'multilevel'); +$section->addListItem('List Item I.a', 1, null, 'multilevel'); +$section->addListItem('List Item I.b', 1, null, 'multilevel'); +$section->addListItem('List Item II', 0, null, 'multilevel'); +``` + +## Tables + +To add tables, rows, and cells, use the `addTable`, `addRow`, and `addCell` methods: + +```php +$table = $section->addTable([$tableStyle]); +$table->addRow([$height], [$rowStyle]); +$cell = $table->addCell($width, [$cellStyle]); +``` + +Table style can be defined with `addTableStyle`: + +```php +$tableStyle = array( + 'borderColor' => '006699', + 'borderSize' => 6, + 'cellMargin' => 50 +); +$firstRowStyle = array('bgColor' => '66BBFF'); +$phpWord->addTableStyle('myTable', $tableStyle, $firstRowStyle); +$table = $section->addTable('myTable'); +``` + +### Cell span + +You can span a cell on multiple columns by using `gridSpan` or multiple rows by using `vMerge`. + +```php +$cell = $table->addCell(200); +$cell->getStyle()->setGridSpan(5); +``` + +See `Sample_09_Tables.php` for more code sample. + +## Images + +To add an image, use the `addImage` method to sections, headers, footers, textruns, or table cells. + +```php +$section->addImage($src, [$style]); +``` + +- source String path to a local image or URL of a remote image +- styles Array fo styles for the image. See below. + +Examples: + +```php +$section = $phpWord->addSection(); +$section->addImage( + 'mars.jpg', + array( + 'width' => 100, + 'height' => 100, + 'marginTop' => -1, + 'marginLeft' => -1, + 'wrappingStyle' => 'behind' + ) +); +$footer = $section->addFooter(); +$footer->addImage('http://example.com/image.php'); +$textrun = $section->addTextRun(); +$textrun->addImage('http://php.net/logo.jpg'); +``` + +### Watermarks + +To add a watermark (or page background image), your section needs a header reference. After creating a header, you can use the `addWatermark` method to add a watermark. + +```php +$section = $phpWord->addSection(); +$header = $section->addHeader(); +$header->addWatermark('resources/_earth.jpg', array('marginTop' => 200, 'marginLeft' => 55)); +``` + +## Objects + +You can add OLE embeddings, such as Excel spreadsheets or PowerPoint presentations to the document by using `addObject` method. + +```php +$section->addObject($src, [$style]); +``` + +## Table of contents + +To add a table of contents (TOC), you can use the `addTOC` method. Your TOC can only be generated if you have add at least one title (See "Titles"). + +```php +$section->addTOC([$fontStyle], [$tocStyle], [$minDepth], [$maxDepth]); +``` + +- `$fontStyle`: See font style section +- `$tocStyle`: See available options below +- `$minDepth`: Minimum depth of header to be shown. Default 1 +- `$maxDepth`: Maximum depth of header to be shown. Default 9 + +Options for `$tocStyle`: + +- `tabLeader` Fill type between the title text and the page number. Use the defined constants in PHPWord\_Style\_TOC. +- `tabPos` The position of the tab where the page number appears in twips. +- `indent` The indent factor of the titles in twips. + +## Footnotes & endnotes + +You can create footnotes with `addFootnote` and endnotes with `addEndnote` in texts or textruns, but it's recommended to use textrun to have better layout. You can use `addText`, `addLink`, `addTextBreak`, `addImage`, `addObject` on footnotes and endnotes. + +On textrun: + +```php +$textrun = $section->addTextRun(); +$textrun->addText('Lead text.'); +$footnote = $textrun->addFootnote(); +$footnote->addText('Footnote text can have '); +$footnote->addLink('http://test.com', 'links'); +$footnote->addText('.'); +$footnote->addTextBreak(); +$footnote->addText('And text break.'); +$textrun->addText('Trailing text.'); +$endnote = $textrun->addEndnote(); +$endnote->addText('Endnote put at the end'); +``` + +On text: + +```php +$section->addText('Lead text.'); +$footnote = $section->addFootnote(); +$footnote->addText('Footnote text.'); +``` + +The footnote reference number will be displayed with decimal number starting from 1. This number use `FooterReference` style which you can redefine by `addFontStyle` method. Default value for this style is `array('superScript' => true)`; + +## Checkboxes + +Checkbox elements can be added to sections or table cells by using `addCheckBox`. + +```php +$section->addCheckBox($name, $text, [$fontStyle], [$paragraphStyle]) +``` + +- `$name` Name of the check box. +- `$text` Text following the check box +- `$fontStyle` See "Font style" section. +- `$paragraphStyle` See "Paragraph style" section. + +## Textboxes + +To be completed. + +## Fields + +To be completed. + +## Lines + +To be completed. + +## Shapes + +To be completed. + +## Charts + +To be completed. + +## Form fields + +To be completed. + +# Styles + +## Section + +Below are the available styles for section: + +- `orientation` Page orientation, i.e. 'portrait' (default) or 'landscape' +- `marginTop` Page margin top in twips +- `marginLeft` Page margin left in twips +- `marginRight` Page margin right in twips +- `marginBottom` Page margin bottom in twips +- `borderTopSize` Border top size in twips +- `borderTopColor` Border top color +- `borderLeftSize` Border left size in twips +- `borderLeftColor` Border left color +- `borderRightSize` Border right size in twips +- `borderRightColor` Border right color +- `borderBottomSize` Border bottom size in twips +- `borderBottomColor` Border bottom color +- `headerHeight` Spacing to top of header +- `footerHeight` Spacing to bottom of footer +- `gutter` Page gutter spacing +- `colsNum` Number of columns +- `colsSpace` Spacing between columns +- `breakType` Section break type (nextPage, nextColumn, continuous, evenPage, oddPage) + +The following two styles are automatically set by the use of the `orientation` style. You can alter them but that's not recommended. + +- `pageSizeW` Page width in twips +- `pageSizeH` Page height in twips + +## Font + +Available font styles: + +- `name` Font name, e.g. *Arial* +- `size` Font size, e.g. *20*, *22*, +- `hint` Font content type, *default*, *eastAsia*, or *cs* +- `bold` Bold, *true* or *false* +- `italic` Italic, *true* or *false* +- `superScript` Superscript, *true* or *false* +- `subScript` Subscript, *true* or *false* +- `underline` Underline, *dash*, *dotted*, etc. +- `strikethrough` Strikethrough, *true* or *false* +- `doubleStrikethrough` Double strikethrough, *true* or *false* +- `color` Font color, e.g. *FF0000* +- `fgColor` Font highlight color, e.g. *yellow*, *green*, *blue* +- `bgColor` Font background color, e.g. *FF0000* +- `smallCaps` Small caps, *true* or *false* +- `allCaps` All caps, *true* or *false* + +## Paragraph + +Available paragraph styles: + +- `align` Paragraph alignment, *left*, *right* or *center* +- `spaceBefore` Space before paragraph +- `spaceAfter` Space after paragraph +- `indent` Indent by how much +- `hanging` Hanging by how much +- `basedOn` Parent style +- `next` Style for next paragraph +- `widowControl` Allow first/last line to display on a separate page, *true* or *false* +- `keepNext` Keep paragraph with next paragraph, *true* or *false* +- `keepLines` Keep all lines on one page, *true* or *false* +- `pageBreakBefore` Start paragraph on next page, *true* or *false* +- `lineHeight` text line height, e.g. *1.0*, *1.5*, ect... +- `tabs` Set of custom tab stops + +## Table + +Table styles: + +- `width` Table width in percent +- `bgColor` Background color, e.g. '9966CC' +- `border(Top|Right|Bottom|Left)Size` Border size in twips +- `border(Top|Right|Bottom|Left)Color` Border color, e.g. '9966CC' +- `cellMargin(Top|Right|Bottom|Left)` Cell margin in twips + +Row styles: + +- `tblHeader` Repeat table row on every new page, *true* or *false* +- `cantSplit` Table row cannot break across pages, *true* or *false* +- `exactHeight` Row height is exact or at least + +Cell styles: + +- `width` Cell width in twips +- `valign` Vertical alignment, *top*, *center*, *both*, *bottom* +- `textDirection` Direction of text +- `bgColor` Background color, e.g. '9966CC' +- `border(Top|Right|Bottom|Left)Size` Border size in twips +- `border(Top|Right|Bottom|Left)Color` Border color, e.g. '9966CC' +- `gridSpan` Number of columns spanned +- `vMerge` *restart* or *continue* + +## Image + +Available image styles: + +- `width` Width in pixels +- `height` Height in pixels +- `align` Image alignment, *left*, *right*, or *center* +- `marginTop` Top margin in inches, can be negative +- `marginLeft` Left margin in inches, can be negative +- `wrappingStyle` Wrapping style, *inline*, *square*, *tight*, *behind*, or *infront* + +## Numbering level + +- `start` Starting value +- `format` Numbering format bullet|decimal|upperRoman|lowerRoman|upperLetter|lowerLetter +- `restart` Restart numbering level symbol +- `suffix` Content between numbering symbol and paragraph text tab|space|nothing +- `text` Numbering level text e.g. %1 for nonbullet or bullet character +- `align` Numbering symbol align left|center|right|both +- `left` See paragraph style +- `hanging` See paragraph style +- `tabPos` See paragraph style +- `font` Font name +- `hint` See font style + +# Templates + +You can create a docx template with included search-patterns that can be replaced by any value you wish. Only single-line values can be replaced. To load a template file, use the `loadTemplate` method. After loading the docx template, you can use the `setValue` method to change the value of a search pattern. The search-pattern model is: `${search-pattern}`. It is not possible to add new PHPWord elements to a loaded template file. + +Example: + +```php +$template = $phpWord->loadTemplate('Template.docx'); +$template->setValue('Name', 'Somebody someone'); +$template->setValue('Street', 'Coming-Undone-Street 32'); +``` + +See `Sample_07_TemplateCloneRow.php` for example on how to create multirow from a single row in a template by using `cloneRow`. + +See `Sample_23_TemplateBlock.php` for example on how to clone a block of text using `cloneBlock` and delete a block of text using `deleteBlock`. + +# Writers & readers + +## OOXML + +The package of OOXML document consists of the following files. + +- _rels/ + - .rels +- docProps/ + - app.xml + - core.xml + - custom.xml +- word/ + - rels/ + - document.rels.xml + - media/ + - theme/ + - theme1.xml + - document.xml + - fontTable.xml + - numbering.xml + - settings.xml + - styles.xml + - webSettings.xml +- [Content_Types].xml + +## OpenDocument + +### Package + +The package of OpenDocument document consists of the following files. + +- META-INF/ + - manifest.xml +- Pictures/ +- content.xml +- meta.xml +- styles.xml + +### content.xml + +The structure of `content.xml` is described below. + +- office:document-content + - office:font-facedecls + - office:automatic-styles + - office:body + - office:text + - draw:* + - office:forms + - table:table + - text:list + - text:numbered-paragraph + - text:p + - text:table-of-contents + - text:section + - office:chart + - office:image + - office:drawing + +### styles.xml + +The structure of `styles.xml` is described below. + +- office:document-styles + - office:styles + - office:automatic-styles + - office:master-styles + - office:master-page + +## RTF + +To be completed. + +## HTML + +To be completed. + +## PDF + +To be completed. + +# Recipes + +## Create float left image + +Use absolute positioning relative to margin horizontally and to line vertically. + +```php +$imageStyle = array( + 'width' => 40, + 'height' => 40 + 'wrappingStyle' => 'square', + 'positioning' => 'absolute', + 'posHorizontalRel' => 'margin', + 'posVerticalRel' => 'line', +); +$textrun->addImage('resources/_earth.jpg', $imageStyle); +$textrun->addText($lipsumText); +``` + +## Download the produced file automatically + +Use `php://output` as the filename. + +```php +$phpWord = new \PhpOffice\PhpWord\PhpWord(); +$section = $phpWord->createSection(); +$section->addText('Hello World!'); +$file = 'HelloWorld.docx'; +header("Content-Description: File Transfer"); +header('Content-Disposition: attachment; filename="' . $file . '"'); +header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); +header('Content-Transfer-Encoding: binary'); +header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); +header('Expires: 0'); +$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); +$xmlWriter->save("php://output"); +``` + +## Create numbered headings + +Define a numbering style and title styles, and match the two styles (with `pStyle` and `numStyle`) like below. + +```php +$phpWord->addNumberingStyle( + 'hNum', + array('type' => 'multilevel', 'levels' => array( + array('pStyle' => 'Heading1', 'format' => 'decimal', 'text' => '%1'), + array('pStyle' => 'Heading2', 'format' => 'decimal', 'text' => '%1.%2'), + array('pStyle' => 'Heading3', 'format' => 'decimal', 'text' => '%1.%2.%3'), + ) + ) +); +$phpWord->addTitleStyle(1, array('size' => 16), array('numStyle' => 'hNum', 'numLevel' => 0)); +$phpWord->addTitleStyle(2, array('size' => 14), array('numStyle' => 'hNum', 'numLevel' => 1)); +$phpWord->addTitleStyle(3, array('size' => 12), array('numStyle' => 'hNum', 'numLevel' => 2)); + +$section->addTitle('Heading 1', 1); +$section->addTitle('Heading 2', 2); +$section->addTitle('Heading 3', 3); +``` + +## Add a link within a title + +Apply 'HeadingN' paragraph style to TextRun or Link. Sample code: + +```php +$phpWord = new \PhpOffice\PhpWord\PhpWord(); +$phpWord->addTitleStyle(1, array('size' => 16, 'bold' => true)); +$phpWord->addTitleStyle(2, array('size' => 14, 'bold' => true)); +$phpWord->addFontStyle('Link', array('color' => '0000FF', 'underline' => 'single')); + +$section = $phpWord->addSection(); + +// Textrun +$textrun = $section->addTextRun('Heading1'); +$textrun->addText('The '); +$textrun->addLink('https://github.com/PHPOffice/PHPWord', 'PHPWord', 'Link'); + +// Link +$section->addLink('https://github.com/', 'GitHub', 'Link', 'Heading2'); +``` + +## Remove [Compatibility Mode] text in the MS Word title bar + +Use the `Metadata\Compatibility\setOoxmlVersion(n)` method with `n` is the version of Office (14 = Office 2010, 15 = Office 2013). + +```php +$phpWord->getCompatibility()->setOoxmlVersion(15); +``` + +# Frequently asked questions + +## Is this the same with PHPWord that I found in CodePlex? + +No. This one is much better with tons of new features that you can’t find in PHPWord 0.6.3. The development in CodePlex is halted and switched to GitHub to allow more participation from the crowd. The more the merrier, right? + +## I’ve been running PHPWord from CodePlex flawlessly, but I can’t use the latest PHPWord from GitHub. Why? + +PHPWord requires PHP 5.3+ since 0.8, while PHPWord 0.6.3 from CodePlex can run with PHP 5.2. There’s a lot of new features that we can get from PHP 5.3 and it’s been around since 2009! You should upgrade your PHP version to use PHPWord 0.8+. + +# References + +## ISO/IEC 29500, Third edition, 2012-09-01 + +- [Part 1: Fundamentals and Markup Language Reference](http://standards.iso.org/ittf/PubliclyAvailableStandards/c061750_ISO_IEC_29500-1_2012.zip) +- [Part 2: Open Packaging Conventions](http://standards.iso.org/ittf/PubliclyAvailableStandards/c061796_ISO_IEC_29500-2_2012.zip) +- [Part 3: Markup Compatibility and Extensibility](http://standards.iso.org/ittf/PubliclyAvailableStandards/c061797_ISO_IEC_29500-3_2012.zip) +- [Part 4: Transitional Migration Features](http://standards.iso.org/ittf/PubliclyAvailableStandards/c061798_ISO_IEC_29500-4_2012.zip) + +## Formal specifications + +- [Oasis OpenDocument Standard Version 1.2](http://docs.oasis-open.org/office/v1.2/os/OpenDocument-v1.2-os.html) +- [Rich Text Format (RTF) Specification, version 1.9.1](http://www.microsoft.com/en-us/download/details.aspx?id=10725) + +## Other resources + +- [DocumentFormat.OpenXml.Wordprocessing Namespace on MSDN](http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing%28v=office.14%29.aspx) diff --git a/docs/styles.rst b/docs/styles.rst new file mode 100644 index 00000000..91d5ed7a --- /dev/null +++ b/docs/styles.rst @@ -0,0 +1,138 @@ +.. _styles: + +Styles +====== + +Section +------- + +Below are the available styles for section: + +- ``orientation`` Page orientation, i.e. 'portrait' (default) or + 'landscape' +- ``marginTop`` Page margin top in twips +- ``marginLeft`` Page margin left in twips +- ``marginRight`` Page margin right in twips +- ``marginBottom`` Page margin bottom in twips +- ``borderTopSize`` Border top size in twips +- ``borderTopColor`` Border top color +- ``borderLeftSize`` Border left size in twips +- ``borderLeftColor`` Border left color +- ``borderRightSize`` Border right size in twips +- ``borderRightColor`` Border right color +- ``borderBottomSize`` Border bottom size in twips +- ``borderBottomColor`` Border bottom color +- ``headerHeight`` Spacing to top of header +- ``footerHeight`` Spacing to bottom of footer +- ``gutter`` Page gutter spacing +- ``colsNum`` Number of columns +- ``colsSpace`` Spacing between columns +- ``breakType`` Section break type (nextPage, nextColumn, continuous, + evenPage, oddPage) + +The following two styles are automatically set by the use of the +``orientation`` style. You can alter them but that's not recommended. + +- ``pageSizeW`` Page width in twips +- ``pageSizeH`` Page height in twips + +Font +---- + +Available font styles: + +- ``name`` Font name, e.g. *Arial* +- ``size`` Font size, e.g. *20*, *22*, +- ``hint`` Font content type, *default*, *eastAsia*, or *cs* +- ``bold`` Bold, *true* or *false* +- ``italic`` Italic, *true* or *false* +- ``superScript`` Superscript, *true* or *false* +- ``subScript`` Subscript, *true* or *false* +- ``underline`` Underline, *dash*, *dotted*, etc. +- ``strikethrough`` Strikethrough, *true* or *false* +- ``doubleStrikethrough`` Double strikethrough, *true* or *false* +- ``color`` Font color, e.g. *FF0000* +- ``fgColor`` Font highlight color, e.g. *yellow*, *green*, *blue* +- ``bgColor`` Font background color, e.g. *FF0000* +- ``smallCaps`` Small caps, *true* or *false* +- ``allCaps`` All caps, *true* or *false* +- ``rtl`` Right to Left language, *true* or *false* + +Paragraph +--------- + +Available paragraph styles: + +- ``align`` Paragraph alignment, *left*, *right* or *center* +- ``spaceBefore`` Space before paragraph +- ``spaceAfter`` Space after paragraph +- ``indent`` Indent by how much +- ``hanging`` Hanging by how much +- ``basedOn`` Parent style +- ``next`` Style for next paragraph +- ``widowControl`` Allow first/last line to display on a separate page, + *true* or *false* +- ``keepNext`` Keep paragraph with next paragraph, *true* or *false* +- ``keepLines`` Keep all lines on one page, *true* or *false* +- ``pageBreakBefore`` Start paragraph on next page, *true* or *false* +- ``lineHeight`` text line height, e.g. *1.0*, *1.5*, ect... +- ``tabs`` Set of custom tab stops + +Table +----- + +Table styles: + +- ``width`` Table width in percent +- ``bgColor`` Background color, e.g. '9966CC' +- ``border(Top|Right|Bottom|Left)Size`` Border size in twips +- ``border(Top|Right|Bottom|Left)Color`` Border color, e.g. '9966CC' +- ``cellMargin(Top|Right|Bottom|Left)`` Cell margin in twips + +Row styles: + +- ``tblHeader`` Repeat table row on every new page, *true* or *false* +- ``cantSplit`` Table row cannot break across pages, *true* or *false* +- ``exactHeight`` Row height is exact or at least + +Cell styles: + +- ``width`` Cell width in twips +- ``valign`` Vertical alignment, *top*, *center*, *both*, *bottom* +- ``textDirection`` Direction of text +- ``bgColor`` Background color, e.g. '9966CC' +- ``border(Top|Right|Bottom|Left)Size`` Border size in twips +- ``border(Top|Right|Bottom|Left)Color`` Border color, e.g. '9966CC' +- ``gridSpan`` Number of columns spanned +- ``vMerge`` *restart* or *continue* + +Image +----- + +Available image styles: + +- ``width`` Width in pixels +- ``height`` Height in pixels +- ``align`` Image alignment, *left*, *right*, or *center* +- ``marginTop`` Top margin in inches, can be negative +- ``marginLeft`` Left margin in inches, can be negative +- ``wrappingStyle`` Wrapping style, *inline*, *square*, *tight*, + *behind*, or *infront* + +Numbering level +--------------- + +- ``start`` Starting value +- ``format`` Numbering format + bullet\|decimal\|upperRoman\|lowerRoman\|upperLetter\|lowerLetter +- ``restart`` Restart numbering level symbol +- ``suffix`` Content between numbering symbol and paragraph text + tab\|space\|nothing +- ``text`` Numbering level text e.g. %1 for nonbullet or bullet + character +- ``align`` Numbering symbol align left\|center\|right\|both +- ``left`` See paragraph style +- ``hanging`` See paragraph style +- ``tabPos`` See paragraph style +- ``font`` Font name +- ``hint`` See font style diff --git a/docs/templates.rst b/docs/templates.rst index ec9c7126..b1d9d205 100644 --- a/docs/templates.rst +++ b/docs/templates.rst @@ -19,8 +19,9 @@ Example: $template->setValue('Name', 'Somebody someone'); $template->setValue('Street', 'Coming-Undone-Street 32'); -See ``Sample_07_TemplateCloneRow.php`` for example on how to create multirow -from a single row in a template by using ``cloneRow``. +See ``Sample_07_TemplateCloneRow.php`` for example on how to create +multirow from a single row in a template by using ``cloneRow``. -See ``Sample_23_TemplateBlock.php`` for example on how to clone a block of -text using ``cloneBlock`` and delete a block of text using ``deleteBlock``. +See ``Sample_23_TemplateBlock.php`` for example on how to clone a block +of text using ``cloneBlock`` and delete a block of text using +``deleteBlock``. diff --git a/docs/writersreaders.rst b/docs/writersreaders.rst new file mode 100644 index 00000000..34a0805a --- /dev/null +++ b/docs/writersreaders.rst @@ -0,0 +1,110 @@ +.. _writersreaders: + +Writers & readers +================= + +OOXML +----- + +The package of OOXML document consists of the following files. + +- \_rels/ + + - .rels + +- docProps/ + + - app.xml + - core.xml + - custom.xml + +- word/ + + - rels/ + + - document.rels.xml + + - media/ + - theme/ + + - theme1.xml + + - document.xml + - fontTable.xml + - numbering.xml + - settings.xml + - styles.xml + - webSettings.xml + +- [Content\_Types].xml + +OpenDocument +------------ + +Package +~~~~~~~ + +The package of OpenDocument document consists of the following files. + +- META-INF/ + + - manifest.xml + +- Pictures/ +- content.xml +- meta.xml +- styles.xml + +content.xml +~~~~~~~~~~~ + +The structure of ``content.xml`` is described below. + +- office:document-content + + - office:font-facedecls + - office:automatic-styles + - office:body + + - office:text + + - draw:\* + - office:forms + - table:table + - text:list + - text:numbered-paragraph + - text:p + - text:table-of-contents + - text:section + + - office:chart + - office:image + - office:drawing + +styles.xml +~~~~~~~~~~ + +The structure of ``styles.xml`` is described below. + +- office:document-styles + + - office:styles + - office:automatic-styles + - office:master-styles + + - office:master-page + +RTF +--- + +To be completed. + +HTML +---- + +To be completed. + +PDF +--- + +To be completed. diff --git a/phpmd.xml.dist b/phpmd.xml.dist new file mode 100644 index 00000000..5eb348ec --- /dev/null +++ b/phpmd.xml.dist @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/phpunit.xml.dist b/phpunit.xml.dist index f77b9ce3..015dd2ed 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -10,7 +10,7 @@ syntaxCheck="false"> - ./tests/PhpWord/ + ./tests/PhpWord @@ -21,4 +21,8 @@ + + + + \ No newline at end of file diff --git a/phpword.ini.dist b/phpword.ini.dist new file mode 100644 index 00000000..f8eafb6a --- /dev/null +++ b/phpword.ini.dist @@ -0,0 +1,15 @@ +; Default config file for PHPWord +; Copy this file into phpword.ini and use Settings::loadConfig to load + +[General] + +compatibility = true +zipClass = ZipArchive +pdfRendererName = DomPDF +pdfRendererPath = +; tempDir = "C:\PhpWordTemp" + +[Font] + +defaultFontName = Arial +defaultFontSize = 10 diff --git a/samples/Sample_01_SimpleText.php b/samples/Sample_01_SimpleText.php old mode 100755 new mode 100644 index 02b78bd7..8c93f917 --- a/samples/Sample_01_SimpleText.php +++ b/samples/Sample_01_SimpleText.php @@ -4,7 +4,7 @@ include_once 'Sample_Header.php'; // New Word Document echo date('H:i:s') , " Create new PhpWord object" , EOL; $phpWord = new \PhpOffice\PhpWord\PhpWord(); -$phpWord->addFontStyle('rStyle', array('bold' => true, 'italic' => true, 'size' => 16)); +$phpWord->addFontStyle('rStyle', array('bold' => true, 'italic' => true, 'size' => 16, 'allCaps' => true, 'doubleStrikethrough' => true)); $phpWord->addParagraphStyle('pStyle', array('align' => 'center', 'spaceAfter' => 100)); $phpWord->addTitleStyle(1, array('bold' => true), array('spaceAfter' => 240)); @@ -22,36 +22,54 @@ $section->addTextBreak(2); $section->addText('I am styled by a font style definition.', 'rStyle'); $section->addText('I am styled by a paragraph style definition.', null, 'pStyle'); $section->addText('I am styled by both font and paragraph style.', 'rStyle', 'pStyle'); + $section->addTextBreak(); // Inline font style $fontStyle['name'] = 'Times New Roman'; $fontStyle['size'] = 20; -$fontStyle['bold'] = true; -$fontStyle['italic'] = true; -$fontStyle['underline'] = 'dash'; -$fontStyle['strikethrough'] = true; -$fontStyle['superScript'] = true; -$fontStyle['color'] = 'FF0000'; -$fontStyle['fgColor'] = 'yellow'; -$section->addText('I am inline styled.', $fontStyle); -$section->addTextBreak(); + +$textrun = $section->addTextRun(); +$textrun->addText('I am inline styled ', $fontStyle); +$textrun->addText('with '); +$textrun->addText('color', array('color' => '996699')); +$textrun->addText(', '); +$textrun->addText('bold', array('bold' => true)); +$textrun->addText(', '); +$textrun->addText('italic', array('italic' => true)); +$textrun->addText(', '); +$textrun->addText('underline', array('underline' => 'dash')); +$textrun->addText(', '); +$textrun->addText('strikethrough', array('strikethrough' => true)); +$textrun->addText(', '); +$textrun->addText('doubleStrikethrough', array('doubleStrikethrough' => true)); +$textrun->addText(', '); +$textrun->addText('superScript', array('superScript' => true)); +$textrun->addText(', '); +$textrun->addText('subScript', array('subScript' => true)); +$textrun->addText(', '); +$textrun->addText('smallCaps', array('smallCaps' => true)); +$textrun->addText(', '); +$textrun->addText('allCaps', array('allCaps' => true)); +$textrun->addText(', '); +$textrun->addText('fgColor', array('fgColor' => 'yellow')); +$textrun->addText(', '); +$textrun->addText('scale', array('scale' => 200)); +$textrun->addText(', '); +$textrun->addText('spacing', array('spacing' => 120)); +$textrun->addText(', '); +$textrun->addText('kerning', array('kerning' => 10)); +$textrun->addText('. '); // Link -$section->addLink('http://www.google.com', null, 'NLink'); +$section->addLink('http://www.google.com', 'Google'); $section->addTextBreak(); // Image $section->addImage('resources/_earth.jpg', array('width'=>18, 'height'=>18)); // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_02_TabStops.php b/samples/Sample_02_TabStops.php old mode 100755 new mode 100644 index dbed59a3..d6e4cdbc --- a/samples/Sample_02_TabStops.php +++ b/samples/Sample_02_TabStops.php @@ -33,13 +33,7 @@ $section->addText("Left Aligned\tRight Aligned", null, 'rightTab'); $section->addText("\tCenter Aligned", null, 'centerTab'); // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_03_Sections.php b/samples/Sample_03_Sections.php old mode 100755 new mode 100644 index 4953b6a6..9ed75c73 --- a/samples/Sample_03_Sections.php +++ b/samples/Sample_03_Sections.php @@ -16,8 +16,8 @@ $section->addPageBreak(); $section->addPageBreak(); // New portrait section -$section = $phpWord->addSection(array('marginLeft' => 600, 'marginRight' => 600, 'marginTop' => 600, 'marginBottom' => 600)); -$section->addText('This section uses other margins.'); +$section = $phpWord->addSection(array('paperSize' => 'Folio', 'marginLeft' => 600, 'marginRight' => 600, 'marginTop' => 600, 'marginBottom' => 600)); +$section->addText('This section uses other margins with folio papersize.'); // New portrait section with Header & Footer $section = $phpWord->addSection(array('marginLeft' => 200, 'marginRight' => 200, 'marginTop' => 200, 'marginBottom' => 200, 'headerHeight' => 50, 'footerHeight' => 50,)); @@ -26,13 +26,7 @@ $section->addHeader()->addText('Header'); $section->addFooter()->addText('Footer'); // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_04_Textrun.php b/samples/Sample_04_Textrun.php index 354eadfd..e41f4ddb 100644 --- a/samples/Sample_04_Textrun.php +++ b/samples/Sample_04_Textrun.php @@ -8,7 +8,7 @@ $phpWord = new \PhpOffice\PhpWord\PhpWord(); // Ads styles $phpWord->addParagraphStyle('pStyle', array('spacing'=>100)); $phpWord->addFontStyle('BoldText', array('bold'=>true)); -$phpWord->addFontStyle('ColoredText', array('color'=>'FF8080')); +$phpWord->addFontStyle('ColoredText', array('color'=>'FF8080', 'bgColor' => 'FFFFCC')); $phpWord->addLinkStyle('NLink', array('color'=>'0000FF', 'underline' => \PhpOffice\PhpWord\Style\Font::UNDERLINE_SINGLE)); // New portrait section @@ -34,13 +34,7 @@ $textrun->addObject('resources/_sheet.xls'); $textrun->addText(' Here is some more text. '); // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_05_Multicolumn.php b/samples/Sample_05_Multicolumn.php index 478a8dd0..f4737060 100644 --- a/samples/Sample_05_Multicolumn.php +++ b/samples/Sample_05_Multicolumn.php @@ -18,7 +18,7 @@ $section = $phpWord->addSection(array( 'colsNum' => 2, 'colsSpace' => 1440, 'breakType' => 'continuous')); -$section->addText('Three columns, one inch (1440 twips) spacing. ' . $filler); +$section->addText('Two columns, one inch (1440 twips) spacing. ' . $filler); // Normal $section = $phpWord->addSection(array('breakType' => 'continuous')); @@ -36,13 +36,7 @@ $section = $phpWord->addSection(array('breakType' => 'continuous')); $section->addText('Normal paragraph again.'); // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_06_Footnote.php b/samples/Sample_06_Footnote.php old mode 100755 new mode 100644 index 75120088..1bec44e4 --- a/samples/Sample_06_Footnote.php +++ b/samples/Sample_06_Footnote.php @@ -38,13 +38,7 @@ $footnote = $section->addFootnote(); $footnote->addText('The reference for this is wrapped in its own line'); // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_07_TemplateCloneRow.php b/samples/Sample_07_TemplateCloneRow.php old mode 100755 new mode 100644 index 3049466d..899bc82b --- a/samples/Sample_07_TemplateCloneRow.php +++ b/samples/Sample_07_TemplateCloneRow.php @@ -60,4 +60,7 @@ echo date('H:i:s'), " Write to Word2007 format", EOL; $document->saveAs($name); rename($name, "results/{$name}"); -include_once 'Sample_Footer.php'; +echo getEndingNotes(array('Word2007' => 'docx')); +if (!CLI) { + include_once 'Sample_Footer.php'; +} diff --git a/samples/Sample_08_ParagraphPagination.php b/samples/Sample_08_ParagraphPagination.php index bf1400a0..f3914758 100644 --- a/samples/Sample_08_ParagraphPagination.php +++ b/samples/Sample_08_ParagraphPagination.php @@ -6,7 +6,7 @@ echo date('H:i:s') , " Create new PhpWord object" , EOL; $phpWord = new \PhpOffice\PhpWord\PhpWord(); $phpWord->setDefaultParagraphStyle(array( 'align' => 'both', - 'spaceAfter' => \PhpOffice\PhpWord\Shared\Font::pointSizeToTwips(12), + 'spaceAfter' => \PhpOffice\PhpWord\Shared\Converter::pointToTwip(12), 'spacing' => 120, )); @@ -16,26 +16,26 @@ $section = $phpWord->addSection(); $section->addText('Below are the samples on how to control your paragraph ' . 'pagination. See "Line and Page Break" tab on paragraph properties ' . 'window to see the attribute set by these controls.', - array('bold' => true), null); + array('bold' => true), array('space' => array('before' => 360, 'after' => 480))); $section->addText('Paragraph with widowControl = false (default: true). ' . 'A "widow" is the last line of a paragraph printed by itself at the top ' . 'of a page. An "orphan" is the first line of a paragraph printed by ' . 'itself at the bottom of a page. Set this option to "false" if you want ' . 'to disable this automatic control.', - null, array('widowControl' => false)); + null, array('widowControl' => false, 'indentation' => array('left' => 240, 'right' => 120))); $section->addText('Paragraph with keepNext = true (default: false). ' . '"Keep with next" is used to prevent Word from inserting automatic page ' . 'breaks between paragraphs. Set this option to "true" if you do not want ' . 'your paragraph to be separated with the next paragraph.', - null, array('keepNext' => true)); + null, array('keepNext' => true, 'indentation' => array('firstLine' => 240))); $section->addText('Paragraph with keepLines = true (default: false). ' . '"Keep lines together" will prevent Word from inserting an automatic page ' . 'break within a paragraph. Set this option to "true" if you do not want ' . 'all lines of your paragraph to be in the same page.', - null, array('keepLines' => true)); + null, array('keepLines' => true, 'indentation' => array('left' => 240, 'hanging' => 240))); $section->addText('Keep scrolling. More below.'); @@ -46,13 +46,7 @@ $section->addText('Paragraph with pageBreakBefore = true (default: false). ' . null, array('pageBreakBefore' => true)); // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_09_Tables.php b/samples/Sample_09_Tables.php index 5af73fb6..882653bc 100644 --- a/samples/Sample_09_Tables.php +++ b/samples/Sample_09_Tables.php @@ -51,11 +51,11 @@ for($i = 1; $i <= 8; $i++) { // 3. colspan (gridSpan) and rowspan (vMerge) -$section->addTextBreak(1); +$section->addPageBreak(); $section->addText("Table with colspan and rowspan", $header); $styleTable = array('borderSize' => 6, 'borderColor' => '999999'); -$cellRowSpan = array('vMerge' => 'restart', 'valign' => 'center'); +$cellRowSpan = array('vMerge' => 'restart', 'valign' => 'center', 'bgColor' => 'FFFF00'); $cellRowContinue = array('vMerge' => 'continue'); $cellColSpan = array('gridSpan' => 2, 'valign' => 'center'); $cellHCentered = array('align' => 'center'); @@ -84,14 +84,19 @@ $table->addCell(2000, $cellVCentered)->addText('C', null, $cellHCentered); $table->addCell(2000, $cellVCentered)->addText('D', null, $cellHCentered); $table->addCell(null, $cellRowContinue); -// Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); -} +// 4. Nested table -include_once 'Sample_Footer.php'; +$section->addTextBreak(2); +$section->addText('Nested table in a centered and 50% width table.', $header); + +$table = $section->addTable(array('width' => 50 * 50, 'unit' => 'pct', 'align' => 'center')); +$cell = $table->addRow()->addCell(); +$cell->addText('This cell contains nested table.'); +$innerCell = $cell->addTable(array('align' => 'center'))->addRow()->addCell(); +$innerCell->addText('Inside nested table'); + +// Save file +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; +} diff --git a/samples/Sample_10_EastAsianFontStyle.php b/samples/Sample_10_EastAsianFontStyle.php index 39f449c3..44bca8a6 100644 --- a/samples/Sample_10_EastAsianFontStyle.php +++ b/samples/Sample_10_EastAsianFontStyle.php @@ -10,13 +10,7 @@ $header = array('size' => 16, 'bold' => true); $section->addText('中文楷体样式测试',array('name' => '楷体', 'size' => 16, 'color' => '1B2232')); // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_11_ReadWord2007.php b/samples/Sample_11_ReadWord2007.php index e5112e2e..c0b54c7a 100644 --- a/samples/Sample_11_ReadWord2007.php +++ b/samples/Sample_11_ReadWord2007.php @@ -3,17 +3,13 @@ include_once 'Sample_Header.php'; // Read contents $name = basename(__FILE__, '.php'); -$source = "resources/{$name}.docx"; +$source = __DIR__ . "/resources/{$name}.docx"; + echo date('H:i:s'), " Reading contents from `{$source}`", EOL; $phpWord = \PhpOffice\PhpWord\IOFactory::load($source); -// (Re)write contents -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +// Save file +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_12_HeaderFooter.php b/samples/Sample_12_HeaderFooter.php index 15309041..0fd56edc 100644 --- a/samples/Sample_12_HeaderFooter.php +++ b/samples/Sample_12_HeaderFooter.php @@ -25,6 +25,7 @@ $table->addCell(4500)->addImage( // Add header for all other pages $subsequent = $section->addHeader(); $subsequent->addText("Subsequent pages in Section 1 will Have this!"); +$subsequent->addImage('resources/_mars.jpg', array('width' => 80, 'height' => 80)); // Add footer $footer = $section->addFooter(); @@ -59,15 +60,8 @@ $sec2Header->addText("All pages in Section 2 will Have this!"); $section2->addTextBreak(); $section2->addText('Some text...'); - // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_13_Images.php b/samples/Sample_13_Images.php index 4ef325b8..29b3e733 100644 --- a/samples/Sample_13_Images.php +++ b/samples/Sample_13_Images.php @@ -10,24 +10,63 @@ $section = $phpWord->addSection(); $section->addText('Local image without any styles:'); $section->addImage('resources/_mars.jpg'); $section->addTextBreak(2); -// + $section->addText('Local image with styles:'); $section->addImage('resources/_earth.jpg', array('width' => 210, 'height' => 210, 'align' => 'center')); $section->addTextBreak(2); +// Remote image $source = 'http://php.net/images/logos/php-med-trans-light.gif'; $section->addText("Remote image from: {$source}"); $section->addImage($source); -// End code -// Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +//Wrapping style +$text = str_repeat('Hello World! ', 15); +$wrappingStyles = array('inline', 'behind', 'infront', 'square', 'tight'); +foreach ($wrappingStyles as $wrappingStyle) { + $section->addTextBreak(5); + $section->addText('Wrapping style ' . $wrappingStyle); + $section->addImage('resources/_earth.jpg', array('positioning' => 'relative', 'marginTop' => -1, 'marginLeft' => 1, + 'width' => 80, 'height' => 80, 'wrappingStyle' => $wrappingStyle)); + $section->addText($text); } -include_once 'Sample_Footer.php'; +//Absolute positioning +$section->addTextBreak(3); +$section->addText('Absolute positioning: see top right corner of page'); +$section->addImage( + 'resources/_mars.jpg', + array( + 'width' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(3), + 'height' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(3), + 'positioning' => \PhpOffice\PhpWord\Style\Image::POSITION_ABSOLUTE, + 'posHorizontal' => \PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_RIGHT, + 'posHorizontalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_PAGE, + 'posVerticalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_PAGE, + 'marginLeft' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(15.5), + 'marginTop' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(1.55) + ) +); + +//Relative positioning +$section->addTextBreak(3); +$section->addText('Relative positioning: Horizontal position center relative to column,'); +$section->addText('Vertical position top relative to line'); +$section->addImage( + 'resources/_mars.jpg', + array( + 'width' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(3), + 'height' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(3), + 'positioning' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE, + 'posHorizontal' => \PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_CENTER, + 'posHorizontalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_COLUMN, + 'posVertical' => \PhpOffice\PhpWord\Style\Image::POSITION_VERTICAL_TOP, + 'posVerticalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_LINE + ) +); + +// Save file +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; +} diff --git a/samples/Sample_14_ListItem.php b/samples/Sample_14_ListItem.php index 45d9c1a7..3a3d34ab 100644 --- a/samples/Sample_14_ListItem.php +++ b/samples/Sample_14_ListItem.php @@ -18,7 +18,7 @@ $phpWord->addNumberingStyle( array('format' => 'decimal', 'text' => '%1.', 'left' => 360, 'hanging' => 360, 'tabPos' => 360), array('format' => 'upperLetter', 'text' => '%2.', 'left' => 720, 'hanging' => 360, 'tabPos' => 720), ) - ) + ) ); $predefinedMultilevel = array('listType' => \PhpOffice\PhpWord\Style\ListItem::TYPE_NUMBER_NESTED); @@ -54,15 +54,39 @@ $section->addListItem('List Item 6', 1, 'myOwnStyle', $predefinedMultilevel, 'P- $section->addListItem('List Item 7', 0, 'myOwnStyle', $predefinedMultilevel, 'P-Style'); $section->addTextBreak(2); +$section->addText('List with inline formatting.'); +$listItemRun = $section->addListItemRun(); +$listItemRun->addText('List item 1'); +$listItemRun->addText(' in bold', array('bold'=>true)); +$listItemRun = $section->addListItemRun(); +$listItemRun->addText('List item 2'); +$listItemRun->addText(' in italic', array('italic'=>true)); +$listItemRun = $section->addListItemRun(); +$listItemRun->addText('List item 3'); +$listItemRun->addText(' underlined', array('underline'=>'dash')); +$section->addTextBreak(2); + +// Numbered heading + +$phpWord->addNumberingStyle( + 'headingNumbering', + array('type' => 'multilevel', 'levels' => array( + array('pStyle' => 'Heading1', 'format' => 'decimal', 'text' => '%1'), + array('pStyle' => 'Heading2', 'format' => 'decimal', 'text' => '%1.%2'), + array('pStyle' => 'Heading3', 'format' => 'decimal', 'text' => '%1.%2.%3'), + ) + ) +); +$phpWord->addTitleStyle(1, array('size' => 16), array('numStyle' => 'headingNumbering', 'numLevel' => 0)); +$phpWord->addTitleStyle(2, array('size' => 14), array('numStyle' => 'headingNumbering', 'numLevel' => 1)); +$phpWord->addTitleStyle(3, array('size' => 12), array('numStyle' => 'headingNumbering', 'numLevel' => 2)); + +$section->addTitle('Heading 1', 1); +$section->addTitle('Heading 2', 2); +$section->addTitle('Heading 3', 3); // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_15_Link.php b/samples/Sample_15_Link.php index c4435ac0..1bd61e79 100644 --- a/samples/Sample_15_Link.php +++ b/samples/Sample_15_Link.php @@ -16,16 +16,8 @@ $phpWord->addLinkStyle('myOwnLinkStyle', array('bold'=>true, 'color'=>'808000')) $section->addLink('http://www.bing.com', null, 'myOwnLinkStyle'); $section->addLink('http://www.yahoo.com', null, 'myOwnLinkStyle'); -// End code - // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_16_Object.php b/samples/Sample_16_Object.php index cb8de6db..af23a00f 100644 --- a/samples/Sample_16_Object.php +++ b/samples/Sample_16_Object.php @@ -11,16 +11,8 @@ $section->addText('You can open this OLE object by double clicking on the icon:' $section->addTextBreak(2); $section->addObject('resources/_sheet.xls'); -// End code - // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_17_TitleTOC.php b/samples/Sample_17_TitleTOC.php index 15de531b..b18b1bc9 100644 --- a/samples/Sample_17_TitleTOC.php +++ b/samples/Sample_17_TitleTOC.php @@ -67,16 +67,9 @@ $section->addTitle('Subtitle 3.1.2', 3); $section->addText('Text'); echo date('H:i:s'), " Note: Please refresh TOC manually.", EOL; -// End code // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_18_Watermark.php b/samples/Sample_18_Watermark.php index d0ea786a..313cfbed 100644 --- a/samples/Sample_18_Watermark.php +++ b/samples/Sample_18_Watermark.php @@ -12,16 +12,8 @@ $header = $section->addHeader(); $header->addWatermark('resources/_earth.jpg', array('marginTop' => 200, 'marginLeft' => 55)); $section->addText('The header reference to the current section includes a watermark image.'); -// End code - // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_19_TextBreak.php b/samples/Sample_19_TextBreak.php index d7e11ea4..a209ce39 100644 --- a/samples/Sample_19_TextBreak.php +++ b/samples/Sample_19_TextBreak.php @@ -25,16 +25,8 @@ $section->addText('Text break with inline paragraph style:'); $section->addTextBreak(1, null, $paragraphStyle); $section->addText('Done.'); -// End code - // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_20_BGColor.php b/samples/Sample_20_BGColor.php index fec40859..892cd8b2 100644 --- a/samples/Sample_20_BGColor.php +++ b/samples/Sample_20_BGColor.php @@ -11,13 +11,7 @@ $section->addText("This one uses bgColor and is using hex value (0xfbbb10)", arr $section->addText("Compatible with font colors", array("color"=>"0000ff", "bgColor" => "fbbb10")); // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_21_TableRowRules.php b/samples/Sample_21_TableRowRules.php index 10ad156d..b600ec00 100644 --- a/samples/Sample_21_TableRowRules.php +++ b/samples/Sample_21_TableRowRules.php @@ -28,13 +28,7 @@ $section->addText("In this example, image is 250px height. Rows are calculated i $section->addText("So: $"."table2->addRow(3750, array('exactHeight'=>true));"); // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_22_CheckBox.php b/samples/Sample_22_CheckBox.php index 89827388..e7aae5ba 100644 --- a/samples/Sample_22_CheckBox.php +++ b/samples/Sample_22_CheckBox.php @@ -15,13 +15,7 @@ $cell = $table->addCell(); $cell->addCheckBox('chkBox2', 'Checkbox 2'); // Save file -$name = basename(__FILE__, '.php'); -$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf'); -foreach ($writers as $writer => $extension) { - echo date('H:i:s'), " Write to {$writer} format", EOL; - $xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, $writer); - $xmlWriter->save("{$name}.{$extension}"); - rename("{$name}.{$extension}", "results/{$name}.{$extension}"); +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; } - -include_once 'Sample_Footer.php'; diff --git a/samples/Sample_23_TemplateBlock.php b/samples/Sample_23_TemplateBlock.php index bbde5a72..8ee8fc6d 100644 --- a/samples/Sample_23_TemplateBlock.php +++ b/samples/Sample_23_TemplateBlock.php @@ -18,4 +18,7 @@ echo date('H:i:s'), " Write to Word2007 format", EOL; $document->saveAs($name); rename($name, "results/{$name}"); -include_once 'Sample_Footer.php'; +echo getEndingNotes(array('Word2007' => 'docx')); +if (!CLI) { + include_once 'Sample_Footer.php'; +} diff --git a/samples/Sample_24_ReadODText.php b/samples/Sample_24_ReadODText.php new file mode 100644 index 00000000..42df23ae --- /dev/null +++ b/samples/Sample_24_ReadODText.php @@ -0,0 +1,15 @@ +addSection(); + +// In section +$textbox = $section->addTextBox(array('align' => 'center', 'width' => 400, 'height' => 150, 'borderSize' => 1, 'borderColor' => '#FF0000')); +$textbox->addText('Text box content in section.'); +$textbox->addText('Another line.'); +$cell = $textbox->addTable()->addRow()->addCell(); +$cell->addText('Table inside textbox'); + +// Inside table +$section->addTextBreak(2); +$cell = $section->addTable()->addRow()->addCell(300); +$textbox = $cell->addTextBox(array('borderSize' => 1, 'borderColor' => '#0000FF', 'innerMargin' => 100)); +$textbox->addText('Textbox inside table'); + +// Inside header with textrun +$header = $section->addHeader(); +$textbox = $header->addTextBox(array('width' => 600, 'borderSize' => 1, 'borderColor' => '#00FF00')); +$textrun = $textbox->addTextRun(); +$textrun->addText('TextBox in header. TextBox can contain a TextRun '); +$textrun->addText('with bold text', array('bold' => true)); +$textrun->addText(', '); +$textrun->addLink('http://www.google.com', 'link'); +$textrun->addText(', and image '); +$textrun->addImage('resources/_earth.jpg', array('width' => 18, 'height' => 18)); +$textrun->addText('.'); + +// Save file +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; +} diff --git a/samples/Sample_26_Html.php b/samples/Sample_26_Html.php new file mode 100644 index 00000000..92b3aa49 --- /dev/null +++ b/samples/Sample_26_Html.php @@ -0,0 +1,23 @@ +addSection(); +$html = '

Adding element via HTML

'; +$html .= '

Some well formed HTML snippet needs to be used

'; +$html .= '

With for example some1 inline formatting1

'; +$html .= '

Unordered (bulleted) list:

'; +$html .= ''; +$html .= '

Ordered (numbered) list:

'; +$html .= '
  1. Item 1
  2. Item 2
'; + +\PhpOffice\PhpWord\Shared\Html::addHtml($section, $html); + +// Save file +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; +} \ No newline at end of file diff --git a/samples/Sample_27_Field.php b/samples/Sample_27_Field.php new file mode 100644 index 00000000..fd750372 --- /dev/null +++ b/samples/Sample_27_Field.php @@ -0,0 +1,31 @@ +addSection(); + +// Add Field elements +// See Element/Field.php for all options +$section->addText('Date field:'); +$section->addField('DATE', array('dateformat'=>'dddd d MMMM yyyy H:mm:ss'), array('PreserveFormat')); + +$section->addText('Page field:'); +$section->addField('PAGE', array('format'=>'ArabicDash')); + +$section->addText('Number of pages field:'); +$section->addField('NUMPAGES', array('format'=>'Arabic', 'numformat'=>'0,00'), array('PreserveFormat')); + +$textrun = $section->addTextRun(array('align' => 'center')); +$textrun->addText('This is the date of lunar calendar '); +$textrun->addField('DATE', array('dateformat'=>'d-M-yyyy H:mm:ss'), array('PreserveFormat', 'LunarCalendar')); +$textrun->addText(' written in a textrun.'); + +// Save file +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; +} diff --git a/samples/Sample_28_ReadRTF.php b/samples/Sample_28_ReadRTF.php new file mode 100644 index 00000000..76ac3d48 --- /dev/null +++ b/samples/Sample_28_ReadRTF.php @@ -0,0 +1,15 @@ +addSection(); + +// Add Line elements +// See Element/Line.php for all options +$section->addText('Horizontal Line (Inline style):'); +$section->addLine( + array( + 'width' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(4), + 'height' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(0), + 'positioning' => 'absolute' + ) +); +$section->addText('Vertical Line (Inline style):'); +$section->addLine( + array( + 'width' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(0), + 'height' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(1), + 'positioning' => 'absolute' + ) +); +// Two text break +$section->addTextBreak(1); + +$section->addText('Positioned Line (red):'); +$section->addLine( + array( + 'width' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(4), + 'height' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(1), + 'positioning' => 'absolute', + 'posHorizontalRel' => 'page', + 'posVerticalRel' => 'page', + 'marginLeft' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(10), + 'marginTop' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(8), + 'wrappingStyle' => \PhpOffice\PhpWord\Style\Image::WRAPPING_STYLE_SQUARE, + 'color' => 'red' + ) +); + +$section->addText('Horizontal Formatted Line'); +$section->addLine( + array( + 'width' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(15), + 'height' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(0), + 'positioning' => 'absolute', + 'beginArrow' => \PhpOffice\PhpWord\Style\Line::ARROW_STYLE_BLOCK, + 'endArrow' => \PhpOffice\PhpWord\Style\Line::ARROW_STYLE_OVAL, + 'dash' => \PhpOffice\PhpWord\Style\Line::DASH_STYLE_LONG_DASH_DOT_DOT, + 'weight' => 10 + ) +); + +// Save file +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; +} diff --git a/samples/Sample_30_ReadHTML.php b/samples/Sample_30_ReadHTML.php new file mode 100644 index 00000000..029f8c8c --- /dev/null +++ b/samples/Sample_30_ReadHTML.php @@ -0,0 +1,15 @@ +addTitleStyle(1, array('size' => 14, 'bold' => true)); + +$section = $phpWord->addSection(); + +// Arc +$section->addTitle('Arc', 1); +$section->addShape( + 'arc', + array( + 'points' => '-90 20', + 'frame' => array('width' => 120, 'height' => 120), + 'outline' => array('color' => '#333333', 'weight' => 2, 'startArrow' => 'oval', 'endArrow' => 'open'), + ) +); + +// Curve +$section->addTitle('Curve', 1); +$section->addShape( + 'curve', + array( + 'points' => '1,100 200,1 1,50 200,50', 'connector' => 'elbow', + 'outline' => array('color' => '#66cc00', 'weight' => 2, 'dash' => 'dash', 'startArrow' => 'diamond', 'endArrow' => 'block'), + ) +); + +// Line +$section->addTitle('Line', 1); +$section->addShape( + 'line', + array( + 'points' => '1,1 150,30', + 'outline' => array('color' => '#cc00ff', 'line' => 'thickThin', 'weight' => 3, 'startArrow' => 'oval', 'endArrow' => 'classic'), + ) +); + +// Polyline +$section->addTitle('Polyline', 1); +$section->addShape( + 'polyline', + array( + 'points' => '1,30 20,10 55,20 75,10 100,40 115,50, 120,15 200,50', + 'outline' => array('color' => '#cc6666', 'weight' => 2, 'startArrow' => 'none', 'endArrow' => 'classic'), + ) +); + +// Rectangle +$section->addTitle('Rectangle', 1); +$section->addShape( + 'rect', + array( + 'roundness' => 0.2, + 'frame' => array('width' => 100, 'height' => 100, 'left' => 1, 'top' => 1), + 'fill' => array('color' => '#FFCC33'), + 'outline' => array('color' => '#990000', 'weight' => 1), + 'shadow' => array(), + ) +); + +// Oval +$section->addTitle('Oval', 1); +$section->addShape( + 'oval', + array( + 'frame' => array('width' => 100, 'height' => 70, 'left' => 1, 'top' => 1), + 'fill' => array('color' => '#33CC99'), + 'outline' => array('color' => '#333333', 'weight' => 2), + 'extrusion' => array(), + ) +); + +// Save file +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; +} diff --git a/samples/Sample_32_Chart.php b/samples/Sample_32_Chart.php new file mode 100644 index 00000000..5f2188ed --- /dev/null +++ b/samples/Sample_32_Chart.php @@ -0,0 +1,63 @@ +addTitleStyle(1, array('size' => 14, 'bold' => true), array('keepNext' => true, 'spaceBefore' => 240)); +$phpWord->addTitleStyle(2, array('size' => 14, 'bold' => true), array('keepNext' => true, 'spaceBefore' => 240)); + +// 2D charts +$section = $phpWord->addSection(); +$section->addTitle('2D charts', 1); +$section = $phpWord->addSection(array('colsNum' => 2, 'breakType' => 'continuous')); + +$chartTypes = array('pie', 'doughnut', 'bar', 'column', 'line', 'area', 'scatter', 'radar'); +$twoSeries = array('bar', 'column', 'line', 'area', 'scatter', 'radar'); +$threeSeries = array('bar', 'line'); +$categories = array('A', 'B', 'C', 'D', 'E'); +$series1 = array(1, 3, 2, 5, 4); +$series2 = array(3, 1, 7, 2, 6); +$series3 = array(8, 3, 2, 5, 4); + +foreach ($chartTypes as $chartType) { + $section->addTitle(ucfirst($chartType), 2); + $chart = $section->addChart($chartType, $categories, $series1); + $chart->getStyle() + ->setWidth(Converter::inchToEmu(2.5)) + ->setHeight(Converter::inchToEmu(2)); + if (in_array($chartType, $twoSeries)) { + $chart->addSeries($categories, $series2); + } + if (in_array($chartType, $threeSeries)) { + $chart->addSeries($categories, $series3); + } + $section->addTextBreak(); +} + +// 3D charts +$section = $phpWord->addSection(array('breakType' => 'continuous')); +$section->addTitle('3D charts', 1); +$section = $phpWord->addSection(array('colsNum' => 2, 'breakType' => 'continuous')); + +$chartTypes = array('pie', 'bar', 'column', 'line', 'area'); +$multiSeries = array('bar', 'column', 'line', 'area'); +$style = array('width' => Converter::cmToEmu(5), 'height' => Converter::cmToEmu(4), '3d' => true); +foreach ($chartTypes as $chartType) { + $section->addTitle(ucfirst($chartType), 2); + $chart = $section->addChart($chartType, $categories, $series1, $style); + if (in_array($chartType, $multiSeries)) { + $chart->addSeries($categories, $series2); + $chart->addSeries($categories, $series3); + } + $section->addTextBreak(); +} + +// Save file +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; +} diff --git a/samples/Sample_33_FormField.php b/samples/Sample_33_FormField.php new file mode 100644 index 00000000..d3811fc4 --- /dev/null +++ b/samples/Sample_33_FormField.php @@ -0,0 +1,27 @@ +getProtection()->setEditing('forms'); + +$section = $phpWord->addSection(); + +$textrun = $section->addTextRun(); +$textrun->addText('Form fields can be added in a text run and can be in form of textinput '); +$textrun->addFormField('textinput')->setName('MyTextBox'); +$textrun->addText(', checkbox '); +$textrun->addFormField('checkbox')->setDefault(true); +$textrun->addText(', or dropdown '); +$textrun->addFormField('dropdown')->setEntries(array('Choice 1', 'Choice 2', 'Choice 3')); +$textrun->addText('. You have to set document protection to "forms" to enable dropdown.'); + +$section->addText('They can also be added as a stand alone paragraph.'); +$section->addFormField('textinput')->setValue('Your name'); + +// Save file +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; +} diff --git a/samples/Sample_34_SDT.php b/samples/Sample_34_SDT.php new file mode 100644 index 00000000..241dee2a --- /dev/null +++ b/samples/Sample_34_SDT.php @@ -0,0 +1,26 @@ +addSection(); + +$textrun = $section->addTextRun(); +$textrun->addText('Combobox: '); +$textrun->addSDT('comboBox')->setListItems(array('1' => 'Choice 1', '2' => 'Choice 2')); + +$textrun = $section->addTextRun(); +$textrun->addText('Date: '); +$textrun->addSDT('date'); + +$textrun = $section->addTextRun(); +$textrun->addText('Drop down list: '); +$textrun->addSDT('dropDownList')->setListItems(array('1' => 'Choice 1', '2' => 'Choice 2')); + +// Save file +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; +} diff --git a/samples/Sample_35_InternalLink.php b/samples/Sample_35_InternalLink.php new file mode 100644 index 00000000..3b6aae51 --- /dev/null +++ b/samples/Sample_35_InternalLink.php @@ -0,0 +1,22 @@ +addSection(); +$section->addTitle( 'This is page 1', 1 ); +$linkIsInternal = true; +$section->addLink('MyBookmark', 'Take me to page 3', null ,null,$linkIsInternal); +$section->addPageBreak(); +$section->addTitle( 'This is page 2', 1 ); +$section->addPageBreak(); +$section->addTitle( 'This is page 3', 1 ); +$section->addBookmark('MyBookmark'); + +// Save file +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; +} diff --git a/samples/Sample_36_RTL.php b/samples/Sample_36_RTL.php new file mode 100644 index 00000000..9b85fb1e --- /dev/null +++ b/samples/Sample_36_RTL.php @@ -0,0 +1,19 @@ +addSection(); +$textrun = $section->addTextRun(); +$textrun->addText('This is a Left to Right paragraph.'); + +$textrun = $section->addTextRun(array('align' => 'right')); +$textrun->addText('سلام این یک پاراگراف راست به چپ است', array('rtl' => true)); + +// Save file +echo write($phpWord, basename(__FILE__, '.php'), $writers); +if (!CLI) { + include_once 'Sample_Footer.php'; +} diff --git a/samples/Sample_Footer.php b/samples/Sample_Footer.php index 4d5777c2..f7e2305f 100644 --- a/samples/Sample_Footer.php +++ b/samples/Sample_Footer.php @@ -2,33 +2,10 @@ /** * Footer file */ -// Do not show execution time for index -if (!IS_INDEX) { - echo date('H:i:s'), " Done writing file(s)", EOL; - echo date('H:i:s'), " Peak memory usage: ", (memory_get_peak_usage(true) / 1024 / 1024), " MB", EOL; -} -// Show message when executed with CLI, show links when using browsers -if (CLI) { - echo 'The results are stored in the "results" subdirectory.', EOL; -} else { - if (!IS_INDEX) { - $types = array('docx', 'odt', 'rtf'); - echo '

 

'; - echo '

Results: '; - foreach ($types as $type) { - $result = 'results/' . SCRIPT_FILENAME . '.' . $type; - if (file_exists($result)) { - echo "{$type} "; - } - } - echo '

'; - } ?> -'); define('SCRIPT_FILENAME', basename($_SERVER['SCRIPT_FILENAME'], '.php')); define('IS_INDEX', SCRIPT_FILENAME == 'index'); -require_once '../src/PhpWord/Autoloader.php'; -\PhpOffice\PhpWord\Autoloader::register(); +require_once __DIR__ . '/../src/PhpWord/Autoloader.php'; +Autoloader::register(); +Settings::loadConfig(); + +// Set writers +$writers = array('Word2007' => 'docx', 'ODText' => 'odt', 'RTF' => 'rtf', 'HTML' => 'html', 'PDF' => 'pdf'); + +// Set PDF renderer +if (Settings::getPdfRendererPath() === null) { + $writers['PDF'] = null; +} // Return to the caller script when runs by CLI if (CLI) { @@ -24,6 +36,7 @@ $pageHeading = str_replace('_', ' ', SCRIPT_FILENAME); $pageTitle = IS_INDEX ? 'Welcome to ' : "{$pageHeading} - "; $pageTitle .= 'PHPWord'; $pageHeading = IS_INDEX ? '' : "

{$pageHeading}

"; + // Populate samples $files = ''; if ($handle = opendir('.')) { @@ -35,12 +48,79 @@ if ($handle = opendir('.')) { } closedir($handle); } + +/** + * Write documents + * + * @param \PhpOffice\PhpWord\PhpWord $phpWord + * @param string $filename + * @param array $writers + */ +function write($phpWord, $filename, $writers) +{ + $result = ''; + + // Write documents + foreach ($writers as $format => $extension) { + $result .= date('H:i:s') . " Write to {$format} format"; + if ($extension !== null) { + $targetFile = __DIR__ . "/results/{$filename}.{$extension}"; + $phpWord->save($targetFile, $format); + } else { + $result .= ' ... NOT DONE!'; + } + $result .= EOL; + } + + $result .= getEndingNotes($writers); + + return $result; +} + +/** + * Get ending notes + * + * @param array $writers + */ +function getEndingNotes($writers) +{ + $result = ''; + + // Do not show execution time for index + if (!IS_INDEX) { + $result .= date('H:i:s') . " Done writing file(s)" . EOL; + $result .= date('H:i:s') . " Peak memory usage: " . (memory_get_peak_usage(true) / 1024 / 1024) . " MB" . EOL; + } + + // Return + if (CLI) { + $result .= 'The results are stored in the "results" subdirectory.' . EOL; + } else { + if (!IS_INDEX) { + $types = array_values($writers); + $result .= '

 

'; + $result .= '

Results: '; + foreach ($types as $type) { + if (!is_null($type)) { + $resultFile = 'results/' . SCRIPT_FILENAME . '.' . $type; + if (file_exists($resultFile)) { + $result .= "{$type} "; + } + } + } + $result .= '

'; + } + } + + return $result; +} ?> <?php echo $pageTitle; ?> + @@ -59,14 +139,14 @@ if ($handle = opendir('.')) { diff --git a/samples/bootstrap/css/font-awesome.min.css b/samples/bootstrap/css/font-awesome.min.css new file mode 100644 index 00000000..449d6ac5 --- /dev/null +++ b/samples/bootstrap/css/font-awesome.min.css @@ -0,0 +1,4 @@ +/*! + * Font Awesome 4.0.3 by @davegandy - http://fontawesome.io - @fontawesome + * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) + */@font-face{font-family:'FontAwesome';src:url('../fonts/fontawesome-webfont.eot?v=4.0.3');src:url('../fonts/fontawesome-webfont.eot?#iefix&v=4.0.3') format('embedded-opentype'),url('../fonts/fontawesome-webfont.woff?v=4.0.3') format('woff'),url('../fonts/fontawesome-webfont.ttf?v=4.0.3') format('truetype'),url('../fonts/fontawesome-webfont.svg?v=4.0.3#fontawesomeregular') format('svg');font-weight:normal;font-style:normal}.fa{display:inline-block;font-family:FontAwesome;font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-lg{font-size:1.3333333333333333em;line-height:.75em;vertical-align:-15%}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-fw{width:1.2857142857142858em;text-align:center}.fa-ul{padding-left:0;margin-left:2.142857142857143em;list-style-type:none}.fa-ul>li{position:relative}.fa-li{position:absolute;left:-2.142857142857143em;width:2.142857142857143em;top:.14285714285714285em;text-align:center}.fa-li.fa-lg{left:-1.8571428571428572em}.fa-border{padding:.2em .25em .15em;border:solid .08em #eee;border-radius:.1em}.pull-right{float:right}.pull-left{float:left}.fa.pull-left{margin-right:.3em}.fa.pull-right{margin-left:.3em}.fa-spin{-webkit-animation:spin 2s infinite linear;-moz-animation:spin 2s infinite linear;-o-animation:spin 2s infinite linear;animation:spin 2s infinite linear}@-moz-keyframes spin{0%{-moz-transform:rotate(0deg)}100%{-moz-transform:rotate(359deg)}}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0deg)}100%{-webkit-transform:rotate(359deg)}}@-o-keyframes spin{0%{-o-transform:rotate(0deg)}100%{-o-transform:rotate(359deg)}}@-ms-keyframes spin{0%{-ms-transform:rotate(0deg)}100%{-ms-transform:rotate(359deg)}}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(359deg)}}.fa-rotate-90{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=1);-webkit-transform:rotate(90deg);-moz-transform:rotate(90deg);-ms-transform:rotate(90deg);-o-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);-webkit-transform:rotate(180deg);-moz-transform:rotate(180deg);-ms-transform:rotate(180deg);-o-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);-webkit-transform:rotate(270deg);-moz-transform:rotate(270deg);-ms-transform:rotate(270deg);-o-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=0,mirror=1);-webkit-transform:scale(-1,1);-moz-transform:scale(-1,1);-ms-transform:scale(-1,1);-o-transform:scale(-1,1);transform:scale(-1,1)}.fa-flip-vertical{filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2,mirror=1);-webkit-transform:scale(1,-1);-moz-transform:scale(1,-1);-ms-transform:scale(1,-1);-o-transform:scale(1,-1);transform:scale(1,-1)}.fa-stack{position:relative;display:inline-block;width:2em;height:2em;line-height:2em;vertical-align:middle}.fa-stack-1x,.fa-stack-2x{position:absolute;left:0;width:100%;text-align:center}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-glass:before{content:"\f000"}.fa-music:before{content:"\f001"}.fa-search:before{content:"\f002"}.fa-envelope-o:before{content:"\f003"}.fa-heart:before{content:"\f004"}.fa-star:before{content:"\f005"}.fa-star-o:before{content:"\f006"}.fa-user:before{content:"\f007"}.fa-film:before{content:"\f008"}.fa-th-large:before{content:"\f009"}.fa-th:before{content:"\f00a"}.fa-th-list:before{content:"\f00b"}.fa-check:before{content:"\f00c"}.fa-times:before{content:"\f00d"}.fa-search-plus:before{content:"\f00e"}.fa-search-minus:before{content:"\f010"}.fa-power-off:before{content:"\f011"}.fa-signal:before{content:"\f012"}.fa-gear:before,.fa-cog:before{content:"\f013"}.fa-trash-o:before{content:"\f014"}.fa-home:before{content:"\f015"}.fa-file-o:before{content:"\f016"}.fa-clock-o:before{content:"\f017"}.fa-road:before{content:"\f018"}.fa-download:before{content:"\f019"}.fa-arrow-circle-o-down:before{content:"\f01a"}.fa-arrow-circle-o-up:before{content:"\f01b"}.fa-inbox:before{content:"\f01c"}.fa-play-circle-o:before{content:"\f01d"}.fa-rotate-right:before,.fa-repeat:before{content:"\f01e"}.fa-refresh:before{content:"\f021"}.fa-list-alt:before{content:"\f022"}.fa-lock:before{content:"\f023"}.fa-flag:before{content:"\f024"}.fa-headphones:before{content:"\f025"}.fa-volume-off:before{content:"\f026"}.fa-volume-down:before{content:"\f027"}.fa-volume-up:before{content:"\f028"}.fa-qrcode:before{content:"\f029"}.fa-barcode:before{content:"\f02a"}.fa-tag:before{content:"\f02b"}.fa-tags:before{content:"\f02c"}.fa-book:before{content:"\f02d"}.fa-bookmark:before{content:"\f02e"}.fa-print:before{content:"\f02f"}.fa-camera:before{content:"\f030"}.fa-font:before{content:"\f031"}.fa-bold:before{content:"\f032"}.fa-italic:before{content:"\f033"}.fa-text-height:before{content:"\f034"}.fa-text-width:before{content:"\f035"}.fa-align-left:before{content:"\f036"}.fa-align-center:before{content:"\f037"}.fa-align-right:before{content:"\f038"}.fa-align-justify:before{content:"\f039"}.fa-list:before{content:"\f03a"}.fa-dedent:before,.fa-outdent:before{content:"\f03b"}.fa-indent:before{content:"\f03c"}.fa-video-camera:before{content:"\f03d"}.fa-picture-o:before{content:"\f03e"}.fa-pencil:before{content:"\f040"}.fa-map-marker:before{content:"\f041"}.fa-adjust:before{content:"\f042"}.fa-tint:before{content:"\f043"}.fa-edit:before,.fa-pencil-square-o:before{content:"\f044"}.fa-share-square-o:before{content:"\f045"}.fa-check-square-o:before{content:"\f046"}.fa-arrows:before{content:"\f047"}.fa-step-backward:before{content:"\f048"}.fa-fast-backward:before{content:"\f049"}.fa-backward:before{content:"\f04a"}.fa-play:before{content:"\f04b"}.fa-pause:before{content:"\f04c"}.fa-stop:before{content:"\f04d"}.fa-forward:before{content:"\f04e"}.fa-fast-forward:before{content:"\f050"}.fa-step-forward:before{content:"\f051"}.fa-eject:before{content:"\f052"}.fa-chevron-left:before{content:"\f053"}.fa-chevron-right:before{content:"\f054"}.fa-plus-circle:before{content:"\f055"}.fa-minus-circle:before{content:"\f056"}.fa-times-circle:before{content:"\f057"}.fa-check-circle:before{content:"\f058"}.fa-question-circle:before{content:"\f059"}.fa-info-circle:before{content:"\f05a"}.fa-crosshairs:before{content:"\f05b"}.fa-times-circle-o:before{content:"\f05c"}.fa-check-circle-o:before{content:"\f05d"}.fa-ban:before{content:"\f05e"}.fa-arrow-left:before{content:"\f060"}.fa-arrow-right:before{content:"\f061"}.fa-arrow-up:before{content:"\f062"}.fa-arrow-down:before{content:"\f063"}.fa-mail-forward:before,.fa-share:before{content:"\f064"}.fa-expand:before{content:"\f065"}.fa-compress:before{content:"\f066"}.fa-plus:before{content:"\f067"}.fa-minus:before{content:"\f068"}.fa-asterisk:before{content:"\f069"}.fa-exclamation-circle:before{content:"\f06a"}.fa-gift:before{content:"\f06b"}.fa-leaf:before{content:"\f06c"}.fa-fire:before{content:"\f06d"}.fa-eye:before{content:"\f06e"}.fa-eye-slash:before{content:"\f070"}.fa-warning:before,.fa-exclamation-triangle:before{content:"\f071"}.fa-plane:before{content:"\f072"}.fa-calendar:before{content:"\f073"}.fa-random:before{content:"\f074"}.fa-comment:before{content:"\f075"}.fa-magnet:before{content:"\f076"}.fa-chevron-up:before{content:"\f077"}.fa-chevron-down:before{content:"\f078"}.fa-retweet:before{content:"\f079"}.fa-shopping-cart:before{content:"\f07a"}.fa-folder:before{content:"\f07b"}.fa-folder-open:before{content:"\f07c"}.fa-arrows-v:before{content:"\f07d"}.fa-arrows-h:before{content:"\f07e"}.fa-bar-chart-o:before{content:"\f080"}.fa-twitter-square:before{content:"\f081"}.fa-facebook-square:before{content:"\f082"}.fa-camera-retro:before{content:"\f083"}.fa-key:before{content:"\f084"}.fa-gears:before,.fa-cogs:before{content:"\f085"}.fa-comments:before{content:"\f086"}.fa-thumbs-o-up:before{content:"\f087"}.fa-thumbs-o-down:before{content:"\f088"}.fa-star-half:before{content:"\f089"}.fa-heart-o:before{content:"\f08a"}.fa-sign-out:before{content:"\f08b"}.fa-linkedin-square:before{content:"\f08c"}.fa-thumb-tack:before{content:"\f08d"}.fa-external-link:before{content:"\f08e"}.fa-sign-in:before{content:"\f090"}.fa-trophy:before{content:"\f091"}.fa-github-square:before{content:"\f092"}.fa-upload:before{content:"\f093"}.fa-lemon-o:before{content:"\f094"}.fa-phone:before{content:"\f095"}.fa-square-o:before{content:"\f096"}.fa-bookmark-o:before{content:"\f097"}.fa-phone-square:before{content:"\f098"}.fa-twitter:before{content:"\f099"}.fa-facebook:before{content:"\f09a"}.fa-github:before{content:"\f09b"}.fa-unlock:before{content:"\f09c"}.fa-credit-card:before{content:"\f09d"}.fa-rss:before{content:"\f09e"}.fa-hdd-o:before{content:"\f0a0"}.fa-bullhorn:before{content:"\f0a1"}.fa-bell:before{content:"\f0f3"}.fa-certificate:before{content:"\f0a3"}.fa-hand-o-right:before{content:"\f0a4"}.fa-hand-o-left:before{content:"\f0a5"}.fa-hand-o-up:before{content:"\f0a6"}.fa-hand-o-down:before{content:"\f0a7"}.fa-arrow-circle-left:before{content:"\f0a8"}.fa-arrow-circle-right:before{content:"\f0a9"}.fa-arrow-circle-up:before{content:"\f0aa"}.fa-arrow-circle-down:before{content:"\f0ab"}.fa-globe:before{content:"\f0ac"}.fa-wrench:before{content:"\f0ad"}.fa-tasks:before{content:"\f0ae"}.fa-filter:before{content:"\f0b0"}.fa-briefcase:before{content:"\f0b1"}.fa-arrows-alt:before{content:"\f0b2"}.fa-group:before,.fa-users:before{content:"\f0c0"}.fa-chain:before,.fa-link:before{content:"\f0c1"}.fa-cloud:before{content:"\f0c2"}.fa-flask:before{content:"\f0c3"}.fa-cut:before,.fa-scissors:before{content:"\f0c4"}.fa-copy:before,.fa-files-o:before{content:"\f0c5"}.fa-paperclip:before{content:"\f0c6"}.fa-save:before,.fa-floppy-o:before{content:"\f0c7"}.fa-square:before{content:"\f0c8"}.fa-bars:before{content:"\f0c9"}.fa-list-ul:before{content:"\f0ca"}.fa-list-ol:before{content:"\f0cb"}.fa-strikethrough:before{content:"\f0cc"}.fa-underline:before{content:"\f0cd"}.fa-table:before{content:"\f0ce"}.fa-magic:before{content:"\f0d0"}.fa-truck:before{content:"\f0d1"}.fa-pinterest:before{content:"\f0d2"}.fa-pinterest-square:before{content:"\f0d3"}.fa-google-plus-square:before{content:"\f0d4"}.fa-google-plus:before{content:"\f0d5"}.fa-money:before{content:"\f0d6"}.fa-caret-down:before{content:"\f0d7"}.fa-caret-up:before{content:"\f0d8"}.fa-caret-left:before{content:"\f0d9"}.fa-caret-right:before{content:"\f0da"}.fa-columns:before{content:"\f0db"}.fa-unsorted:before,.fa-sort:before{content:"\f0dc"}.fa-sort-down:before,.fa-sort-asc:before{content:"\f0dd"}.fa-sort-up:before,.fa-sort-desc:before{content:"\f0de"}.fa-envelope:before{content:"\f0e0"}.fa-linkedin:before{content:"\f0e1"}.fa-rotate-left:before,.fa-undo:before{content:"\f0e2"}.fa-legal:before,.fa-gavel:before{content:"\f0e3"}.fa-dashboard:before,.fa-tachometer:before{content:"\f0e4"}.fa-comment-o:before{content:"\f0e5"}.fa-comments-o:before{content:"\f0e6"}.fa-flash:before,.fa-bolt:before{content:"\f0e7"}.fa-sitemap:before{content:"\f0e8"}.fa-umbrella:before{content:"\f0e9"}.fa-paste:before,.fa-clipboard:before{content:"\f0ea"}.fa-lightbulb-o:before{content:"\f0eb"}.fa-exchange:before{content:"\f0ec"}.fa-cloud-download:before{content:"\f0ed"}.fa-cloud-upload:before{content:"\f0ee"}.fa-user-md:before{content:"\f0f0"}.fa-stethoscope:before{content:"\f0f1"}.fa-suitcase:before{content:"\f0f2"}.fa-bell-o:before{content:"\f0a2"}.fa-coffee:before{content:"\f0f4"}.fa-cutlery:before{content:"\f0f5"}.fa-file-text-o:before{content:"\f0f6"}.fa-building-o:before{content:"\f0f7"}.fa-hospital-o:before{content:"\f0f8"}.fa-ambulance:before{content:"\f0f9"}.fa-medkit:before{content:"\f0fa"}.fa-fighter-jet:before{content:"\f0fb"}.fa-beer:before{content:"\f0fc"}.fa-h-square:before{content:"\f0fd"}.fa-plus-square:before{content:"\f0fe"}.fa-angle-double-left:before{content:"\f100"}.fa-angle-double-right:before{content:"\f101"}.fa-angle-double-up:before{content:"\f102"}.fa-angle-double-down:before{content:"\f103"}.fa-angle-left:before{content:"\f104"}.fa-angle-right:before{content:"\f105"}.fa-angle-up:before{content:"\f106"}.fa-angle-down:before{content:"\f107"}.fa-desktop:before{content:"\f108"}.fa-laptop:before{content:"\f109"}.fa-tablet:before{content:"\f10a"}.fa-mobile-phone:before,.fa-mobile:before{content:"\f10b"}.fa-circle-o:before{content:"\f10c"}.fa-quote-left:before{content:"\f10d"}.fa-quote-right:before{content:"\f10e"}.fa-spinner:before{content:"\f110"}.fa-circle:before{content:"\f111"}.fa-mail-reply:before,.fa-reply:before{content:"\f112"}.fa-github-alt:before{content:"\f113"}.fa-folder-o:before{content:"\f114"}.fa-folder-open-o:before{content:"\f115"}.fa-smile-o:before{content:"\f118"}.fa-frown-o:before{content:"\f119"}.fa-meh-o:before{content:"\f11a"}.fa-gamepad:before{content:"\f11b"}.fa-keyboard-o:before{content:"\f11c"}.fa-flag-o:before{content:"\f11d"}.fa-flag-checkered:before{content:"\f11e"}.fa-terminal:before{content:"\f120"}.fa-code:before{content:"\f121"}.fa-reply-all:before{content:"\f122"}.fa-mail-reply-all:before{content:"\f122"}.fa-star-half-empty:before,.fa-star-half-full:before,.fa-star-half-o:before{content:"\f123"}.fa-location-arrow:before{content:"\f124"}.fa-crop:before{content:"\f125"}.fa-code-fork:before{content:"\f126"}.fa-unlink:before,.fa-chain-broken:before{content:"\f127"}.fa-question:before{content:"\f128"}.fa-info:before{content:"\f129"}.fa-exclamation:before{content:"\f12a"}.fa-superscript:before{content:"\f12b"}.fa-subscript:before{content:"\f12c"}.fa-eraser:before{content:"\f12d"}.fa-puzzle-piece:before{content:"\f12e"}.fa-microphone:before{content:"\f130"}.fa-microphone-slash:before{content:"\f131"}.fa-shield:before{content:"\f132"}.fa-calendar-o:before{content:"\f133"}.fa-fire-extinguisher:before{content:"\f134"}.fa-rocket:before{content:"\f135"}.fa-maxcdn:before{content:"\f136"}.fa-chevron-circle-left:before{content:"\f137"}.fa-chevron-circle-right:before{content:"\f138"}.fa-chevron-circle-up:before{content:"\f139"}.fa-chevron-circle-down:before{content:"\f13a"}.fa-html5:before{content:"\f13b"}.fa-css3:before{content:"\f13c"}.fa-anchor:before{content:"\f13d"}.fa-unlock-alt:before{content:"\f13e"}.fa-bullseye:before{content:"\f140"}.fa-ellipsis-h:before{content:"\f141"}.fa-ellipsis-v:before{content:"\f142"}.fa-rss-square:before{content:"\f143"}.fa-play-circle:before{content:"\f144"}.fa-ticket:before{content:"\f145"}.fa-minus-square:before{content:"\f146"}.fa-minus-square-o:before{content:"\f147"}.fa-level-up:before{content:"\f148"}.fa-level-down:before{content:"\f149"}.fa-check-square:before{content:"\f14a"}.fa-pencil-square:before{content:"\f14b"}.fa-external-link-square:before{content:"\f14c"}.fa-share-square:before{content:"\f14d"}.fa-compass:before{content:"\f14e"}.fa-toggle-down:before,.fa-caret-square-o-down:before{content:"\f150"}.fa-toggle-up:before,.fa-caret-square-o-up:before{content:"\f151"}.fa-toggle-right:before,.fa-caret-square-o-right:before{content:"\f152"}.fa-euro:before,.fa-eur:before{content:"\f153"}.fa-gbp:before{content:"\f154"}.fa-dollar:before,.fa-usd:before{content:"\f155"}.fa-rupee:before,.fa-inr:before{content:"\f156"}.fa-cny:before,.fa-rmb:before,.fa-yen:before,.fa-jpy:before{content:"\f157"}.fa-ruble:before,.fa-rouble:before,.fa-rub:before{content:"\f158"}.fa-won:before,.fa-krw:before{content:"\f159"}.fa-bitcoin:before,.fa-btc:before{content:"\f15a"}.fa-file:before{content:"\f15b"}.fa-file-text:before{content:"\f15c"}.fa-sort-alpha-asc:before{content:"\f15d"}.fa-sort-alpha-desc:before{content:"\f15e"}.fa-sort-amount-asc:before{content:"\f160"}.fa-sort-amount-desc:before{content:"\f161"}.fa-sort-numeric-asc:before{content:"\f162"}.fa-sort-numeric-desc:before{content:"\f163"}.fa-thumbs-up:before{content:"\f164"}.fa-thumbs-down:before{content:"\f165"}.fa-youtube-square:before{content:"\f166"}.fa-youtube:before{content:"\f167"}.fa-xing:before{content:"\f168"}.fa-xing-square:before{content:"\f169"}.fa-youtube-play:before{content:"\f16a"}.fa-dropbox:before{content:"\f16b"}.fa-stack-overflow:before{content:"\f16c"}.fa-instagram:before{content:"\f16d"}.fa-flickr:before{content:"\f16e"}.fa-adn:before{content:"\f170"}.fa-bitbucket:before{content:"\f171"}.fa-bitbucket-square:before{content:"\f172"}.fa-tumblr:before{content:"\f173"}.fa-tumblr-square:before{content:"\f174"}.fa-long-arrow-down:before{content:"\f175"}.fa-long-arrow-up:before{content:"\f176"}.fa-long-arrow-left:before{content:"\f177"}.fa-long-arrow-right:before{content:"\f178"}.fa-apple:before{content:"\f179"}.fa-windows:before{content:"\f17a"}.fa-android:before{content:"\f17b"}.fa-linux:before{content:"\f17c"}.fa-dribbble:before{content:"\f17d"}.fa-skype:before{content:"\f17e"}.fa-foursquare:before{content:"\f180"}.fa-trello:before{content:"\f181"}.fa-female:before{content:"\f182"}.fa-male:before{content:"\f183"}.fa-gittip:before{content:"\f184"}.fa-sun-o:before{content:"\f185"}.fa-moon-o:before{content:"\f186"}.fa-archive:before{content:"\f187"}.fa-bug:before{content:"\f188"}.fa-vk:before{content:"\f189"}.fa-weibo:before{content:"\f18a"}.fa-renren:before{content:"\f18b"}.fa-pagelines:before{content:"\f18c"}.fa-stack-exchange:before{content:"\f18d"}.fa-arrow-circle-o-right:before{content:"\f18e"}.fa-arrow-circle-o-left:before{content:"\f190"}.fa-toggle-left:before,.fa-caret-square-o-left:before{content:"\f191"}.fa-dot-circle-o:before{content:"\f192"}.fa-wheelchair:before{content:"\f193"}.fa-vimeo-square:before{content:"\f194"}.fa-turkish-lira:before,.fa-try:before{content:"\f195"}.fa-plus-square-o:before{content:"\f196"} \ No newline at end of file diff --git a/samples/bootstrap/css/phpword.css b/samples/bootstrap/css/phpword.css index d7470598..fc410ec2 100644 --- a/samples/bootstrap/css/phpword.css +++ b/samples/bootstrap/css/phpword.css @@ -1,6 +1,7 @@ body { padding-top: 20px; padding-bottom: 20px; + min-height: 1000px; } .navbar { margin-bottom: 20px; diff --git a/samples/bootstrap/fonts/FontAwesome.otf b/samples/bootstrap/fonts/FontAwesome.otf new file mode 100644 index 00000000..8b0f54e4 Binary files /dev/null and b/samples/bootstrap/fonts/FontAwesome.otf differ diff --git a/samples/bootstrap/fonts/fontawesome-webfont.eot b/samples/bootstrap/fonts/fontawesome-webfont.eot new file mode 100644 index 00000000..7c79c6a6 Binary files /dev/null and b/samples/bootstrap/fonts/fontawesome-webfont.eot differ diff --git a/samples/bootstrap/fonts/fontawesome-webfont.svg b/samples/bootstrap/fonts/fontawesome-webfont.svg new file mode 100644 index 00000000..45fdf338 --- /dev/null +++ b/samples/bootstrap/fonts/fontawesome-webfont.svg @@ -0,0 +1,414 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/samples/bootstrap/fonts/fontawesome-webfont.ttf b/samples/bootstrap/fonts/fontawesome-webfont.ttf new file mode 100644 index 00000000..e89738de Binary files /dev/null and b/samples/bootstrap/fonts/fontawesome-webfont.ttf differ diff --git a/samples/bootstrap/fonts/fontawesome-webfont.woff b/samples/bootstrap/fonts/fontawesome-webfont.woff new file mode 100644 index 00000000..8c1748aa Binary files /dev/null and b/samples/bootstrap/fonts/fontawesome-webfont.woff differ diff --git a/samples/index.php b/samples/index.php index 451cf381..f25f7f33 100644 --- a/samples/index.php +++ b/samples/index.php @@ -1,28 +1,44 @@ array('PHP 5.3.0', version_compare(phpversion(), '5.3.0', '>=')), + 'xml' => array('PHP extension XML', extension_loaded('xml')), + 'temp' => array('Temp folder "' . Settings::getTempDir() . '" is writable', is_writable(Settings::getTempDir())), + 'zip' => array('PHP extension ZipArchive (optional)', extension_loaded('zip')), + 'gd' => array('PHP extension GD (optional)', extension_loaded('gd')), + 'xmlw' => array('PHP extension XMLWriter (optional)', extension_loaded('xmlwriter')), + 'xsl' => array('PHP extension XSL (optional)', extension_loaded('xsl')), +); if (!CLI) { ?>
-

Welcome to PHPWord, a pure PHP library for reading and writing word processing documents, i.e. Word (.docx), WordPad (.rtf), and Libre/OpenOffice Writer (.odt).

-

Please use the menu above to browse PHPWord samples.

+

Welcome to PHPWord, a library written in pure PHP that provides a set of classes to write to and read from different document file formats, i.e. Office Open XML (.docx), Open Document Format (.odt), and Rich Text Format (.rtf).

+

 

- Fork us on Github! - Read the Docs + Fork us on Github! + Read the Docs

- array('PHP 5.3.0', version_compare(phpversion(), '5.3.0', '>=')), - 'zip' => array('PHP extension ZipArchive', extension_loaded('zip')), - 'xml' => array('PHP extension XML', extension_loaded('xml')), - 'gd' => array('PHP extension GD (optional)', extension_loaded('gd')), -); -echo "

Requirements

"; -echo ""; -} // if (!CLI) -include_once 'Sample_Footer.php'; diff --git a/samples/resources/Sample_07_TemplateCloneRow.docx b/samples/resources/Sample_07_TemplateCloneRow.docx old mode 100755 new mode 100644 diff --git a/samples/resources/Sample_11_ReadWord2007.docx b/samples/resources/Sample_11_ReadWord2007.docx index 2143c628..c9a50f48 100644 Binary files a/samples/resources/Sample_11_ReadWord2007.docx and b/samples/resources/Sample_11_ReadWord2007.docx differ diff --git a/samples/resources/Sample_24_ReadODText.odt b/samples/resources/Sample_24_ReadODText.odt new file mode 100644 index 00000000..d37c4e66 Binary files /dev/null and b/samples/resources/Sample_24_ReadODText.odt differ diff --git a/samples/resources/Sample_28_ReadRTF.rtf b/samples/resources/Sample_28_ReadRTF.rtf new file mode 100644 index 00000000..6f9ac0f8 --- /dev/null +++ b/samples/resources/Sample_28_ReadRTF.rtf @@ -0,0 +1,21 @@ +{\rtf1 +\ansi\ansicpg1252 +\deff0 +{\fonttbl{\f0\fnil\fcharset0 Arial;}{\f1\fnil\fcharset0 Times New Roman;}} +{\colortbl;\red255\green0\blue0;\red14\green0\blue0} +{\*\generator PhpWord;} + +{\info{\title }{\subject }{\category }{\keywords }{\comment }{\author }{\operator }{\creatim \yr2014\mo05\dy27\hr23\min36\sec45}{\revtim \yr2014\mo05\dy27\hr23\min36\sec45}{\company }{\manager }} +\deftab720\viewkind1\uc1\pard\nowidctlpar\lang1036\kerning1\fs20 +{Welcome to PhpWord}\par +\pard\nowidctlpar{\cf0\f0 Hello World!}\par +\par +\par +\pard\nowidctlpar{\cf0\f0\fs32\b\i I am styled by a font style definition.}\par +\pard\nowidctlpar{\cf0\f0 I am styled by a paragraph style definition.}\par +\pard\nowidctlpar\qc\sa100{\cf0\f0\fs32\b\i I am styled by both font and paragraph style.}\par +\pard\nowidctlpar{\cf1\f1\fs40\b\i\ul\strike\super I am inline styled.}\par +\par +{\field {\*\fldinst {HYPERLINK "http://www.google.com"}}{\fldrslt {Google}}}\par +\par +} \ No newline at end of file diff --git a/samples/resources/Sample_30_ReadHTML.html b/samples/resources/Sample_30_ReadHTML.html new file mode 100644 index 00000000..5593298b --- /dev/null +++ b/samples/resources/Sample_30_ReadHTML.html @@ -0,0 +1,15 @@ + + + +PHPWord + + +

Adding element via HTML

+

Some well formed HTML snippet needs to be used

+

With for example some1 inline formatting1

+

Unordered (bulleted) list:

+ +

Ordered (numbered) list:

+
  1. Item 1
  2. Item 2
+ + diff --git a/samples/results/.gitignore b/samples/results/.gitignore new file mode 100644 index 00000000..c96a04f0 --- /dev/null +++ b/samples/results/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore \ No newline at end of file diff --git a/samples/results/.gitkeep b/samples/results/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/PhpWord/Autoloader.php b/src/PhpWord/Autoloader.php index 5bb331ab..68da845d 100644 --- a/src/PhpWord/Autoloader.php +++ b/src/PhpWord/Autoloader.php @@ -1,10 +1,18 @@ items; + } + + /** + * Get item by index + * + * @param int $index + * @return mixed + */ + public function getItem($index) + { + if (array_key_exists($index, $this->items)) { + return $this->items[$index]; + } else { + return null; + } + } + + /** + * Set item. + * + * @param int $index + * @param mixed $item + * @return void + */ + public function setItem($index, $item) + { + if (array_key_exists($index, $this->items)) { + $this->items[$index] = $item; + } + } + + /** + * Add new item + * + * @param mixed $item + * @return int + */ + public function addItem($item) + { + $index = $this->countItems() + 1; + $this->items[$index] = $item; + + return $index; + } + + /** + * Get item count + * + * @return int + */ + public function countItems() + { + return count($this->items); + } +} diff --git a/src/PhpWord/Collection/Bookmarks.php b/src/PhpWord/Collection/Bookmarks.php new file mode 100644 index 00000000..cb9d74d5 --- /dev/null +++ b/src/PhpWord/Collection/Bookmarks.php @@ -0,0 +1,27 @@ +addElement($element, $fontStyle, $paragraphStyle); + } + + // All other elements + } else { + array_unshift($args, $element); // Prepend element name to the beginning of args array + return call_user_func_array(array($this, 'addElement'), $args); + } + } + + return null; + } + + /** + * Add element + * + * Each element has different number of parameters passed + * + * @param string $elementName + * @return \PhpOffice\PhpWord\Element\AbstractElement + */ + protected function addElement($elementName) + { + $elementClass = __NAMESPACE__ . '\\' . $elementName; + $this->checkValidity($elementName); + + // Get arguments + $args = func_get_args(); + $withoutP = in_array($this->container, array('TextRun', 'Footnote', 'Endnote', 'ListItemRun', 'Field')); + if ($withoutP && ($elementName == 'Text' || $elementName == 'PreserveText')) { + $args[3] = null; // Remove paragraph style for texts in textrun + } + + // Create element using reflection + $reflection = new \ReflectionClass($elementClass); + $elementArgs = $args; + array_shift($elementArgs); // Shift the $elementName off the beginning of array + + /** @var \PhpOffice\PhpWord\Element\AbstractElement $element Type hint */ + $element = $reflection->newInstanceArgs($elementArgs); + + // Set parent container + $element->setParentContainer($this); + $element->setElementIndex($this->countElements() + 1); + $element->setElementId(); + + $this->elements[] = $element; + + return $element; + } + + /** + * Get all elements + * + * @return array + */ + public function getElements() + { + return $this->elements; + } + + /** + * Count elements + * + * @return int + */ + public function countElements() + { + return count($this->elements); + } + + /** + * Check if a method is allowed for the current container + * + * @param string $method + * @return bool + * @throws \BadMethodCallException + */ + private function checkValidity($method) + { + // Valid containers for each element + $allContainers = array( + 'Section', 'Header', 'Footer', 'Footnote', 'Endnote', + 'Cell', 'TextRun', 'TextBox', 'ListItemRun', + ); + $validContainers = array( + 'Text' => $allContainers, + 'Bookmark' => $allContainers, + 'Link' => $allContainers, + 'TextBreak' => $allContainers, + 'Image' => $allContainers, + 'Object' => $allContainers, + 'Field' => $allContainers, + 'Line' => $allContainers, + 'Shape' => $allContainers, + 'FormField' => $allContainers, + 'SDT' => $allContainers, + 'TextRun' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'), + 'ListItem' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'), + 'ListItemRun' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'), + 'Table' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'), + 'CheckBox' => array('Section', 'Header', 'Footer', 'Cell'), + 'TextBox' => array('Section', 'Header', 'Footer', 'Cell'), + 'Footnote' => array('Section', 'TextRun', 'Cell'), + 'Endnote' => array('Section', 'TextRun', 'Cell'), + 'PreserveText' => array('Header', 'Footer', 'Cell'), + 'Title' => array('Section'), + 'TOC' => array('Section'), + 'PageBreak' => array('Section'), + 'Chart' => array('Section'), + ); + // Special condition, e.g. preservetext can only exists in cell when + // the cell is located in header or footer + $validSubcontainers = array( + 'PreserveText' => array(array('Cell'), array('Header', 'Footer')), + 'Footnote' => array(array('Cell', 'TextRun'), array('Section')), + 'Endnote' => array(array('Cell', 'TextRun'), array('Section')), + ); + + // Check if a method is valid for current container + if (array_key_exists($method, $validContainers)) { + if (!in_array($this->container, $validContainers[$method])) { + throw new \BadMethodCallException("Cannot add $method in $this->container."); + } + } + // Check if a method is valid for current container, located in other container + if (array_key_exists($method, $validSubcontainers)) { + $rules = $validSubcontainers[$method]; + $containers = $rules[0]; + $allowedDocParts = $rules[1]; + foreach ($containers as $container) { + if ($this->container == $container && !in_array($this->getDocPart(), $allowedDocParts)) { + throw new \BadMethodCallException("Cannot add $method in $this->container."); + } + } + } + + return true; + } + + /** + * Add memory image element + * + * @param string $src + * @param mixed $style + * @return \PhpOffice\PhpWord\Element\Image + * @deprecated 0.9.0 + * @codeCoverageIgnore + */ + public function addMemoryImage($src, $style = null) + { + return $this->addImage($src, $style); + } + + /** + * Create textrun element + * + * @param mixed $paragraphStyle + * @return \PhpOffice\PhpWord\Element\TextRun + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function createTextRun($paragraphStyle = null) + { + return $this->addTextRun($paragraphStyle); + } + + /** + * Create footnote element + * + * @param mixed $paragraphStyle + * @return \PhpOffice\PhpWord\Element\Footnote + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function createFootnote($paragraphStyle = null) + { + return $this->addFootnote($paragraphStyle); + } +} diff --git a/src/PhpWord/Element/AbstractElement.php b/src/PhpWord/Element/AbstractElement.php index 890227dc..99a7a1be 100644 --- a/src/PhpWord/Element/AbstractElement.php +++ b/src/PhpWord/Element/AbstractElement.php @@ -1,49 +1,39 @@ checkValidity('text'); - - // Reset paragraph style for footnote and textrun. They have their own - if (in_array($this->container, array('textrun', 'footnote', 'endnote'))) { - $paragraphStyle = null; - } - - $text = String::toUTF8($text); - $textObject = new Text($text, $fontStyle, $paragraphStyle); - $textObject->setDocPart($this->getDocPart(), $this->getDocPartId()); - $this->addElement($textObject); - - return $textObject; + return $this->phpWord; } /** - * Add textrun element + * Set PhpWord as reference. * - * @param mixed $paragraphStyle - * @return TextRun + * @param \PhpOffice\PhpWord\PhpWord $phpWord + * @return void */ - public function addTextRun($paragraphStyle = null) + public function setPhpWord(PhpWord $phpWord = null) { - $this->checkValidity('textrun'); - - $textRun = new TextRun($paragraphStyle); - $textRun->setDocPart($this->getDocPart(), $this->getDocPartId()); - $this->addElement($textRun); - - return $textRun; - } - - /** - * Add link element - * - * @param string $linkSrc - * @param string $linkName - * @param mixed $fontStyle - * @param mixed $paragraphStyle - * @return Link - */ - public function addLink($linkSrc, $linkName = null, $fontStyle = null, $paragraphStyle = null) - { - $this->checkValidity('link'); - $elementDocPart = $this->checkElementDocPart(); - - $link = new Link(String::toUTF8($linkSrc), String::toUTF8($linkName), $fontStyle, $paragraphStyle); - $link->setDocPart($this->getDocPart(), $this->getDocPartId()); - $rId = Media::addElement($elementDocPart, 'link', $linkSrc); - $link->setRelationId($rId); - $this->addElement($link); - - return $link; - } - - /** - * Add a Title Element - * - * @param string $text - * @param int $depth - * @return Title - * @todo Enable title element in other containers - */ - public function addTitle($text, $depth = 1) - { - $this->checkValidity('title'); - - $styles = Style::getStyles(); - if (array_key_exists('Heading_' . $depth, $styles)) { - $style = 'Heading' . $depth; - } else { - $style = null; - } - $text = String::toUTF8($text); - $title = new Title($text, $depth, $style); - $title->setDocPart($this->getDocPart(), $this->getDocPartId()); - $data = TOC::addTitle($text, $depth); - $anchor = $data[0]; - $bookmarkId = $data[1]; - $title->setAnchor($anchor); - $title->setBookmarkId($bookmarkId); - $this->addElement($title); - - return $title; - } - - /** - * Add preserve text element - * - * @param string $text - * @param mixed $fontStyle - * @param mixed $paragraphStyle - * @return PreserveText - */ - public function addPreserveText($text, $fontStyle = null, $paragraphStyle = null) - { - $this->checkValidity('preservetext'); - - $preserveText = new PreserveText(String::toUTF8($text), $fontStyle, $paragraphStyle); - $preserveText->setDocPart($this->getDocPart(), $this->getDocPartId()); - $this->addElement($preserveText); - - return $preserveText; - } - - /** - * Add text break element - * - * @param int $count - * @param mixed $fontStyle - * @param mixed $paragraphStyle - */ - public function addTextBreak($count = 1, $fontStyle = null, $paragraphStyle = null) - { - $this->checkValidity('textbreak'); - - for ($i = 1; $i <= $count; $i++) { - $textBreak = new TextBreak($fontStyle, $paragraphStyle); - $textBreak->setDocPart($this->getDocPart(), $this->getDocPartId()); - $this->addElement($textBreak); - } - } - - /** - * Add listitem element - * - * @param string $text - * @param int $depth - * @param mixed $fontStyle - * @param mixed $styleList - * @param mixed $paragraphStyle - * @return ListItem - */ - public function addListItem($text, $depth = 0, $fontStyle = null, $styleList = null, $paragraphStyle = null) - { - $this->checkValidity('listitem'); - - $listItem = new ListItem(String::toUTF8($text), $depth, $fontStyle, $styleList, $paragraphStyle); - $listItem->setDocPart($this->getDocPart(), $this->getDocPartId()); - $this->addElement($listItem); - - return $listItem; - } - - /** - * Add table element - * - * @param mixed $style - * @return Table - */ - public function addTable($style = null) - { - $this->checkValidity('table'); - - $table = new Table($this->getDocPart(), $this->getDocPartId(), $style); - $this->addElement($table); - - return $table; - } - - /** - * Add image element - * - * @param string $src - * @param mixed $style Image style - * @param boolean $isWatermark - * @return Image - */ - public function addImage($src, $style = null, $isWatermark = false) - { - $this->checkValidity('image'); - $elementDocPart = $this->checkElementDocPart(); - - $image = new Image($src, $style, $isWatermark); - $image->setDocPart($this->getDocPart(), $this->getDocPartId()); - $rId = Media::addElement($elementDocPart, 'image', $src, $image); - $image->setRelationId($rId); - $this->addElement($image); - - return $image; - } - - /** - * Add OLE-object element - * - * All exceptions should be handled by PhpOffice\PhpWord\Element\Object - * - * @param string $src - * @param mixed $style - * @return Object - * @todo Enable OLE object element in header and footer - */ - public function addObject($src, $style = null) - { - $this->checkValidity('object'); - $elementDocPart = $this->checkElementDocPart(); - - $object = new Object($src, $style); - $object->setDocPart($this->getDocPart(), $this->getDocPartId()); - if (!is_null($object->getSource())) { - $inf = pathinfo($src); - $ext = $inf['extension']; - if (strlen($ext) == 4 && strtolower(substr($ext, -1)) == 'x') { - $ext = substr($ext, 0, -1); - } - $icon = realpath(__DIR__ . "/../_staticDocParts/_{$ext}.png"); - $rId = Media::addElement($elementDocPart, 'object', $src); - $object->setRelationId($rId); - $rIdimg = Media::addElement($elementDocPart, 'image', $icon, new Image($icon)); - $object->setImageRelationId($rIdimg); - $this->addElement($object); - - return $object; - } else { - throw new InvalidObjectException(); - } - } - - /** - * Add footnote element - * - * @param mixed $paragraphStyle - * @return FootnoteElement - */ - public function addFootnote($paragraphStyle = null) - { - $this->checkValidity('footnote'); - - $footnote = new FootnoteElement($paragraphStyle); - $rId = Footnotes::addElement($footnote); - - $footnote->setDocPart('footnote', $this->getDocPartId()); - $footnote->setRelationId($rId); - $this->addElement($footnote); - - return $footnote; - } - - /** - * Add endnote element - * - * @param mixed $paragraphStyle - * @return Endnote - */ - public function addEndnote($paragraphStyle = null) - { - $this->checkValidity('endnote'); - - $endnote = new Endnote($paragraphStyle); - $rId = Endnotes::addElement($endnote); - - $endnote->setDocPart('endnote', $this->getDocPartId()); - $endnote->setRelationId($rId); - $this->addElement($endnote); - - return $endnote; - } - - /** - * Add a CheckBox Element - * - * @param string $name - * @param string $text - * @param mixed $fontStyle - * @param mixed $paragraphStyle - * @return CheckBox - */ - public function addCheckBox($name, $text, $fontStyle = null, $paragraphStyle = null) - { - $this->checkValidity('checkbox'); - - $checkBox = new CheckBox(String::toUTF8($name), String::toUTF8($text), $fontStyle, $paragraphStyle); - $checkBox->setDocPart($this->getDocPart(), $this->getDocPartId()); - $this->addElement($checkBox); - - return $checkBox; + $this->phpWord = $phpWord; } /** * Get section number * - * @return integer + * @return int */ public function getSectionId() { @@ -401,10 +147,11 @@ abstract class AbstractElement } /** - * Set doc part + * Set doc part. * * @param string $docPart - * @param integer $docPartId + * @param int $docPartId + * @return void */ public function setDocPart($docPart, $docPartId = 1) { @@ -425,7 +172,7 @@ abstract class AbstractElement /** * Get doc part Id * - * @return integer + * @return int */ public function getDocPartId() { @@ -433,33 +180,18 @@ abstract class AbstractElement } /** - * Set element index and unique id, and add element into elements collection - */ - protected function addElement(AbstractElement $element) - { - $element->setElementIndex($this->countElements() + 1); - $element->setElementId(); - $this->elements[] = $element; - } - - /** - * Get all elements + * Return media element (image, object, link) container name * - * @return array + * @return string section|headerx|footerx|footnote|endnote */ - public function getElements() + private function getMediaPart() { - return $this->elements; - } + $mediaPart = $this->docPart; + if ($mediaPart == 'Header' || $mediaPart == 'Footer') { + $mediaPart .= $this->docPartId; + } - /** - * Count elements - * - * @return integer - */ - public function countElements() - { - return count($this->elements); + return strtolower($mediaPart); } /** @@ -473,9 +205,10 @@ abstract class AbstractElement } /** - * Set element index + * Set element index. * * @param int $value + * @return void */ public function setElementIndex($value) { @@ -493,7 +226,9 @@ abstract class AbstractElement } /** - * Set element unique ID from 6 first digit of md5 + * Set element unique ID from 6 first digit of md5. + * + * @return void */ public function setElementId() { @@ -507,44 +242,128 @@ abstract class AbstractElement */ public function getRelationId() { - $this->checkValidity('relationid'); return $this->relationId; } /** - * Set relation Id + * Set relation Id. * - * @param int $rId + * @param int $value + * @return void */ - public function setRelationId($rId) + public function setRelationId($value) { - $this->checkValidity('relationid'); - $this->relationId = $rId; + $this->relationId = $value; } /** - * Check if element is located in section doc part (as opposed to header/footer) + * Get nested level * - * @return boolean + * @return int + */ + public function getNestedLevel() + { + return $this->nestedLevel; + } + + /** + * Set parent container + * + * Passed parameter should be a container, except for Table (contain Row) and Row (contain Cell) + * + * @param \PhpOffice\PhpWord\Element\AbstractElement $container + * @return void + */ + public function setParentContainer(AbstractElement $container) + { + $this->parentContainer = substr(get_class($container), strrpos(get_class($container), '\\') + 1); + + // Set nested level + $this->nestedLevel = $container->getNestedLevel(); + if ($this->parentContainer == 'Cell') { + $this->nestedLevel++; + } + + // Set phpword + $this->setPhpWord($container->getPhpWord()); + + // Set doc part + if (!$this instanceof Footnote) { + $this->setDocPart($container->getDocPart(), $container->getDocPartId()); + } + + $this->setMediaRelation(); + $this->setCollectionRelation(); + } + + /** + * Set relation Id for media elements (link, image, object; legacy of OOXML) + * + * - Image element needs to be passed to Media object + * - Icon needs to be set for Object element + * + * @return void + */ + private function setMediaRelation() + { + if (!$this instanceof Link && !$this instanceof Image && !$this instanceof Object) { + return; + } + + $elementName = substr(get_class($this), strrpos(get_class($this), '\\') + 1); + $mediaPart = $this->getMediaPart(); + $source = $this->getSource(); + $image = null; + if ($this instanceof Image) { + $image = $this; + } + $rId = Media::addElement($mediaPart, strtolower($elementName), $source, $image); + $this->setRelationId($rId); + + if ($this instanceof Object) { + $icon = $this->getIcon(); + $rId = Media::addElement($mediaPart, 'image', $icon, new Image($icon)); + $this->setImageRelationId($rId); + } + } + + /** + * Set relation Id for elements that will be registered in the Collection subnamespaces. + * + * @return void + */ + private function setCollectionRelation() + { + if ($this->collectionRelation === true && $this->phpWord instanceof PhpWord) { + $elementName = substr(get_class($this), strrpos(get_class($this), '\\') + 1); + $addMethod = "add{$elementName}"; + $rId = $this->phpWord->$addMethod($this); + $this->setRelationId($rId); + } + } + + /** + * Check if element is located in Section doc part (as opposed to Header/Footer) + * + * @return bool */ public function isInSection() { - return ($this->docPart == 'section'); + return ($this->docPart == 'Section'); } /** - * Set style value + * Set new style value * * @param mixed $styleObject Style object * @param mixed $styleValue Style value - * @param boolean $returnObject Always return object + * @param bool $returnObject Always return object + * @return mixed */ - protected function setStyle($styleObject, $styleValue = null, $returnObject = false) + protected function setNewStyle($styleObject, $styleValue = null, $returnObject = false) { if (!is_null($styleValue) && is_array($styleValue)) { - foreach ($styleValue as $key => $value) { - $styleObject->setStyleValue($key, $value); - } + $styleObject->setStyleByArray($styleValue); $style = $styleObject; } else { $style = $returnObject ? $styleObject : $styleValue; @@ -554,106 +373,23 @@ abstract class AbstractElement } /** - * Check if a method is allowed for the current container + * Set enum value * - * @param string $method - * @return boolean + * @param mixed $value + * @param array $enum + * @param mixed $default + * @return mixed + * @throws \InvalidArgumentException + * @todo Merge with the same method in AbstractStyle */ - private function checkValidity($method) + protected function setEnumVal($value = null, $enum = array(), $default = null) { - // Valid containers for each element - $allContainers = array('section', 'header', 'footer', 'cell', 'textrun', 'footnote', 'endnote'); - $validContainers = array( - 'text' => $allContainers, - 'link' => $allContainers, - 'textbreak' => $allContainers, - 'image' => $allContainers, - 'object' => $allContainers, - 'textrun' => array('section', 'header', 'footer', 'cell'), - 'listitem' => array('section', 'header', 'footer', 'cell'), - 'checkbox' => array('section', 'header', 'footer', 'cell'), - 'table' => array('section', 'header', 'footer'), - 'footnote' => array('section', 'textrun', 'cell'), - 'endnote' => array('section', 'textrun', 'cell'), - 'preservetext' => array('header', 'footer', 'cell'), - 'title' => array('section'), - ); - // Special condition, e.g. preservetext can only exists in cell when - // the cell is located in header or footer - $validContainerInContainers = array( - 'preservetext' => array(array('cell'), array('header', 'footer')), - 'footnote' => array(array('cell', 'textrun'), array('section')), - 'endnote' => array(array('cell', 'textrun'), array('section')), - ); - - // Check if a method is valid for current container - if (array_key_exists($method, $validContainers)) { - if (!in_array($this->container, $validContainers[$method])) { - throw new \BadMethodCallException(); - } - } - // Check if a method is valid for current container, located in other container - if (array_key_exists($method, $validContainerInContainers)) { - $rules = $validContainerInContainers[$method]; - $containers = $rules[0]; - $allowedDocParts = $rules[1]; - foreach ($containers as $container) { - if ($this->container == $container && !in_array($this->getDocPart(), $allowedDocParts)) { - throw new \BadMethodCallException(); - } - } + if ($value != null && trim($value) != '' && !empty($enum) && !in_array($value, $enum)) { + throw new \InvalidArgumentException("Invalid style value: {$value}"); + } elseif ($value === null || trim($value) == '') { + $value = $default; } - return true; - } - - /** - * Return element location in document: section, headerx, or footerx - */ - private function checkElementDocPart() - { - $isCellTextrun = in_array($this->container, array('cell', 'textrun')); - $docPart = $isCellTextrun ? $this->getDocPart() : $this->container; - $docPartId = $isCellTextrun ? $this->getDocPartId() : $this->sectionId; - $inHeaderFooter = ($docPart == 'header' || $docPart == 'footer'); - - return $inHeaderFooter ? $docPart . $docPartId : $docPart; - } - - /** - * Add memory image element - * - * @param string $src - * @param mixed $style - * @deprecated 0.9.0 - * @codeCoverageIgnore - */ - public function addMemoryImage($src, $style = null) - { - return $this->addImage($src, $style); - } - - /** - * Create textrun element - * - * @param mixed $paragraphStyle - * @deprecated 0.10.0 - * @codeCoverageIgnore - */ - public function createTextRun($paragraphStyle = null) - { - return $this->addTextRun($paragraphStyle); - } - - /** - * Create footnote element - * - * @param mixed $paragraphStyle - * @deprecated 0.10.0 - * @codeCoverageIgnore - */ - public function createFootnote($paragraphStyle = null) - { - return $this->addFootnote($paragraphStyle); + return $value; } } diff --git a/src/PhpWord/Element/Bookmark.php b/src/PhpWord/Element/Bookmark.php new file mode 100644 index 00000000..d5b8ff6f --- /dev/null +++ b/src/PhpWord/Element/Bookmark.php @@ -0,0 +1,63 @@ +name = String::toUTF8($name); + return $this; + } + + /** + * Get Bookmark name + * + * @return string + */ + public function getName() + { + return $this->name; + } +} diff --git a/src/PhpWord/Element/Cell.php b/src/PhpWord/Element/Cell.php old mode 100755 new mode 100644 index 2f92bce1..cac37a78 --- a/src/PhpWord/Element/Cell.php +++ b/src/PhpWord/Element/Cell.php @@ -1,10 +1,18 @@ container = 'cell'; - $this->setDocPart($docPart, $docPartId); $this->width = $width; - $this->cellStyle = $this->setStyle(new CellStyle(), $style, true); + $this->style = $this->setNewStyle(new CellStyle(), $style, true); } /** * Get cell style * - * @return CellStyle + * @return \PhpOffice\PhpWord\Style\Cell */ public function getStyle() { - return $this->cellStyle; + return $this->style; } /** diff --git a/src/PhpWord/Element/Chart.php b/src/PhpWord/Element/Chart.php new file mode 100644 index 00000000..66c59ff5 --- /dev/null +++ b/src/PhpWord/Element/Chart.php @@ -0,0 +1,125 @@ +setType($type); + $this->addSeries($categories, $values); + $this->style = $this->setNewStyle(new ChartStyle(), $style, true); + } + + /** + * Get type + * + * @return string + */ + public function getType() + { + return $this->type; + } + + /** + * Set type. + * + * @param string $value + * @return void + */ + public function setType($value) + { + $enum = array('pie', 'doughnut', 'line', 'bar', 'column', 'area', 'radar', 'scatter'); + $this->type = $this->setEnumVal($value, $enum, 'pie'); + } + + /** + * Add series + * + * @param array $categories + * @param array $values + * @return void + */ + public function addSeries($categories, $values) + { + $this->series[] = array('categories' => $categories, 'values' => $values); + } + + /** + * Get series + * + * @return array + */ + public function getSeries() + { + return $this->series; + } + + /** + * Get chart style + * + * @return \PhpOffice\PhpWord\Style\Chart + */ + public function getStyle() + { + return $this->style; + } +} diff --git a/src/PhpWord/Element/CheckBox.php b/src/PhpWord/Element/CheckBox.php index 31f067d7..d3b2a3c6 100644 --- a/src/PhpWord/Element/CheckBox.php +++ b/src/PhpWord/Element/CheckBox.php @@ -1,21 +1,30 @@ setName($name); - $this->setText($text); - $paragraphStyle = $this->setParagraphStyle($paragraphStyle); - $this->setFontStyle($fontStyle, $paragraphStyle); - - return $this; - } - - /** - * Set Text style - * - * @param mixed $style - * @param mixed $paragraphStyle - * @return string|Font - */ - public function setFontStyle($style = null, $paragraphStyle = null) - { - if ($style instanceof Font) { - $this->fontStyle = $style; - $this->setParagraphStyle($paragraphStyle); - } elseif (is_array($style)) { - $this->fontStyle = new Font('text', $paragraphStyle); - $this->fontStyle->setArrayStyle($style); - } elseif (null === $style) { - $this->fontStyle = new Font('text', $paragraphStyle); - } else { - $this->fontStyle = $style; - $this->setParagraphStyle($paragraphStyle); - } - return $this->fontStyle; - } - - /** - * Get Text style - * - * @return string|Font - */ - public function getFontStyle() - { - return $this->fontStyle; - } - - /** - * Set Paragraph style - * - * @param mixed $style - * @return string|Paragraph - */ - public function setParagraphStyle($style = null) - { - if (is_array($style)) { - $this->paragraphStyle = new Paragraph; - $this->paragraphStyle->setArrayStyle($style); - } elseif ($style instanceof Paragraph) { - $this->paragraphStyle = $style; - } elseif (null === $style) { - $this->paragraphStyle = new Paragraph; - } else { - $this->paragraphStyle = $style; - } - return $this->paragraphStyle; - } - - /** - * Get Paragraph style - * - * @return string|Paragraph - */ - public function getParagraphStyle() - { - return $this->paragraphStyle; + parent::__construct($text, $fontStyle, $paragraphStyle); } /** * Set name content * * @param string $name - * @return $this + * @return self */ public function setName($name) { - $this->name = $name; + $this->name = String::toUTF8($name); + return $this; } @@ -149,26 +70,4 @@ class CheckBox extends AbstractElement { return $this->name; } - - /** - * Set text content - * - * @param string $text - * @return $this - */ - public function setText($text) - { - $this->text = $text; - return $this; - } - - /** - * Get text content - * - * @return string - */ - public function getText() - { - return $this->text; - } } diff --git a/src/PhpWord/Element/Endnote.php b/src/PhpWord/Element/Endnote.php index bdcf8e76..10000555 100644 --- a/src/PhpWord/Element/Endnote.php +++ b/src/PhpWord/Element/Endnote.php @@ -1,10 +1,18 @@ container = 'endnote'; - $this->paragraphStyle = $this->setStyle(new Paragraph(), $paragraphStyle); + $this->paragraphStyle = $this->setNewStyle(new Paragraph(), $paragraphStyle); } } diff --git a/src/PhpWord/Element/Field.php b/src/PhpWord/Element/Field.php new file mode 100644 index 00000000..50f0522f --- /dev/null +++ b/src/PhpWord/Element/Field.php @@ -0,0 +1,181 @@ +array( + 'properties'=>array( + 'format' => array('Arabic', 'ArabicDash', 'alphabetic', 'ALPHABETIC', 'roman', 'ROMAN'), + ), + 'options'=>array('PreserveFormat') + ), + 'NUMPAGES'=>array( + 'properties'=>array( + 'format' => array('Arabic', 'ArabicDash', 'alphabetic', 'ALPHABETIC', 'roman', 'ROMAN'), + 'numformat' => array('0', '0,00', '#.##0', '#.##0,00', '€ #.##0,00(€ #.##0,00)', '0%', '0,00%') + ), + 'options'=>array('PreserveFormat') + ), + 'DATE'=>array( + 'properties'=> array( + 'dateformat' =>array('d-M-yyyy', 'dddd d MMMM yyyy', 'd MMMM yyyy', 'd-M-yy', 'yyyy-MM-dd', + 'd-MMM-yy', 'd/M/yyyy', 'd MMM. yy', 'd/M/yy', 'MMM-yy', 'd-M-yyy H:mm', 'd-M-yyyy H:mm:ss', + 'h:mm am/pm', 'h:mm:ss am/pm', 'HH:mm', 'HH:mm:ss') + ), + 'options'=>array('PreserveFormat', 'LunarCalendar', 'SakaEraCalendar', 'LastUsedFormat') + ) + ); + + /** + * Field type + * + * @var string + */ + protected $type; + + /** + * Field properties + * + * @var array + */ + protected $properties = array(); + + /** + * Field options + * + * @var array + */ + protected $options = array(); + + /** + * Create a new Field Element + * + * @param string $type + * @param array $properties + * @param array $options + */ + public function __construct($type = null, $properties = array(), $options = array()) + { + $this->setType($type); + $this->setProperties($properties); + $this->setOptions($options); + } + + /** + * Set Field type + * + * @param string $type + * @return string + * @throws \InvalidArgumentException + */ + public function setType($type = null) + { + if (isset($type)) { + if (array_key_exists($type, $this->fieldsArray)) { + $this->type = $type; + } else { + throw new \InvalidArgumentException("Invalid type"); + } + } + return $this->type; + } + + /** + * Get Field type + * + * @return string + */ + public function getType() + { + return $this->type; + } + + /** + * Set Field properties + * + * @param array $properties + * @return self + * @throws \InvalidArgumentException + */ + public function setProperties($properties = array()) + { + if (is_array($properties)) { + foreach (array_keys($properties) as $propkey) { + if (!(array_key_exists($propkey, $this->fieldsArray[$this->type]['properties']))) { + throw new \InvalidArgumentException("Invalid property"); + } + } + $this->properties = array_merge($this->properties, $properties); + } + return $this->properties; + } + + /** + * Get Field properties + * + * @return array + */ + public function getProperties() + { + return $this->properties; + } + + /** + * Set Field options + * + * @param array $options + * @return self + * @throws \InvalidArgumentException + */ + public function setOptions($options = array()) + { + if (is_array($options)) { + foreach (array_keys($options) as $optionkey) { + if (!(array_key_exists($optionkey, $this->fieldsArray[$this->type]['options']))) { + throw new \InvalidArgumentException("Invalid option"); + } + } + $this->options = array_merge($this->options, $options); + } + return $this->options; + } + + /** + * Get Field properties + * + * @return array + */ + public function getOptions() + { + return $this->options; + } +} diff --git a/src/PhpWord/Element/Footer.php b/src/PhpWord/Element/Footer.php old mode 100755 new mode 100644 index 8db9c6eb..8e19eaf7 --- a/src/PhpWord/Element/Footer.php +++ b/src/PhpWord/Element/Footer.php @@ -1,10 +1,18 @@ container = 'footer'; $this->sectionId = $sectionId; $this->setType($type); - $this->setDocPart($this->container, ($sectionId - 1) * 3 + $footerId); + $this->setDocPart($this->container, ($sectionId - 1) * 3 + $containerId); } /** - * Set type + * Set type. + * + * @since 0.10.0 * * @param string $value - * @since 0.10.0 + * @return void */ public function setType($value = self::AUTO) { + if (!in_array($value, array(self::AUTO, self::FIRST, self::EVEN))) { + $value = self::AUTO; + } $this->type = $value; } @@ -61,4 +84,34 @@ class Footer extends AbstractElement { return $this->type; } + + /** + * Reset type to default + * + * @return string + */ + public function resetType() + { + return $this->type = self::AUTO; + } + + /** + * First page only header + * + * @return string + */ + public function firstPage() + { + return $this->type = self::FIRST; + } + + /** + * Even numbered pages only + * + * @return string + */ + public function evenPage() + { + return $this->type = self::EVEN; + } } diff --git a/src/PhpWord/Element/Footnote.php b/src/PhpWord/Element/Footnote.php index 8f1cf7bc..162a703e 100644 --- a/src/PhpWord/Element/Footnote.php +++ b/src/PhpWord/Element/Footnote.php @@ -1,10 +1,18 @@ container = 'footnote'; - $this->paragraphStyle = $this->setStyle(new Paragraph(), $paragraphStyle); + $this->paragraphStyle = $this->setNewStyle(new Paragraph(), $paragraphStyle); + $this->setDocPart($this->container); } /** * Get paragraph style * - * @return string|Paragraph + * @return string|\PhpOffice\PhpWord\Style\Paragraph */ public function getParagraphStyle() { diff --git a/src/PhpWord/Element/FormField.php b/src/PhpWord/Element/FormField.php new file mode 100644 index 00000000..7bd61be1 --- /dev/null +++ b/src/PhpWord/Element/FormField.php @@ -0,0 +1,195 @@ +setType($type); + } + + /** + * Get type + * + * @return string + */ + public function getType() + { + return $this->type; + } + + /** + * Set type + * + * @param string $value + * @return self + */ + public function setType($value) + { + $enum = array('textinput', 'checkbox', 'dropdown'); + $this->type = $this->setEnumVal($value, $enum, $this->type); + + return $this; + } + + /** + * Get name + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Set name + * + * @param string|bool|int $value + * @return self + */ + public function setName($value) + { + $this->name = $value; + + return $this; + } + + /** + * Get default + * + * @return string|bool|int + */ + public function getDefault() + { + return $this->default; + } + + /** + * Set default + * + * @param string|bool|int $value + * @return self + */ + public function setDefault($value) + { + $this->default = $value; + + return $this; + } + + /** + * Get value + * + * @return string|bool|int + */ + public function getValue() + { + return $this->value; + } + + /** + * Set value + * + * @param string|bool|int $value + * @return self + */ + public function setValue($value) + { + $this->value = $value; + + return $this; + } + + /** + * Get entries + * + * @return array + */ + public function getEntries() + { + return $this->entries; + } + + /** + * Set entries + * + * @param array $value + * @return self + */ + public function setEntries($value) + { + $this->entries = $value; + + return $this; + } +} diff --git a/src/PhpWord/Element/Header.php b/src/PhpWord/Element/Header.php old mode 100755 new mode 100644 index e4211d29..feaa86e8 --- a/src/PhpWord/Element/Header.php +++ b/src/PhpWord/Element/Header.php @@ -1,52 +1,31 @@ container = 'header'; - $this->sectionId = $sectionId; - $this->setType($type); - $this->setDocPart($this->container, ($sectionId - 1) * 3 + $headerId); - } + protected $container = 'Header'; /** * Add a Watermark Element @@ -59,58 +38,4 @@ class Header extends AbstractElement { return $this->addImage($src, $style, true); } - - /** - * Set header type - * - * @param string $value - * @since 0.10.0 - */ - public function setType($value = self::AUTO) - { - if (!in_array($value, array(self::AUTO, self::FIRST, self::EVEN))) { - $value = self::AUTO; - } - $this->type = $value; - } - - /** - * Get header type - * - * @return string - */ - public function getType() - { - return $this->type; - } - - /** - * Reset type to default - * - * @return string - */ - public function resetType() - { - return $this->type = self::AUTO; - } - - /** - * First page only header - * - * @return string - */ - public function firstPage() - { - return $this->type = self::FIRST; - } - - /** - * Even numbered pages only - * - * @return string - */ - public function evenPage() - { - return $this->type = self::EVEN; - } } diff --git a/src/PhpWord/Element/Image.php b/src/PhpWord/Element/Image.php old mode 100755 new mode 100644 index 942ae224..cab2527a --- a/src/PhpWord/Element/Image.php +++ b/src/PhpWord/Element/Image.php @@ -1,16 +1,27 @@ isMemImage = true; - } else { - $this->isMemImage = (filter_var($source, FILTER_VALIDATE_URL) !== false); - } - - // Check supported types - if ($this->isMemImage) { - $supportedTypes = array('image/jpeg', 'image/gif', 'image/png'); - $imgData = @getimagesize($source); - if (!is_array($imgData)) { - throw new InvalidImageException(); - } - $this->imageType = $imgData['mime']; // string - if (!in_array($this->imageType, $supportedTypes)) { - throw new UnsupportedImageTypeException(); - } - } else { - $supportedTypes = array( - IMAGETYPE_JPEG, IMAGETYPE_GIF, - IMAGETYPE_PNG, IMAGETYPE_BMP, - IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM - ); - if (!file_exists($source)) { - throw new InvalidImageException(); - } - $imgData = getimagesize($source); - if (function_exists('exif_imagetype')) { - $this->imageType = exif_imagetype($source); - } else { - // @codeCoverageIgnoreStart - $tmp = getimagesize($source); - $this->imageType = $tmp[2]; - // @codeCoverageIgnoreEnd - } - if (!in_array($this->imageType, $supportedTypes)) { - throw new UnsupportedImageTypeException(); - } - $this->imageType = image_type_to_mime_type($this->imageType); - } - - // Set private properties $this->source = $source; - $this->isWatermark = $isWatermark; - $this->style = $this->setStyle(new ImageStyle(), $style, true); - if ($this->style->getWidth() == null && $this->style->getHeight() == null) { - $this->style->setWidth($imgData[0]); - $this->style->setHeight($imgData[1]); - } - $this->setImageFunctions(); + $this->setIsWatermark($watermark); + $this->style = $this->setNewStyle(new ImageStyle(), $style, true); + + $this->checkImage($source); } /** @@ -158,6 +158,16 @@ class Image extends AbstractElement return $this->source; } + /** + * Get image source type + * + * @return string + */ + public function getSourceType() + { + return $this->sourceType; + } + /** * Get image media ID * @@ -173,19 +183,19 @@ class Image extends AbstractElement * * @return boolean */ - public function getIsWatermark() + public function isWatermark() { - return $this->isWatermark; + return $this->watermark; } /** * Set is watermark * - * @param boolean $pValue + * @param boolean $value */ - public function setIsWatermark($pValue) + public function setIsWatermark($value) { - $this->isWatermark = $pValue; + $this->watermark = $value; } /** @@ -233,15 +243,224 @@ class Image extends AbstractElement * * @return boolean */ - public function getIsMemImage() + public function isMemImage() { - return $this->isMemImage; + return $this->memoryImage; } /** - * Set image functions + * Get target file name + * + * @return string */ - private function setImageFunctions() + public function getTarget() + { + return $this->target; + } + + /** + * Set target file name. + * + * @param string $value + * @return void + */ + public function setTarget($value) + { + $this->target = $value; + } + + /** + * Get media index + * + * @return integer + */ + public function getMediaIndex() + { + return $this->mediaIndex; + } + + /** + * Set media index. + * + * @param integer $value + * @return void + */ + public function setMediaIndex($value) + { + $this->mediaIndex = $value; + } + + /** + * Get image string data + * + * @param bool $base64 + * @return string|null + * @since 0.11.0 + */ + public function getImageStringData($base64 = false) + { + $source = $this->source; + $actualSource = null; + $imageBinary = null; + $imageData = null; + $isTemp = false; + + // Get actual source from archive image or other source + // Return null if not found + if ($this->sourceType == self::SOURCE_ARCHIVE) { + $source = substr($source, 6); + list($zipFilename, $imageFilename) = explode('#', $source); + + $zip = new ZipArchive(); + if ($zip->open($zipFilename) !== false) { + if ($zip->locateName($imageFilename)) { + $isTemp = true; + $zip->extractTo(Settings::getTempDir(), $imageFilename); + $actualSource = Settings::getTempDir() . DIRECTORY_SEPARATOR . $imageFilename; + } + } + $zip->close(); + } else { + $actualSource = $source; + } + + // Can't find any case where $actualSource = null hasn't captured by + // preceding exceptions. Please uncomment when you find the case and + // put the case into Element\ImageTest. + // if ($actualSource === null) { + // return null; + // } + + // Read image binary data and convert to hex/base64 string + if ($this->sourceType == self::SOURCE_GD) { + $imageResource = call_user_func($this->imageCreateFunc, $actualSource); + ob_start(); + call_user_func($this->imageFunc, $imageResource); + $imageBinary = ob_get_contents(); + ob_end_clean(); + } else { + $fileHandle = fopen($actualSource, 'rb', false); + if ($fileHandle !== false) { + $imageBinary = fread($fileHandle, filesize($actualSource)); + fclose($fileHandle); + } + } + if ($imageBinary !== null) { + if ($base64) { + $imageData = chunk_split(base64_encode($imageBinary)); + } else { + $imageData = chunk_split(bin2hex($imageBinary)); + } + } + + // Delete temporary file if necessary + if ($isTemp === true) { + @unlink($actualSource); + } + + return $imageData; + } + + /** + * Check memory image, supported type, image functions, and proportional width/height. + * + * @param string $source + * @return void + * @throws \PhpOffice\PhpWord\Exception\InvalidImageException + * @throws \PhpOffice\PhpWord\Exception\UnsupportedImageTypeException + */ + private function checkImage($source) + { + $this->setSourceType($source); + + // Check image data + if ($this->sourceType == self::SOURCE_ARCHIVE) { + $imageData = $this->getArchiveImageSize($source); + } else { + $imageData = @getimagesize($source); + } + if (!is_array($imageData)) { + throw new InvalidImageException(); + } + list($actualWidth, $actualHeight, $imageType) = $imageData; + + // Check image type support + $supportedTypes = array(IMAGETYPE_JPEG, IMAGETYPE_GIF, IMAGETYPE_PNG); + if ($this->sourceType != self::SOURCE_GD) { + $supportedTypes = array_merge($supportedTypes, array(IMAGETYPE_BMP, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM)); + } + if (!in_array($imageType, $supportedTypes)) { + throw new UnsupportedImageTypeException(); + } + + // Define image functions + $this->imageType = image_type_to_mime_type($imageType); + $this->setFunctions(); + $this->setProportionalSize($actualWidth, $actualHeight); + } + + /** + * Set source type. + * + * @param string $source + * @return void + */ + private function setSourceType($source) + { + if (stripos(strrev($source), strrev('.php')) === 0) { + $this->memoryImage = true; + $this->sourceType = self::SOURCE_GD; + } elseif (strpos($source, 'zip://') !== false) { + $this->memoryImage = false; + $this->sourceType = self::SOURCE_ARCHIVE; + } else { + $this->memoryImage = (filter_var($source, FILTER_VALIDATE_URL) !== false); + $this->sourceType = $this->memoryImage ? self::SOURCE_GD : self::SOURCE_LOCAL; + } + } + + /** + * Get image size from archive + * + * @since 0.12.0 Throws CreateTemporaryFileException. + * + * @param string $source + * @return array|null + * @throws \PhpOffice\PhpWord\Exception\CreateTemporaryFileException + */ + private function getArchiveImageSize($source) + { + $imageData = null; + $source = substr($source, 6); + list($zipFilename, $imageFilename) = explode('#', $source); + + $tempFilename = tempnam(Settings::getTempDir(), 'PHPWordImage'); + if (false === $tempFilename) { + throw new CreateTemporaryFileException(); + } + + $zip = new ZipArchive(); + if ($zip->open($zipFilename) !== false) { + if ($zip->locateName($imageFilename)) { + $imageContent = $zip->getFromName($imageFilename); + if ($imageContent !== false) { + file_put_contents($tempFilename, $imageContent); + $imageData = getimagesize($tempFilename); + unlink($tempFilename); + } + } + $zip->close(); + } + + return $imageData; + } + + /** + * Set image functions and extensions. + * + * @return void + */ + private function setFunctions() { switch ($this->imageType) { case 'image/png': @@ -260,8 +479,8 @@ class Image extends AbstractElement $this->imageFunc = 'imagejpeg'; $this->imageExtension = 'jpg'; break; - case 'image/x-ms-bmp': case 'image/bmp': + case 'image/x-ms-bmp': $this->imageType = 'image/bmp'; $this->imageExtension = 'bmp'; break; @@ -270,4 +489,49 @@ class Image extends AbstractElement break; } } + + /** + * Set proportional width/height if one dimension not available. + * + * @param integer $actualWidth + * @param integer $actualHeight + * @return void + */ + private function setProportionalSize($actualWidth, $actualHeight) + { + $styleWidth = $this->style->getWidth(); + $styleHeight = $this->style->getHeight(); + if (!($styleWidth && $styleHeight)) { + if ($styleWidth == null && $styleHeight == null) { + $this->style->setWidth($actualWidth); + $this->style->setHeight($actualHeight); + } elseif ($styleWidth) { + $this->style->setHeight($actualHeight * ($styleWidth / $actualWidth)); + } else { + $this->style->setWidth($actualWidth * ($styleHeight / $actualHeight)); + } + } + } + + /** + * Get is watermark + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getIsWatermark() + { + return $this->isWatermark(); + } + + /** + * Get is memory image + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getIsMemImage() + { + return $this->isMemImage(); + } } diff --git a/src/PhpWord/Element/Line.php b/src/PhpWord/Element/Line.php new file mode 100644 index 00000000..b76ac4fb --- /dev/null +++ b/src/PhpWord/Element/Line.php @@ -0,0 +1,53 @@ +style = $this->setNewStyle(new LineStyle(), $style); + } + + /** + * Get line style + * + * @return \PhpOffice\PhpWord\Style\Line + */ + public function getStyle() + { + return $this->style; + } +} diff --git a/src/PhpWord/Element/Link.php b/src/PhpWord/Element/Link.php index 1cf35624..9d0eb766 100644 --- a/src/PhpWord/Element/Link.php +++ b/src/PhpWord/Element/Link.php @@ -1,14 +1,23 @@ source = $linkSrc; - $this->name = $linkName; - $this->fontStyle = $this->setStyle(new Font('text'), $fontStyle); - $this->paragraphStyle = $this->setStyle(new Paragraph(), $paragraphStyle); - + $this->source = String::toUTF8($source); + $this->text = is_null($text) ? $this->source : String::toUTF8($text); + $this->fontStyle = $this->setNewStyle(new Font('text'), $fontStyle); + $this->paragraphStyle = $this->setNewStyle(new Paragraph(), $paragraphStyle); + $this->internal = $internal; return $this; } /** - * Get Link source + * Get link source * * @return string */ - public function getLinkSrc() + public function getSource() { return $this->source; } /** - * Get Link name + * Get link text * * @return string */ - public function getLinkName() + public function getText() { - return $this->name; + return $this->text; } /** * Get Text style * - * @return string|Font + * @return string|\PhpOffice\PhpWord\Style\Font */ public function getFontStyle() { @@ -97,10 +119,56 @@ class Link extends AbstractElement /** * Get Paragraph style * - * @return string|Paragraph + * @return string|\PhpOffice\PhpWord\Style\Paragraph */ public function getParagraphStyle() { return $this->paragraphStyle; } + + /** + * Get link target + * + * @return string + * @deprecated 0.12.0 + * @codeCoverageIgnore + */ + public function getTarget() + { + return $this->source; + } + + /** + * Get Link source + * + * @return string + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getLinkSrc() + { + return $this->getSource(); + } + + /** + * Get Link name + * + * @return string + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getLinkName() + { + return $this->getText(); + } + + /** + * is internal + * + * @return bool + */ + public function isInternal() + { + return $this->internal; + } } diff --git a/src/PhpWord/Element/ListItem.php b/src/PhpWord/Element/ListItem.php index bebf8b38..4cb8d339 100644 --- a/src/PhpWord/Element/ListItem.php +++ b/src/PhpWord/Element/ListItem.php @@ -1,15 +1,23 @@ textObject = new Text($text, $fontStyle, $paragraphStyle); + $this->textObject = new Text(String::toUTF8($text), $fontStyle, $paragraphStyle); $this->depth = $depth; // Version >= 0.10.0 will pass numbering style name. Older version will use old method if (!is_null($listStyle) && is_string($listStyle)) { $this->style = new ListItemStyle($listStyle); } else { - $this->style = $this->setStyle(new ListItemStyle(), $listStyle, true); + $this->style = $this->setNewStyle(new ListItemStyle(), $listStyle, true); } } /** - * Get ListItem style + * Get style + * + * @return \PhpOffice\PhpWord\Style\ListItem */ public function getStyle() { @@ -70,7 +79,9 @@ class ListItem extends AbstractElement } /** - * Get ListItem TextRun + * Get Text object + * + * @return \PhpOffice\PhpWord\Element\Text */ public function getTextObject() { @@ -78,10 +89,23 @@ class ListItem extends AbstractElement } /** - * Get ListItem depth + * Get depth + * + * @return int */ public function getDepth() { return $this->depth; } + + /** + * Get text + * + * @return string + * @since 0.11.0 + */ + public function getText() + { + return $this->textObject->getText(); + } } diff --git a/src/PhpWord/Element/ListItemRun.php b/src/PhpWord/Element/ListItemRun.php new file mode 100644 index 00000000..1b77830d --- /dev/null +++ b/src/PhpWord/Element/ListItemRun.php @@ -0,0 +1,86 @@ +depth = $depth; + + // Version >= 0.10.0 will pass numbering style name. Older version will use old method + if (!is_null($listStyle) && is_string($listStyle)) { + $this->style = new ListItemStyle($listStyle); + } else { + $this->style = $this->setNewStyle(new ListItemStyle(), $listStyle, true); + } + $this->paragraphStyle = $this->setNewStyle(new Paragraph(), $paragraphStyle); + } + + /** + * Get ListItem style. + * + * @return \PhpOffice\PhpWord\Style\ListItem + */ + public function getStyle() + { + return $this->style; + } + + /** + * Get ListItem depth. + * + * @return int + */ + public function getDepth() + { + return $this->depth; + } +} diff --git a/src/PhpWord/Element/Object.php b/src/PhpWord/Element/Object.php index 81004872..31943ba6 100644 --- a/src/PhpWord/Element/Object.php +++ b/src/PhpWord/Element/Object.php @@ -1,14 +1,23 @@ source = $source; + $this->style = $this->setNewStyle(new ImageStyle(), $style, true); + $this->icon = realpath(__DIR__ . "/../resources/{$ext}.png"); - if (file_exists($src) && in_array($inf['extension'], $supportedTypes)) { - $this->source = $src; - $this->style = $this->setStyle(new ImageStyle(), $style, true); return $this; } else { - return false; + throw new InvalidObjectException(); } } /** - * Get Image style - * - * @return ImageStyle - */ - public function getStyle() - { - return $this->style; - } - - /** - * Get Source + * Get object source * * @return string */ @@ -78,7 +99,27 @@ class Object extends AbstractElement } /** - * Get Image Relation ID + * Get object style + * + * @return \PhpOffice\PhpWord\Style\Image + */ + public function getStyle() + { + return $this->style; + } + + /** + * Get object icon + * + * @return string + */ + public function getIcon() + { + return $this->icon; + } + + /** + * Get image relation ID * * @return int */ @@ -88,9 +129,10 @@ class Object extends AbstractElement } /** - * Set Image Relation ID + * Set Image Relation ID. * * @param int $rId + * @return void */ public function setImageRelationId($rId) { diff --git a/src/PhpWord/Element/PageBreak.php b/src/PhpWord/Element/PageBreak.php index d2f85f20..a1e7e998 100644 --- a/src/PhpWord/Element/PageBreak.php +++ b/src/PhpWord/Element/PageBreak.php @@ -1,10 +1,18 @@ fontStyle = $this->setStyle(new Font('text'), $styleFont); - $this->paragraphStyle = $this->setStyle(new Paragraph(), $styleParagraph); + $this->fontStyle = $this->setNewStyle(new Font('text'), $fontStyle); + $this->paragraphStyle = $this->setNewStyle(new Paragraph(), $paragraphStyle); - $matches = preg_split('/({.*?})/', $text, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); + $this->text = String::toUTF8($text); + $matches = preg_split('/({.*?})/', $this->text, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); if (isset($matches[0])) { $this->text = $matches; } @@ -63,7 +73,7 @@ class PreserveText extends AbstractElement /** * Get Text style * - * @return string|Font + * @return string|\PhpOffice\PhpWord\Style\Font */ public function getFontStyle() { @@ -73,7 +83,7 @@ class PreserveText extends AbstractElement /** * Get Paragraph style * - * @return string|Paragraph + * @return string|\PhpOffice\PhpWord\Style\Paragraph */ public function getParagraphStyle() { diff --git a/src/PhpWord/Element/Row.php b/src/PhpWord/Element/Row.php index c20b018b..e2df6325 100644 --- a/src/PhpWord/Element/Row.php +++ b/src/PhpWord/Element/Row.php @@ -1,10 +1,18 @@ setDocPart($docPart, $docPartId); $this->height = $height; - $this->style = $this->setStyle(new RowStyle(), $style, true); + $this->style = $this->setNewStyle(new RowStyle(), $style, true); } /** @@ -57,18 +64,21 @@ class Row extends AbstractElement * * @param int $width * @param mixed $style + * @return \PhpOffice\PhpWord\Element\Cell */ public function addCell($width = null, $style = null) { - $cell = new Cell($this->getDocPart(), $this->getDocPartId(), $width, $style); + $cell = new Cell($width, $style); + $cell->setParentContainer($this); $this->cells[] = $cell; + return $cell; } /** * Get all cells * - * @return array + * @return \PhpOffice\PhpWord\Element\Cell[] */ public function getCells() { @@ -78,7 +88,7 @@ class Row extends AbstractElement /** * Get row style * - * @return RowStyle + * @return \PhpOffice\PhpWord\Style\Row */ public function getStyle() { diff --git a/src/PhpWord/Element/SDT.php b/src/PhpWord/Element/SDT.php new file mode 100644 index 00000000..c69ed427 --- /dev/null +++ b/src/PhpWord/Element/SDT.php @@ -0,0 +1,130 @@ +setType($type); + } + + /** + * Get type + * + * @return string + */ + public function getType() + { + return $this->type; + } + + /** + * Set type + * + * @param string $value + * @return self + */ + public function setType($value) + { + $enum = array('comboBox', 'dropDownList', 'date'); + $this->type = $this->setEnumVal($value, $enum, 'comboBox'); + + return $this; + } + + /** + * Get value + * + * @return string|bool|int + */ + public function getValue() + { + return $this->value; + } + + /** + * Set value + * + * @param string|bool|int $value + * @return self + */ + public function setValue($value) + { + $this->value = $value; + + return $this; + } + + /** + * Get listItems + * + * @return array + */ + public function getListItems() + { + return $this->listItems; + } + + /** + * Set listItems + * + * @param array $value + * @return self + */ + public function setListItems($value) + { + $this->listItems = $value; + + return $this; + } +} diff --git a/src/PhpWord/Element/Section.php b/src/PhpWord/Element/Section.php index 9e5dbd0a..d746f69b 100644 --- a/src/PhpWord/Element/Section.php +++ b/src/PhpWord/Element/Section.php @@ -1,29 +1,41 @@ container = 'section'; $this->sectionId = $sectionCount; $this->setDocPart($this->container, $this->sectionId); - $this->settings = new SectionSettings(); - $this->setSettings($settings); + $this->style = new SectionStyle(); + $this->setStyle($style); } /** - * Set section settings + * Set section style. * - * @param array $settings + * @param array $style + * @return void */ - public function setSettings($settings = null) + public function setStyle($style = null) { - if (!is_null($settings) && is_array($settings)) { - foreach ($settings as $key => $value) { - if (is_null($value)) { - continue; - } - $this->settings->setSettingValue($key, $value); - } + if (!is_null($style) && is_array($style)) { + $this->style->setStyleByArray($style); } } /** - * Get Section Settings + * Get section style * - * @return SectionSettings + * @return \PhpOffice\PhpWord\Style\Section */ - public function getSettings() + public function getStyle() { - return $this->settings; - } - - /** - * Add a PageBreak Element - */ - public function addPageBreak() - { - $this->elements[] = new PageBreak(); - } - - /** - * Add a Table-of-Contents Element - * - * @param mixed $styleFont - * @param mixed $styleTOC - * @param integer $minDepth - * @param integer $maxDepth - * @return TOC - */ - public function addTOC($styleFont = null, $styleTOC = null, $minDepth = 1, $maxDepth = 9) - { - $toc = new TOC($styleFont, $styleTOC, $minDepth, $maxDepth); - $this->elements[] = $toc; - return $toc; + return $this->style; } /** @@ -173,19 +156,22 @@ class Section extends AbstractElement * @param string $type * @param boolean $header * @return Header|Footer - * @throws Exception + * @throws \PhpOffice\PhpWord\Exception\Exception * @since 0.10.0 */ private function addHeaderFooter($type = Header::AUTO, $header = true) { + $containerClass = substr(get_class($this), 0, strrpos(get_class($this), '\\')) . '\\' . + ($header ? 'Header' : 'Footer'); $collectionArray = $header ? 'headers' : 'footers'; - $containerClass = 'PhpOffice\\PhpWord\\Element\\'; - $containerClass .= ($header ? 'Header' : 'Footer'); $collection = &$this->$collectionArray; if (in_array($type, array(Header::AUTO, Header::FIRST, Header::EVEN))) { $index = count($collection); + /** @var \PhpOffice\PhpWord\Element\AbstractContainer $container Type hint */ $container = new $containerClass($this->sectionId, ++$index, $type); + $container->setPhpWord($this->phpWord); + $collection[$index] = $container; return $container; } else { @@ -194,6 +180,30 @@ class Section extends AbstractElement } + /** + * Set section style + * + * @param array $settings + * @deprecated 0.12.0 + * @codeCoverageIgnore + */ + public function setSettings($settings = null) + { + $this->setStyle($settings); + } + + /** + * Get section style + * + * @return \PhpOffice\PhpWord\Style\Section + * @deprecated 0.12.0 + * @codeCoverageIgnore + */ + public function getSettings() + { + return $this->getStyle(); + } + /** * Create header * diff --git a/src/PhpWord/Element/Shape.php b/src/PhpWord/Element/Shape.php new file mode 100644 index 00000000..a7a96d18 --- /dev/null +++ b/src/PhpWord/Element/Shape.php @@ -0,0 +1,88 @@ +setType($type); + $this->style = $this->setNewStyle(new ShapeStyle(), $style); + } + + /** + * Get type + * + * @return string + */ + public function getType() + { + return $this->type; + } + + /** + * Set pattern + * + * @param string $value + * @return self + */ + public function setType($value = null) + { + $enum = array('arc', 'curve', 'line', 'polyline', 'rect', 'oval'); + $this->type = $this->setEnumVal($value, $enum, null); + + return $this; + } + + /** + * Get shape style + * + * @return \PhpOffice\PhpWord\Style\Shape + */ + public function getStyle() + { + return $this->style; + } +} diff --git a/src/PhpWord/Element/TOC.php b/src/PhpWord/Element/TOC.php new file mode 100644 index 00000000..a56d9ffe --- /dev/null +++ b/src/PhpWord/Element/TOC.php @@ -0,0 +1,172 @@ +TOCStyle = new TOCStyle(); + + if (!is_null($tocStyle) && is_array($tocStyle)) { + $this->TOCStyle->setStyleByArray($tocStyle); + } + + if (!is_null($fontStyle) && is_array($fontStyle)) { + $this->fontStyle = new Font(); + $this->fontStyle->setStyleByArray($fontStyle); + } else { + $this->fontStyle = $fontStyle; + } + + $this->minDepth = $minDepth; + $this->maxDepth = $maxDepth; + } + + /** + * Get all titles + * + * @return array + */ + public function getTitles() + { + if (!$this->phpWord instanceof PhpWord) { + return array(); + } + + $titles = $this->phpWord->getTitles()->getItems(); + foreach ($titles as $i => $title) { + /** @var \PhpOffice\PhpWord\Element\Title $title Type hint */ + $depth = $title->getDepth(); + if ($this->minDepth > $depth) { + unset($titles[$i]); + } + if (($this->maxDepth != 0) && ($this->maxDepth < $depth)) { + unset($titles[$i]); + } + } + + return $titles; + } + + /** + * Get TOC Style + * + * @return \PhpOffice\PhpWord\Style\TOC + */ + public function getStyleTOC() + { + return $this->TOCStyle; + } + + /** + * Get Font Style + * + * @return \PhpOffice\PhpWord\Style\Font + */ + public function getStyleFont() + { + return $this->fontStyle; + } + + /** + * Set max depth. + * + * @param int $value + * @return void + */ + public function setMaxDepth($value) + { + $this->maxDepth = $value; + } + + /** + * Get Max Depth + * + * @return int Max depth of titles + */ + public function getMaxDepth() + { + return $this->maxDepth; + } + + /** + * Set min depth. + * + * @param int $value + * @return void + */ + public function setMinDepth($value) + { + $this->minDepth = $value; + } + + /** + * Get Min Depth + * + * @return int Min depth of titles + */ + public function getMinDepth() + { + return $this->minDepth; + } +} diff --git a/src/PhpWord/Element/Table.php b/src/PhpWord/Element/Table.php index 3241a8e2..5f0b8f79 100644 --- a/src/PhpWord/Element/Table.php +++ b/src/PhpWord/Element/Table.php @@ -1,16 +1,22 @@ setDocPart($docPart, $docPartId); - $this->style = $this->setStyle(new TableStyle(), $style); + $this->style = $this->setNewStyle(new TableStyle(), $style); } /** * Add a row * - * @param integer $height + * @param int $height * @param mixed $style + * @return \PhpOffice\PhpWord\Element\Row */ public function addRow($height = null, $style = null) { - $row = new Row($this->getDocPart(), $this->getDocPartId(), $height, $style); + $row = new Row($height, $style); + $row->setParentContainer($this); $this->rows[] = $row; + return $row; } /** * Add a cell * - * @param integer $width + * @param int $width * @param mixed $style - * @return Cell + * @return \PhpOffice\PhpWord\Element\Cell */ public function addCell($width = null, $style = null) { - $i = count($this->rows) - 1; - $cell = $this->rows[$i]->addCell($width, $style); + $index = count($this->rows) - 1; + $row = $this->rows[$index]; + $cell = $row->addCell($width, $style); + return $cell; } /** * Get all rows * - * @return array + * @return \PhpOffice\PhpWord\Element\Row[] */ public function getRows() { @@ -93,37 +100,38 @@ class Table extends AbstractElement /** * Get table style * - * @return TableStyle + * @return \PhpOffice\PhpWord\Style\Table */ public function getStyle() { return $this->style; } - /** - * Set table width - * - * @param integer $width - */ - public function setWidth($width) - { - $this->width = $width; - } - /** * Get table width * - * @return integer + * @return int */ public function getWidth() { return $this->width; } + /** + * Set table width. + * + * @param int $width + * @return void + */ + public function setWidth($width) + { + $this->width = $width; + } + /** * Get column count * - * @return integer + * @return int */ public function countColumns() { @@ -131,7 +139,9 @@ class Table extends AbstractElement if (is_array($this->rows)) { $rowCount = count($this->rows); for ($i = 0; $i < $rowCount; $i++) { - $cellCount = count($this->rows[$i]->getCells()); + /** @var \PhpOffice\PhpWord\Element\Row $row Type hint */ + $row = $this->rows[$i]; + $cellCount = count($row->getCells()); if ($columnCount < $cellCount) { $columnCount = $cellCount; } diff --git a/src/PhpWord/Element/Text.php b/src/PhpWord/Element/Text.php index bb1d5aac..52fccb3f 100644 --- a/src/PhpWord/Element/Text.php +++ b/src/PhpWord/Element/Text.php @@ -1,14 +1,23 @@ setParagraphStyle($paragraphStyle); } elseif (is_array($style)) { $this->fontStyle = new Font('text', $paragraphStyle); - $this->fontStyle->setArrayStyle($style); + $this->fontStyle->setStyleByArray($style); } elseif (null === $style) { $this->fontStyle = new Font('text', $paragraphStyle); } else { $this->fontStyle = $style; $this->setParagraphStyle($paragraphStyle); } + return $this->fontStyle; } /** * Get Text style * - * @return string|Font + * @return string|\PhpOffice\PhpWord\Style\Font */ public function getFontStyle() { @@ -89,14 +99,14 @@ class Text extends AbstractElement /** * Set Paragraph style * - * @param string|array|Paragraph $style - * @return string|Paragraph + * @param string|array|\PhpOffice\PhpWord\Style\Paragraph $style + * @return string|\PhpOffice\PhpWord\Style\Paragraph */ public function setParagraphStyle($style = null) { if (is_array($style)) { $this->paragraphStyle = new Paragraph; - $this->paragraphStyle->setArrayStyle($style); + $this->paragraphStyle->setStyleByArray($style); } elseif ($style instanceof Paragraph) { $this->paragraphStyle = $style; } elseif (null === $style) { @@ -104,13 +114,14 @@ class Text extends AbstractElement } else { $this->paragraphStyle = $style; } + return $this->paragraphStyle; } /** * Get Paragraph style * - * @return string|Paragraph + * @return string|\PhpOffice\PhpWord\Style\Paragraph */ public function getParagraphStyle() { @@ -121,11 +132,12 @@ class Text extends AbstractElement * Set text content * * @param string $text - * @return $this + * @return self */ public function setText($text) { - $this->text = $text; + $this->text = String::toUTF8($text); + return $this; } diff --git a/src/PhpWord/Element/TextBox.php b/src/PhpWord/Element/TextBox.php new file mode 100644 index 00000000..d929bf35 --- /dev/null +++ b/src/PhpWord/Element/TextBox.php @@ -0,0 +1,60 @@ +style = $this->setNewStyle(new TextBoxStyle(), $style); + } + + /** + * Get textbox style + * + * @return \PhpOffice\PhpWord\Style\TextBox + */ + public function getStyle() + { + return $this->style; + } +} diff --git a/src/PhpWord/Element/TextBreak.php b/src/PhpWord/Element/TextBreak.php old mode 100755 new mode 100644 index aa3d5cca..aa6ab582 --- a/src/PhpWord/Element/TextBreak.php +++ b/src/PhpWord/Element/TextBreak.php @@ -1,10 +1,18 @@ setParagraphStyle($paragraphStyle); } elseif (is_array($style)) { $this->fontStyle = new Font('text', $paragraphStyle); - $this->fontStyle->setArrayStyle($style); + $this->fontStyle->setStyleByArray($style); } else { $this->fontStyle = $style; $this->setParagraphStyle($paragraphStyle); @@ -72,7 +80,7 @@ class TextBreak extends AbstractElement /** * Get Text style * - * @return string|Font + * @return string|\PhpOffice\PhpWord\Style\Font */ public function getFontStyle() { @@ -82,14 +90,14 @@ class TextBreak extends AbstractElement /** * Set Paragraph style * - * @param string|array|Paragraph $style - * @return string|Paragraph + * @param string|array|\PhpOffice\PhpWord\Style\Paragraph $style + * @return string|\PhpOffice\PhpWord\Style\Paragraph */ public function setParagraphStyle($style = null) { if (is_array($style)) { $this->paragraphStyle = new Paragraph; - $this->paragraphStyle->setArrayStyle($style); + $this->paragraphStyle->setStyleByArray($style); } elseif ($style instanceof Paragraph) { $this->paragraphStyle = $style; } else { @@ -101,10 +109,20 @@ class TextBreak extends AbstractElement /** * Get Paragraph style * - * @return string|Paragraph + * @return string|\PhpOffice\PhpWord\Style\Paragraph */ public function getParagraphStyle() { return $this->paragraphStyle; } + + /** + * Has font/paragraph style defined + * + * @return bool + */ + public function hasStyle() + { + return !is_null($this->fontStyle) || !is_null($this->paragraphStyle); + } } diff --git a/src/PhpWord/Element/TextRun.php b/src/PhpWord/Element/TextRun.php old mode 100755 new mode 100644 index f7286d8f..c356cfa8 --- a/src/PhpWord/Element/TextRun.php +++ b/src/PhpWord/Element/TextRun.php @@ -1,10 +1,18 @@ container = 'textrun'; - $this->paragraphStyle = $this->setStyle(new Paragraph(), $paragraphStyle); + $this->paragraphStyle = $this->setNewStyle(new Paragraph(), $paragraphStyle); } /** * Get Paragraph style * - * @return string|Paragraph + * @return string|\PhpOffice\PhpWord\Style\Paragraph */ public function getParagraphStyle() { diff --git a/src/PhpWord/Element/Title.php b/src/PhpWord/Element/Title.php index 5ed1bfbc..8d385845 100644 --- a/src/PhpWord/Element/Title.php +++ b/src/PhpWord/Element/Title.php @@ -1,14 +1,25 @@ style = $style; + + $this->text = String::toUTF8($text); + $this->depth = $depth; + if (array_key_exists('Heading_' . $this->depth, Style::getStyles())) { + $this->style = 'Heading' . $this->depth; } - $this->text = $text; - $this->depth = $depth; - return $this; } - /** - * Set Anchor - * - * @param int $anchor - */ - public function setAnchor($anchor) - { - $this->anchor = $anchor; - } - - /** - * Get Anchor - * - * @return int - */ - public function getAnchor() - { - return $this->anchor; - } - - /** - * Set Bookmark ID - * - * @param int $bookmarkId - */ - public function setBookmarkId($bookmarkId) - { - $this->bookmarkId = $bookmarkId; - } - - /** - * Get Anchor - * - * @return int - */ - public function getBookmarkId() - { - return $this->bookmarkId; - } - /** * Get Title Text content * @@ -119,6 +81,16 @@ class Title extends AbstractElement return $this->text; } + /** + * Get depth + * + * @return integer + */ + public function getDepth() + { + return $this->depth; + } + /** * Get Title style * diff --git a/src/PhpWord/Endnotes.php b/src/PhpWord/Endnotes.php deleted file mode 100644 index 206814e8..00000000 --- a/src/PhpWord/Endnotes.php +++ /dev/null @@ -1,97 +0,0 @@ - $mediaTypeCount); switch ($mediaType) { // Images @@ -57,7 +67,7 @@ class Media if (is_null($image)) { throw new Exception('Image object not assigned.'); } - $isMemImage = $image->getIsMemImage(); + $isMemImage = $image->isMemImage(); $extension = $image->getImageExtension(); $mediaData['imageExtension'] = $extension; $mediaData['imageType'] = $image->getImageType(); @@ -66,12 +76,14 @@ class Media $mediaData['createFunction'] = $image->getImageCreateFunction(); $mediaData['imageFunction'] = $image->getImageFunction(); } - $target = "media/{$container}_image{$mediaTypeCount}.{$extension}"; + $target = "{$container}_image{$mediaTypeCount}.{$extension}"; + $image->setTarget($target); + $image->setMediaIndex($mediaTypeCount); break; // Objects case 'object': - $target = "embeddings/{$container}_oleObject{$mediaTypeCount}.bin"; + $target = "{$container}_oleObject{$mediaTypeCount}.bin"; break; // Links @@ -87,7 +99,12 @@ class Media self::$elements[$container][$mediaId] = $mediaData; return $rId; } else { - return self::$elements[$container][$mediaId]['rID']; + $mediaData = self::$elements[$container][$mediaId]; + if (!is_null($image)) { + $image->setTarget($mediaData['target']); + $image->setMediaIndex($mediaData['mediaIndex']); + } + return $mediaData['rID']; } } @@ -104,7 +121,7 @@ class Media $mediaCount = 0; if (array_key_exists($container, self::$elements)) { - foreach (self::$elements[$container] as $mediaKey => $mediaData) { + foreach (self::$elements[$container] as $mediaData) { if (!is_null($mediaType)) { if ($mediaType == $mediaData['type']) { $mediaCount++; @@ -122,37 +139,53 @@ class Media * Get media elements * * @param string $container section|headerx|footerx|footnote|endnote - * @param string $mediaType image|object|link + * @param string $type image|object|link * @return array * @since 0.10.0 */ - public static function getElements($container, $mediaType = null) + public static function getElements($container, $type = null) { - $mediaElements = array(); + $elements = array(); // If header/footer, search for headerx and footerx where x is number if ($container == 'header' || $container == 'footer') { foreach (self::$elements as $key => $val) { if (substr($key, 0, 6) == $container) { - $mediaElements[$key] = $val; + $elements[$key] = $val; } } + return $elements; } else { if (!array_key_exists($container, self::$elements)) { - return $mediaElements; + return $elements; } - foreach (self::$elements[$container] as $mediaKey => $mediaData) { - if (!is_null($mediaType)) { - if ($mediaType == $mediaData['type']) { - $mediaElements[$mediaKey] = $mediaData; - } - } else { - $mediaElements[$mediaKey] = $mediaData; + return self::getElementsByType($container, $type); + } + } + + /** + * Get elements by media type + * + * @param string $container section|footnote|endnote + * @param string $type image|object|link + * @return array + * @since 0.11.0 Splitted from `getElements` to reduce complexity + */ + private static function getElementsByType($container, $type = null) + { + $elements = array(); + + foreach (self::$elements[$container] as $key => $data) { + if ($type !== null) { + if ($type == $data['type']) { + $elements[$key] = $data; } + } else { + $elements[$key] = $data; } } - return $mediaElements; + return $elements; } /** @@ -168,7 +201,7 @@ class Media * * @param string $src * @param string $type - * @param Image $image + * @param \PhpOffice\PhpWord\Element\Image $image * @return integer * @deprecated 0.10.0 * @codeCoverageIgnore @@ -222,7 +255,7 @@ class Media * * @param integer $headerCount * @param string $src - * @param Image $image + * @param \PhpOffice\PhpWord\Element\Image $image * @return integer * @deprecated 0.10.0 * @codeCoverageIgnore @@ -262,7 +295,7 @@ class Media * * @param integer $footerCount * @param string $src - * @param Image $image + * @param \PhpOffice\PhpWord\Element\Image $image * @return integer * @deprecated 0.10.0 * @codeCoverageIgnore diff --git a/src/PhpWord/Metadata/Compatibility.php b/src/PhpWord/Metadata/Compatibility.php new file mode 100644 index 00000000..d78b97f1 --- /dev/null +++ b/src/PhpWord/Metadata/Compatibility.php @@ -0,0 +1,62 @@ +ooxmlVersion; + } + + /** + * Set OOXML version + * + * @param int $value + * @return self + */ + public function setOoxmlVersion($value) + { + $this->ooxmlVersion = $value; + + return $this; + } +} diff --git a/src/PhpWord/DocumentProperties.php b/src/PhpWord/Metadata/DocInfo.php similarity index 59% rename from src/PhpWord/DocumentProperties.php rename to src/PhpWord/Metadata/DocInfo.php index f41ae421..9643685f 100644 --- a/src/PhpWord/DocumentProperties.php +++ b/src/PhpWord/Metadata/DocInfo.php @@ -1,20 +1,28 @@ creator = $pValue; + $this->creator = $this->setValue($value, ''); + return $this; } @@ -159,12 +168,13 @@ class DocumentProperties /** * Set Last Modified By * - * @param string $pValue + * @param string $value * @return self */ - public function setLastModifiedBy($pValue = '') + public function setLastModifiedBy($value = '') { - $this->lastModifiedBy = $pValue; + $this->lastModifiedBy = $this->setValue($value, $this->creator); + return $this; } @@ -181,15 +191,13 @@ class DocumentProperties /** * Set Created * - * @param int $pValue + * @param int $value * @return self */ - public function setCreated($pValue = null) + public function setCreated($value = null) { - if (is_null($pValue)) { - $pValue = time(); - } - $this->created = $pValue; + $this->created = $this->setValue($value, time()); + return $this; } @@ -206,15 +214,13 @@ class DocumentProperties /** * Set Modified * - * @param int $pValue + * @param int $value * @return self */ - public function setModified($pValue = null) + public function setModified($value = null) { - if (is_null($pValue)) { - $pValue = time(); - } - $this->modified = $pValue; + $this->modified = $this->setValue($value, time()); + return $this; } @@ -231,12 +237,13 @@ class DocumentProperties /** * Set Title * - * @param string $pValue + * @param string $value * @return self */ - public function setTitle($pValue = '') + public function setTitle($value = '') { - $this->title = $pValue; + $this->title = $this->setValue($value, ''); + return $this; } @@ -253,12 +260,13 @@ class DocumentProperties /** * Set Description * - * @param string $pValue + * @param string $value * @return self */ - public function setDescription($pValue = '') + public function setDescription($value = '') { - $this->description = $pValue; + $this->description = $this->setValue($value, ''); + return $this; } @@ -275,12 +283,13 @@ class DocumentProperties /** * Set Subject * - * @param string $pValue + * @param string $value * @return self */ - public function setSubject($pValue = '') + public function setSubject($value = '') { - $this->subject = $pValue; + $this->subject = $this->setValue($value, ''); + return $this; } @@ -297,12 +306,13 @@ class DocumentProperties /** * Set Keywords * - * @param string $pValue + * @param string $value * @return self */ - public function setKeywords($pValue = '') + public function setKeywords($value = '') { - $this->keywords = $pValue; + $this->keywords = $this->setValue($value, ''); + return $this; } @@ -319,12 +329,13 @@ class DocumentProperties /** * Set Category * - * @param string $pValue + * @param string $value * @return self */ - public function setCategory($pValue = '') + public function setCategory($value = '') { - $this->category = $pValue; + $this->category = $this->setValue($value, ''); + return $this; } @@ -341,12 +352,13 @@ class DocumentProperties /** * Set Company * - * @param string $pValue + * @param string $value * @return self */ - public function setCompany($pValue = '') + public function setCompany($value = '') { - $this->company = $pValue; + $this->company = $this->setValue($value, ''); + return $this; } @@ -363,12 +375,13 @@ class DocumentProperties /** * Set Manager * - * @param string $pValue + * @param string $value * @return self */ - public function setManager($pValue = '') + public function setManager($value = '') { - $this->manager = $pValue; + $this->manager = $this->setValue($value, ''); + return $this; } @@ -401,10 +414,11 @@ class DocumentProperties */ public function getCustomPropertyValue($propertyName) { - if (isset($this->customProperties[$propertyName])) { + if ($this->isCustomPropertySet($propertyName)) { return $this->customProperties[$propertyName]['value']; + } else { + return null; } - } /** @@ -415,10 +429,11 @@ class DocumentProperties */ public function getCustomPropertyType($propertyName) { - if (isset($this->customProperties[$propertyName])) { + if ($this->isCustomPropertySet($propertyName)) { return $this->customProperties[$propertyName]['type']; + } else { + return null; } - } /** @@ -473,50 +488,23 @@ class DocumentProperties */ public static function convertProperty($propertyValue, $propertyType) { - switch ($propertyType) { - case 'empty': // Empty + $conversion = self::getConversion($propertyType); + + switch ($conversion) { + case 'empty': // Empty return ''; - case 'null': // Null + case 'null': // Null return null; - case 'i1': // 1-Byte Signed Integer - case 'i2': // 2-Byte Signed Integer - case 'i4': // 4-Byte Signed Integer - case 'i8': // 8-Byte Signed Integer - case 'int': // Integer + case 'int': // Signed integer return (int) $propertyValue; - case 'ui1': // 1-Byte Unsigned Integer - case 'ui2': // 2-Byte Unsigned Integer - case 'ui4': // 4-Byte Unsigned Integer - case 'ui8': // 8-Byte Unsigned Integer - case 'uint': // Unsigned Integer + case 'uint': // Unsigned integer return abs((int) $propertyValue); - case 'r4': // 4-Byte Real Number - case 'r8': // 8-Byte Real Number - case 'decimal': // Decimal + case 'float': // Float return (float) $propertyValue; - case 'lpstr': // LPSTR - case 'lpwstr': // LPWSTR - case 'bstr': // Basic String - return $propertyValue; - case 'date': // Date and Time - case 'filetime': // File Time + case 'date': // Date return strtotime($propertyValue); - case 'bool': // Boolean + case 'bool': // Boolean return ($propertyValue == 'true') ? true : false; - case 'cy': // Currency - case 'error': // Error Status Code - case 'vector': // Vector - case 'array': // Array - case 'blob': // Binary Blob - case 'oblob': // Binary Blob Object - case 'stream': // Binary Stream - case 'ostream': // Binary Stream Object - case 'storage': // Binary Storage - case 'ostorage': // Binary Storage Object - case 'vstream': // Binary Versioned Stream - case 'clsid': // Class ID - case 'cf': // Clipboard Data - return $propertyValue; } return $propertyValue; @@ -530,48 +518,61 @@ class DocumentProperties */ public static function convertPropertyType($propertyType) { - switch ($propertyType) { - case 'i1': // 1-Byte Signed Integer - case 'i2': // 2-Byte Signed Integer - case 'i4': // 4-Byte Signed Integer - case 'i8': // 8-Byte Signed Integer - case 'int': // Integer - case 'ui1': // 1-Byte Unsigned Integer - case 'ui2': // 2-Byte Unsigned Integer - case 'ui4': // 4-Byte Unsigned Integer - case 'ui8': // 8-Byte Unsigned Integer - case 'uint': // Unsigned Integer - return self::PROPERTY_TYPE_INTEGER; - case 'r4': // 4-Byte Real Number - case 'r8': // 8-Byte Real Number - case 'decimal': // Decimal - return self::PROPERTY_TYPE_FLOAT; - case 'empty': // Empty - case 'null': // Null - case 'lpstr': // LPSTR - case 'lpwstr': // LPWSTR - case 'bstr': // Basic String - return self::PROPERTY_TYPE_STRING; - case 'date': // Date and Time - case 'filetime': // File Time - return self::PROPERTY_TYPE_DATE; - case 'bool': // Boolean - return self::PROPERTY_TYPE_BOOLEAN; - case 'cy': // Currency - case 'error': // Error Status Code - case 'vector': // Vector - case 'array': // Array - case 'blob': // Binary Blob - case 'oblob': // Binary Blob Object - case 'stream': // Binary Stream - case 'ostream': // Binary Stream Object - case 'storage': // Binary Storage - case 'ostorage': // Binary Storage Object - case 'vstream': // Binary Versioned Stream - case 'clsid': // Class ID - case 'cf': // Clipboard Data - return self::PROPERTY_TYPE_UNKNOWN; + $typeGroups = array( + self::PROPERTY_TYPE_INTEGER => array('i1', 'i2', 'i4', 'i8', 'int', 'ui1', 'ui2', 'ui4', 'ui8', 'uint'), + self::PROPERTY_TYPE_FLOAT => array('r4', 'r8', 'decimal'), + self::PROPERTY_TYPE_STRING => array('empty', 'null', 'lpstr', 'lpwstr', 'bstr'), + self::PROPERTY_TYPE_DATE => array('date', 'filetime'), + self::PROPERTY_TYPE_BOOLEAN => array('bool'), + ); + foreach ($typeGroups as $groupId => $groupMembers) { + if (in_array($propertyType, $groupMembers)) { + return $groupId; + } } + return self::PROPERTY_TYPE_UNKNOWN; } + + /** + * Set default for null and empty value + * + * @param mixed $value + * @param mixed $default + * @return mixed + */ + private function setValue($value, $default) + { + if ($value === null || $value == '') { + $value = $default; + } + + return $value; + } + + /** + * Get conversion model depending on property type + * + * @param string $propertyType + * @return string + */ + private static function getConversion($propertyType) + { + $conversions = array( + 'empty' => array('empty'), + 'null' => array('null'), + 'int' => array('i1', 'i2', 'i4', 'i8', 'int'), + 'uint' => array('ui1', 'ui2', 'ui4', 'ui8', 'uint'), + 'float' => array('r4', 'r8', 'decimal'), + 'bool' => array('bool'), + 'date' => array('date', 'filetime'), + ); + foreach ($conversions as $conversion => $types) { + if (in_array($propertyType, $types)) { + return $conversion; + } + } + + return 'string'; + } } diff --git a/src/PhpWord/Metadata/Protection.php b/src/PhpWord/Metadata/Protection.php new file mode 100644 index 00000000..3556ce8c --- /dev/null +++ b/src/PhpWord/Metadata/Protection.php @@ -0,0 +1,69 @@ +setEditing($editing); + } + + /** + * Get editing protection + * + * @return string + */ + public function getEditing() + { + return $this->editing; + } + + /** + * Set editing protection + * + * @param string $editing + * @return self + */ + public function setEditing($editing = null) + { + $this->editing = $editing; + + return $this; + } +} diff --git a/src/PhpWord/PhpWord.php b/src/PhpWord/PhpWord.php index 73ba1cc3..84e5ebc7 100644 --- a/src/PhpWord/PhpWord.php +++ b/src/PhpWord/PhpWord.php @@ -1,106 +1,208 @@ documentProperties = new DocumentProperties(); - $this->defaultFontName = self::DEFAULT_FONT_NAME; - $this->defaultFontSize = self::DEFAULT_FONT_SIZE; + // Collection + $collections = array('Bookmarks', 'Titles', 'Footnotes', 'Endnotes', 'Charts'); + foreach ($collections as $collection) { + $class = 'PhpOffice\\PhpWord\\Collection\\' . $collection; + $this->collections[$collection] = new $class(); + } + + // Metadata + $metadata = array('DocInfo', 'Protection', 'Compatibility'); + foreach ($metadata as $meta) { + $class = 'PhpOffice\\PhpWord\\Metadata\\' . $meta; + $this->metadata[$meta] = new $class(); + } + } + + /** + * Dynamic function call to reduce static dependency + * + * @param mixed $function + * @param mixed $args + * @throws \BadMethodCallException + * @return mixed + * @since 0.12.0 + */ + public function __call($function, $args) + { + $function = strtolower($function); + + $getCollection = array(); + $addCollection = array(); + $addStyle = array(); + + $collections = array('Bookmark', 'Title', 'Footnote', 'Endnote', 'Chart'); + foreach ($collections as $collection) { + $getCollection[] = strtolower("get{$collection}s"); + $addCollection[] = strtolower("add{$collection}"); + } + + $styles = array('Paragraph', 'Font', 'Table', 'Numbering', 'Link', 'Title'); + foreach ($styles as $style) { + $addStyle[] = strtolower("add{$style}style"); + } + + // Run get collection method + if (in_array($function, $getCollection)) { + $key = ucfirst(str_replace('get', '', $function)); + + return $this->collections[$key]; + } + + // Run add collection item method + if (in_array($function, $addCollection)) { + $key = ucfirst(str_replace('add', '', $function) . 's'); + + /** @var \PhpOffice\PhpWord\Collection\AbstractCollection $collectionObject */ + $collectionObject = $this->collections[$key]; + + return $collectionObject->addItem(array_key_exists(0, $args) ? $args[0] : null); + } + + // Run add style method + if (in_array($function, $addStyle)) { + return forward_static_call_array(array('PhpOffice\\PhpWord\\Style', $function), $args); + } + + // Exception + throw new \BadMethodCallException("Method $function is not defined."); } /** * Get document properties object * - * @return DocumentProperties + * @return \PhpOffice\PhpWord\Metadata\DocInfo */ - public function getDocumentProperties() + public function getDocInfo() { - return $this->documentProperties; + return $this->metadata['DocInfo']; } /** - * Set document properties object + * Get protection * - * @param DocumentProperties $documentProperties - * @return self + * @return \PhpOffice\PhpWord\Metadata\Protection + * @since 0.12.0 */ - public function setDocumentProperties(DocumentProperties $documentProperties) + public function getProtection() { - $this->documentProperties = $documentProperties; + return $this->metadata['Protection']; + } - return $this; + /** + * Get compatibility + * + * @return \PhpOffice\PhpWord\Metadata\Compatibility + * @since 0.12.0 + */ + public function getCompatibility() + { + return $this->metadata['Compatibility']; + } + + /** + * Get all sections + * + * @return \PhpOffice\PhpWord\Element\Section[] + */ + public function getSections() + { + return $this->sections; } /** * Create new section * - * @param array $settings - * @return Section + * @param array $style + * @return \PhpOffice\PhpWord\Element\Section */ - public function addSection($settings = null) + public function addSection($style = null) { - $section = new Section(count($this->sections) + 1, $settings); + $section = new Section(count($this->sections) + 1, $style); + $section->setPhpWord($this); $this->sections[] = $section; return $section; @@ -113,17 +215,18 @@ class PhpWord */ public function getDefaultFontName() { - return $this->defaultFontName; + return Settings::getDefaultFontName(); } /** - * Set default font name + * Set default font name. * * @param string $fontName + * @return void */ public function setDefaultFontName($fontName) { - $this->defaultFontName = $fontName; + Settings::setDefaultFontName($fontName); } /** @@ -133,106 +236,29 @@ class PhpWord */ public function getDefaultFontSize() { - return $this->defaultFontSize; + return Settings::getDefaultFontSize(); } /** - * Set default font size + * Set default font size. * * @param int $fontSize + * @return void */ public function setDefaultFontSize($fontSize) { - $this->defaultFontSize = $fontSize; + Settings::setDefaultFontSize($fontSize); } /** * Set default paragraph style definition to styles.xml * * @param array $styles Paragraph style definition + * @return \PhpOffice\PhpWord\Style\Paragraph */ public function setDefaultParagraphStyle($styles) { - Style::setDefaultParagraphStyle($styles); - } - - /** - * Adds a paragraph style definition to styles.xml - * - * @param string $styleName - * @param array $styles - */ - public function addParagraphStyle($styleName, $styles) - { - Style::addParagraphStyle($styleName, $styles); - } - - /** - * Adds a font style definition to styles.xml - * - * @param string $styleName - * @param mixed $styleFont - * @param mixed $styleParagraph - */ - public function addFontStyle($styleName, $styleFont, $styleParagraph = null) - { - Style::addFontStyle($styleName, $styleFont, $styleParagraph); - } - - /** - * Adds a table style definition to styles.xml - * - * @param string $styleName - * @param mixed $styleTable - * @param mixed $styleFirstRow - */ - public function addTableStyle($styleName, $styleTable, $styleFirstRow = null) - { - Style::addTableStyle($styleName, $styleTable, $styleFirstRow); - } - - /** - * Adds a heading style definition to styles.xml - * - * @param int $titleCount - * @param mixed $styleFont - * @param mixed $styleParagraph - */ - public function addTitleStyle($titleCount, $styleFont, $styleParagraph = null) - { - Style::addTitleStyle($titleCount, $styleFont, $styleParagraph); - } - - /** - * Adds a hyperlink style to styles.xml - * - * @param string $styleName - * @param mixed $styles - */ - public function addLinkStyle($styleName, $styles) - { - Style::addLinkStyle($styleName, $styles); - } - - /** - * Adds a numbering style - * - * @param string $styleName - * @param mixed $styles - */ - public function addNumberingStyle($styleName, $styles) - { - Style::addNumberingStyle($styleName, $styles); - } - - /** - * Get all sections - * - * @return Section[] - */ - public function getSections() - { - return $this->sections; + return Style::setDefaultParagraphStyle($styles); } /** @@ -240,7 +266,7 @@ class PhpWord * * @param string $filename Fully qualified filename. * @return Template - * @throws Exception + * @throws \PhpOffice\PhpWord\Exception\Exception */ public function loadTemplate($filename) { @@ -251,11 +277,48 @@ class PhpWord } } + /** + * Save to file or download + * + * All exceptions should already been handled by the writers + * + * @param string $filename + * @param string $format + * @param bool $download + * @return bool + */ + public function save($filename, $format = 'Word2007', $download = false) + { + $mime = array( + 'Word2007' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'ODText' => 'application/vnd.oasis.opendocument.text', + 'RTF' => 'application/rtf', + 'HTML' => 'text/html', + 'PDF' => 'application/pdf', + ); + + $writer = IOFactory::createWriter($this, $format); + + if ($download === true) { + header("Content-Description: File Transfer"); + header('Content-Disposition: attachment; filename="' . $filename . '"'); + header('Content-Type: ' . $mime[$format]); + header('Content-Transfer-Encoding: binary'); + header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); + header('Expires: 0'); + $filename = 'php://output'; // Change filename to force download + } + + $writer->save($filename); + + return true; + } + /** * Create new section * * @param array $settings - * @return Section + * @return \PhpOffice\PhpWord\Element\Section * @deprecated 0.10.0 * @codeCoverageIgnore */ @@ -263,4 +326,31 @@ class PhpWord { return $this->addSection($settings); } + + /** + * Get document properties object + * + * @return \PhpOffice\PhpWord\Metadata\DocInfo + * @deprecated 0.12.0 + * @codeCoverageIgnore + */ + public function getDocumentProperties() + { + return $this->getDocInfo(); + } + + /** + * Set document properties object + * + * @param \PhpOffice\PhpWord\Metadata\DocInfo $documentProperties + * @return self + * @deprecated 0.12.0 + * @codeCoverageIgnore + */ + public function setDocumentProperties($documentProperties) + { + $this->metadata['Document'] = $documentProperties; + + return $this; + } } diff --git a/src/PhpWord/Reader/AbstractReader.php b/src/PhpWord/Reader/AbstractReader.php index 99db598c..c08914e5 100644 --- a/src/PhpWord/Reader/AbstractReader.php +++ b/src/PhpWord/Reader/AbstractReader.php @@ -1,10 +1,18 @@ readDataOnly; return true; @@ -46,47 +55,47 @@ abstract class AbstractReader implements ReaderInterface /** * Set read data only * - * @param bool $pValue + * @param bool $value * @return self */ - public function setReadDataOnly($pValue = true) + public function setReadDataOnly($value = true) { - $this->readDataOnly = $pValue; + $this->readDataOnly = $value; return $this; } /** * Open file for reading * - * @param string $pFilename + * @param string $filename * @return resource - * @throws Exception + * @throws \PhpOffice\PhpWord\Exception\Exception */ - protected function openFile($pFilename) + protected function openFile($filename) { // Check if file exists - if (!file_exists($pFilename) || !is_readable($pFilename)) { - throw new Exception("Could not open " . $pFilename . " for reading! File does not exist."); + if (!file_exists($filename) || !is_readable($filename)) { + throw new Exception("Could not open " . $filename . " for reading! File does not exist."); } // Open file - $this->fileHandle = fopen($pFilename, 'r'); + $this->fileHandle = fopen($filename, 'r'); if ($this->fileHandle === false) { - throw new Exception("Could not open file " . $pFilename . " for reading."); + throw new Exception("Could not open file " . $filename . " for reading."); } } /** * Can the current ReaderInterface read the file? * - * @param string $pFilename + * @param string $filename * @return bool */ - public function canRead($pFilename) + public function canRead($filename) { // Check if file exists try { - $this->openFile($pFilename); + $this->openFile($filename); } catch (Exception $e) { return false; } @@ -96,4 +105,15 @@ abstract class AbstractReader implements ReaderInterface return true; } + + /** + * Read data only? + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getReadDataOnly() + { + return $this->isReadDataOnly(); + } } diff --git a/src/PhpWord/Reader/HTML.php b/src/PhpWord/Reader/HTML.php new file mode 100644 index 00000000..a6582a3f --- /dev/null +++ b/src/PhpWord/Reader/HTML.php @@ -0,0 +1,50 @@ +canRead($docFile)) { + $section = $phpWord->addSection(); + HTMLParser::addHtml($section, file_get_contents($docFile), true); + } else { + throw new \Exception("Cannot read {$docFile}."); + } + + return $phpWord; + } +} diff --git a/src/PhpWord/Reader/ODText.php b/src/PhpWord/Reader/ODText.php new file mode 100644 index 00000000..d992f7fd --- /dev/null +++ b/src/PhpWord/Reader/ODText.php @@ -0,0 +1,95 @@ +readRelationships($docFile); + + $readerParts = array( + 'content.xml' => 'Content', + 'meta.xml' => 'Meta', + ); + + foreach ($readerParts as $xmlFile => $partName) { + $this->readPart($phpWord, $relationships, $partName, $docFile, $xmlFile); + } + + return $phpWord; + } + + /** + * Read document part. + * + * @param \PhpOffice\PhpWord\PhpWord $phpWord + * @param array $relationships + * @param string $partName + * @param string $docFile + * @param string $xmlFile + * @return void + */ + private function readPart(PhpWord $phpWord, $relationships, $partName, $docFile, $xmlFile) + { + $partClass = "PhpOffice\\PhpWord\\Reader\\ODText\\{$partName}"; + if (class_exists($partClass)) { + /** @var \PhpOffice\PhpWord\Reader\ODText\AbstractPart $part Type hint */ + $part = new $partClass($docFile, $xmlFile); + $part->setRels($relationships); + $part->read($phpWord); + } + } + + /** + * Read all relationship files + * + * @param string $docFile + * @return array + */ + private function readRelationships($docFile) + { + $rels = array(); + $xmlFile = 'META-INF/manifest.xml'; + $xmlReader = new XMLReader(); + $xmlReader->getDomFromZip($docFile, $xmlFile); + $nodes = $xmlReader->getElements('manifest:file-entry'); + foreach ($nodes as $node) { + $type = $xmlReader->getAttribute('manifest:media-type', $node); + $target = $xmlReader->getAttribute('manifest:full-path', $node); + $rels[] = array('type' => $type, 'target' => $target); + } + + return $rels; + } +} diff --git a/src/PhpWord/Reader/ODText/AbstractPart.php b/src/PhpWord/Reader/ODText/AbstractPart.php new file mode 100644 index 00000000..95f70084 --- /dev/null +++ b/src/PhpWord/Reader/ODText/AbstractPart.php @@ -0,0 +1,30 @@ +getDomFromZip($this->docFile, $this->xmlFile); + + $nodes = $xmlReader->getElements('office:body/office:text/*'); + if ($nodes->length > 0) { + $section = $phpWord->addSection(); + foreach ($nodes as $node) { + // $styleName = $xmlReader->getAttribute('text:style-name', $node); + switch ($node->nodeName) { + + case 'text:h': // Heading + $depth = $xmlReader->getAttribute('text:outline-level', $node); + $section->addTitle($node->nodeValue, $depth); + break; + + case 'text:p': // Paragraph + $section->addText($node->nodeValue); + break; + + case 'text:list': // List + $listItems = $xmlReader->getElements('text:list-item/text:p', $node); + foreach ($listItems as $listItem) { + // $listStyleName = $xmlReader->getAttribute('text:style-name', $listItem); + $section->addListItem($listItem->nodeValue, 0); + } + break; + } + } + } + } +} diff --git a/src/PhpWord/Reader/ODText/Meta.php b/src/PhpWord/Reader/ODText/Meta.php new file mode 100644 index 00000000..d08ce3a6 --- /dev/null +++ b/src/PhpWord/Reader/ODText/Meta.php @@ -0,0 +1,80 @@ +getDomFromZip($this->docFile, $this->xmlFile); + $docProps = $phpWord->getDocInfo(); + + $metaNode = $xmlReader->getElement('office:meta'); + + // Standard properties + $properties = array( + 'title' => 'dc:title', + 'subject' => 'dc:subject', + 'description' => 'dc:description', + 'keywords' => 'meta:keyword', + 'creator' => 'meta:initial-creator', + 'lastModifiedBy' => 'dc:creator', + // 'created' => 'meta:creation-date', + // 'modified' => 'dc:date', + ); + foreach ($properties as $property => $path) { + $method = "set{$property}"; + $propertyNode = $xmlReader->getElement($path, $metaNode); + if ($propertyNode !== null && method_exists($docProps, $method)) { + $docProps->$method($propertyNode->nodeValue); + } + } + + // Custom properties + $propertyNodes = $xmlReader->getElements('meta:user-defined', $metaNode); + foreach ($propertyNodes as $propertyNode) { + $property = $xmlReader->getAttribute('meta:name', $propertyNode); + + // Set category, company, and manager property + if (in_array($property, array('Category', 'Company', 'Manager'))) { + $method = "set{$property}"; + $docProps->$method($propertyNode->nodeValue); + + // Set other custom properties + } else { + $docProps->setCustomProperty($property, $propertyNode->nodeValue); + } + } + } +} diff --git a/src/PhpWord/Reader/RTF.php b/src/PhpWord/Reader/RTF.php new file mode 100644 index 00000000..9d5d813b --- /dev/null +++ b/src/PhpWord/Reader/RTF.php @@ -0,0 +1,51 @@ +canRead($docFile)) { + $doc = new Document(); + $doc->rtf = file_get_contents($docFile); + $doc->read($phpWord); + } else { + throw new \Exception("Cannot read {$docFile}."); + } + + return $phpWord; + } +} diff --git a/src/PhpWord/Reader/RTF/Document.php b/src/PhpWord/Reader/RTF/Document.php new file mode 100644 index 00000000..fcd9703f --- /dev/null +++ b/src/PhpWord/Reader/RTF/Document.php @@ -0,0 +1,414 @@ + 'markOpening', // { + 125 => 'markClosing', // } + 92 => 'markBackslash', // \ + 10 => 'markNewline', // LF + 13 => 'markNewline' // CR + ); + + $this->phpWord = $phpWord; + $this->section = $phpWord->addSection(); + $this->textrun = $this->section->addTextRun(); + $this->length = strlen($this->rtf); + + $this->flags['paragraph'] = true; // Set paragraph flag from the beginning + + // Walk each characters + while ($this->offset < $this->length) { + $char = $this->rtf[$this->offset]; + $ascii = ord($char); + + if (array_key_exists($ascii, $markers)) { // Marker found: {, }, \, LF, or CR + $markerFunction = $markers[$ascii]; + $this->$markerFunction(); + } else { + if ($this->isControl === false) { // Non control word: Push character + $this->pushText($char); + } else { + if (preg_match("/^[a-zA-Z0-9-]?$/", $char)) { // No delimiter: Buffer control + $this->control .= $char; + $this->isFirst = false; + } else { // Delimiter found: Parse buffered control + if ($this->isFirst) { + $this->isFirst = false; + } else { + if ($char == ' ') { // Discard space as a control word delimiter + $this->flushControl(true); + } + } + } + } + } + $this->offset++; + } + $this->flushText(); + } + + /** + * Mark opening braket `{` character. + * + * @return void + */ + private function markOpening() + { + $this->flush(true); + array_push($this->groups, $this->flags); + } + + /** + * Mark closing braket `}` character. + * + * @return void + */ + private function markClosing() + { + $this->flush(true); + $this->flags = array_pop($this->groups); + } + + /** + * Mark backslash `\` character. + * + * @return void + */ + private function markBackslash() + { + if ($this->isFirst) { + $this->setControl(false); + $this->text .= '\\'; + } else { + $this->flush(); + $this->setControl(true); + $this->control = ''; + } + } + + /** + * Mark newline character: Flush control word because it's not possible to span multiline. + * + * @return void + */ + private function markNewline() + { + if ($this->isControl) { + $this->flushControl(true); + } + } + + /** + * Flush control word or text. + * + * @param bool $isControl + * @return void + */ + private function flush($isControl = false) + { + if ($this->isControl) { + $this->flushControl($isControl); + } else { + $this->flushText(); + } + } + + /** + * Flush control word. + * + * @param bool $isControl + * @return void + */ + private function flushControl($isControl = false) + { + if (preg_match("/^([A-Za-z]+)(-?[0-9]*) ?$/", $this->control, $match) === 1) { + list(, $control, $parameter) = $match; + $this->parseControl($control, $parameter); + } + + if ($isControl === true) { + $this->setControl(false); + } + } + + /** + * Flush text in queue. + * + * @return void + */ + private function flushText() + { + if ($this->text != '') { + if (isset($this->flags['property'])) { // Set property + $this->flags['value'] = $this->text; + } else { // Set text + if ($this->flags['paragraph'] === true) { + $this->flags['paragraph'] = false; + $this->flags['text'] = $this->text; + } + } + + // Add text if it's not flagged as skipped + if (!isset($this->flags['skipped'])) { + $this->readText(); + } + + $this->text = ''; + } + } + + /** + * Reset control word and first char state. + * + * @param bool $value + * @return void + */ + private function setControl($value) + { + $this->isControl = $value; + $this->isFirst = $value; + } + + /** + * Push text into queue. + * + * @param string $char + * @return void + */ + private function pushText($char) + { + if ($char == '<') { + $this->text .= "<"; + } elseif ($char == '>') { + $this->text .= ">"; + } else { + $this->text .= $char; + } + } + + /** + * Parse control. + * + * @param string $control + * @param string $parameter + * @return void + */ + private function parseControl($control, $parameter) + { + $controls = array( + 'par' => array(self::PARA, 'paragraph', true), + 'b' => array(self::STYL, 'font', 'bold', true), + 'i' => array(self::STYL, 'font', 'italic', true), + 'u' => array(self::STYL, 'font', 'underline', true), + 'strike' => array(self::STYL, 'font', 'strikethrough',true), + 'fs' => array(self::STYL, 'font', 'size', $parameter), + 'qc' => array(self::STYL, 'paragraph', 'align', 'center'), + 'sa' => array(self::STYL, 'paragraph', 'spaceAfter', $parameter), + 'fonttbl' => array(self::SKIP, 'fonttbl', null), + 'colortbl' => array(self::SKIP, 'colortbl', null), + 'info' => array(self::SKIP, 'info', null), + 'generator' => array(self::SKIP, 'generator', null), + 'title' => array(self::SKIP, 'title', null), + 'subject' => array(self::SKIP, 'subject', null), + 'category' => array(self::SKIP, 'category', null), + 'keywords' => array(self::SKIP, 'keywords', null), + 'comment' => array(self::SKIP, 'comment', null), + 'shppict' => array(self::SKIP, 'pic', null), + 'fldinst' => array(self::SKIP, 'link', null), + ); + + if (array_key_exists($control, $controls)) { + list($function) = $controls[$control]; + if (method_exists($this, $function)) { + $directives = $controls[$control]; + array_shift($directives); // remove the function variable; we won't need it + $this->$function($directives); + } + } + } + + /** + * Read paragraph. + * + * @param array $directives + * @return void + */ + private function readParagraph($directives) + { + list($property, $value) = $directives; + $this->textrun = $this->section->addTextRun(); + $this->flags[$property] = $value; + } + + /** + * Read style. + * + * @param array $directives + * @return void + */ + private function readStyle($directives) + { + list($style, $property, $value) = $directives; + $this->flags['styles'][$style][$property] = $value; + } + + /** + * Read skip. + * + * @param array $directives + * @return void + */ + private function readSkip($directives) + { + list($property) = $directives; + $this->flags['property'] = $property; + $this->flags['skipped'] = true; + } + + /** + * Read text. + * + * @return void + */ + private function readText() + { + $text = $this->textrun->addText($this->text); + if (isset($this->flags['styles']['font'])) { + $text->getFontStyle()->setStyleByArray($this->flags['styles']['font']); + } + } +} diff --git a/src/PhpWord/Reader/ReaderInterface.php b/src/PhpWord/Reader/ReaderInterface.php index 2829d4ab..361c4137 100644 --- a/src/PhpWord/Reader/ReaderInterface.php +++ b/src/PhpWord/Reader/ReaderInterface.php @@ -1,31 +1,41 @@ array(), 'document' => array()); - /** * Loads PhpWord from file * - * @param string $filename - * @return PhpWord + * @param string $docFile + * @return \PhpOffice\PhpWord\PhpWord */ - public function load($filename) + public function load($docFile) { - $this->phpWord = new PhpWord(); + $phpWord = new PhpWord(); + $relationships = $this->readRelationships($docFile); - $this->readRelationships($filename); + $steps = array( + array('stepPart' => 'document', 'stepItems' => array( + 'styles' => 'Styles', + 'numbering' => 'Numbering', + )), + array('stepPart' => 'main', 'stepItems' => array( + 'officeDocument' => 'Document', + 'core-properties' => 'DocPropsCore', + 'extended-properties' => 'DocPropsApp', + 'custom-properties' => 'DocPropsCustom', + )), + array('stepPart' => 'document', 'stepItems' => array( + 'endnotes' => 'Endnotes', + 'footnotes' => 'Footnotes', + )), + ); - - // Read styles and numbering first - foreach ($this->rels['document'] as $rId => $rel) { - switch ($rel['type']) { - case 'styles': - $this->readStyles($filename, $rel['target']); - break; - case 'numbering': - $this->readNumbering($filename, $rel['target']); - break; + foreach ($steps as $step) { + $stepPart = $step['stepPart']; + $stepItems = $step['stepItems']; + foreach ($relationships[$stepPart] as $relItem) { + $relType = $relItem['type']; + if (array_key_exists($relType, $stepItems)) { + $partName = $stepItems[$relType]; + $xmlFile = $relItem['target']; + $this->readPart($phpWord, $relationships, $partName, $docFile, $xmlFile); + } } } - // Read main relationship - foreach ($this->rels['main'] as $rId => $rel) { - switch ($rel['type']) { + return $phpWord; + } - case 'officeDocument': - $this->readDocument($filename, $rel['target']); - break; - - case 'core-properties': - $mapping = array( - 'dc:creator' => 'setCreator', - 'dc:title' => 'setTitle', - 'dc:description' => 'setDescription', - 'dc:subject' => 'setSubject', - 'cp:keywords' => 'setKeywords', - 'cp:category' => 'setCategory', - 'cp:lastModifiedBy' => 'setLastModifiedBy', - 'dcterms:created' => 'setCreated', - 'dcterms:modified' => 'setModified', - ); - $callbacks = array('dcterms:created' => 'strtotime', 'dcterms:modified' => 'strtotime'); - $this->readDocProps($filename, $rel['target'], $mapping, $callbacks); - break; - - case 'extended-properties': - $mapping = array('Company' => 'setCompany', 'Manager' => 'setManager'); - $this->readDocProps($filename, $rel['target'], $mapping); - break; - - case 'custom-properties': - $this->readDocPropsCustom($filename, $rel['target']); - break; - } + /** + * Read document part. + * + * @param \PhpOffice\PhpWord\PhpWord $phpWord + * @param array $relationships + * @param string $partName + * @param string $docFile + * @param string $xmlFile + * @return void + */ + private function readPart(PhpWord $phpWord, $relationships, $partName, $docFile, $xmlFile) + { + $partClass = "PhpOffice\\PhpWord\\Reader\\Word2007\\{$partName}"; + if (class_exists($partClass)) { + /** @var \PhpOffice\PhpWord\Reader\Word2007\AbstractPart $part Type hint */ + $part = new $partClass($docFile, $xmlFile); + $part->setRels($relationships); + $part->read($phpWord); } - // Read footnotes and endnotes - foreach ($this->rels['document'] as $rId => $rel) { - switch ($rel['type']) { - case 'footnotes': - case 'endnotes': - $this->readNotes($filename, $rel['target'], $rel['type']); - break; - } - } - - return $this->phpWord; } /** * Read all relationship files * - * @param string $filename + * @param string $docFile + * @return array */ - private function readRelationships($filename) + private function readRelationships($docFile) { + $relationships = array(); + // _rels/.rels - $this->rels['main'] = $this->getRels($filename, '_rels/.rels'); + $relationships['main'] = $this->getRels($docFile, '_rels/.rels'); // word/_rels/*.xml.rels $wordRelsPath = 'word/_rels/'; - $zipClass = Settings::getZipClass(); - $zip = new $zipClass(); - if ($zip->open($filename) === true) { + $zip = new ZipArchive(); + if ($zip->open($docFile) === true) { for ($i = 0; $i < $zip->numFiles; $i++) { $xmlFile = $zip->getNameIndex($i); if ((substr($xmlFile, 0, strlen($wordRelsPath))) == $wordRelsPath && (substr($xmlFile, -1)) != '/') { $docPart = str_replace('.xml.rels', '', str_replace($wordRelsPath, '', $xmlFile)); - $this->rels[$docPart] = $this->getRels($filename, $xmlFile, 'word/'); + $relationships[$docPart] = $this->getRels($docFile, $xmlFile, 'word/'); } } $zip->close(); } - } - /** - * Read core and extended document properties - * - * @param string $filename - * @param string $xmlFile - * @param array $mapping - * @param array $callbacks - */ - private function readDocProps($filename, $xmlFile, $mapping, $callbacks = array()) - { - $xmlReader = new XMLReader(); - $xmlReader->getDomFromZip($filename, $xmlFile); - $docProps = $this->phpWord->getDocumentProperties(); - - $nodes = $xmlReader->getElements('*'); - if ($nodes->length > 0) { - foreach ($nodes as $node) { - if (!array_key_exists($node->nodeName, $mapping)) { - continue; - } - $method = $mapping[$node->nodeName]; - $value = $node->nodeValue == '' ? null : $node->nodeValue; - if (array_key_exists($node->nodeName, $callbacks)) { - $value = $callbacks[$node->nodeName]($value); - } - if (method_exists($docProps, $method)) { - $docProps->$method($value); - } - } - } - } - - /** - * Read custom document properties - * - * @param string $filename - * @param string $xmlFile - */ - private function readDocPropsCustom($filename, $xmlFile) - { - $xmlReader = new XMLReader(); - $xmlReader->getDomFromZip($filename, $xmlFile); - $docProps = $this->phpWord->getDocumentProperties(); - - $nodes = $xmlReader->getElements('*'); - if ($nodes->length > 0) { - foreach ($nodes as $node) { - $propertyName = $xmlReader->getAttribute('name', $node); - $attributeNode = $xmlReader->getElement('*', $node); - $attributeType = $attributeNode->nodeName; - $attributeValue = $attributeNode->nodeValue; - $attributeValue = DocumentProperties::convertProperty($attributeValue, $attributeType); - $attributeType = DocumentProperties::convertPropertyType($attributeType); - $docProps->setCustomProperty($propertyName, $attributeValue, $attributeType); - } - } - } - - /** - * Read document.xml - * - * @param string $filename - * @param string $xmlFile - */ - private function readDocument($filename, $xmlFile) - { - $xmlReader = new XMLReader(); - $xmlReader->getDomFromZip($filename, $xmlFile); - - $nodes = $xmlReader->getElements('w:body/*'); - if ($nodes->length > 0) { - $section = $this->phpWord->addSection(); - foreach ($nodes as $node) { - switch ($node->nodeName) { - - case 'w:p': // Paragraph - if ($xmlReader->getAttribute('w:type', $node, 'w:r/w:br') == 'page') { - $section->addPageBreak(); // PageBreak - } else { - $this->readParagraph($xmlReader, $node, $section, 'document'); - } - // Section properties - if ($xmlReader->elementExists('w:pPr/w:sectPr', $node)) { - $settingsNode = $xmlReader->getElement('w:pPr/w:sectPr', $node); - if (!is_null($settingsNode)) { - $settings = $this->readSectionStyle($xmlReader, $settingsNode); - $section->setSettings($settings); - if (!is_null($settings)) { - $this->readHeaderFooter($filename, $settings, $section); - } - } - $section = $this->phpWord->addSection(); - } - break; - - case 'w:tbl': // Table - $this->readTable($xmlReader, $node, $section, 'document'); - break; - - case 'w:sectPr': // Last section - $settings = $this->readSectionStyle($xmlReader, $node); - $section->setSettings($settings); - if (!is_null($settings)) { - $this->readHeaderFooter($filename, $settings, $section); - } - break; - } - } - } - } - - /** - * Read styles.xml - * - * @param string $filename - * @param string $xmlFile - */ - private function readStyles($filename, $xmlFile) - { - $xmlReader = new XMLReader(); - $xmlReader->getDomFromZip($filename, $xmlFile); - - $nodes = $xmlReader->getElements('w:style'); - if ($nodes->length > 0) { - foreach ($nodes as $node) { - $type = $xmlReader->getAttribute('w:type', $node); - $name = $xmlReader->getAttribute('w:styleId', $node); - if (is_null($name)) { - $name = $xmlReader->getAttribute('w:val', $node, 'w:name'); - } - // $default = ($xmlReader->getAttribute('w:default', $node) == 1); - switch ($type) { - - case 'paragraph': - $pStyle = $this->readParagraphStyle($xmlReader, $node); - $fStyle = $this->readFontStyle($xmlReader, $node); - if (empty($fStyle)) { - if (is_array($pStyle)) { - $this->phpWord->addParagraphStyle($name, $pStyle); - } - } else { - $this->phpWord->addFontStyle($name, $fStyle, $pStyle); - } - break; - - case 'character': - $fStyle = $this->readFontStyle($xmlReader, $node); - if (!empty($fStyle)) { - $this->phpWord->addFontStyle($name, $fStyle); - } - break; - - case 'table': - $tStyle = $this->readTableStyle($xmlReader, $node); - if (!empty($tStyle)) { - $this->phpWord->addTableStyle($name, $tStyle); - } - break; - } - } - } - } - - /** - * Read numbering.xml - * - * @param string $filename - * @param string $xmlFile - */ - private function readNumbering($filename, $xmlFile) - { - $abstracts = array(); - $numberings = array(); - $xmlReader = new XMLReader(); - $xmlReader->getDomFromZip($filename, $xmlFile); - - // Abstract numbering definition - $nodes = $xmlReader->getElements('w:abstractNum'); - if ($nodes->length > 0) { - foreach ($nodes as $node) { - $abstractId = $xmlReader->getAttribute('w:abstractNumId', $node); - $abstracts[$abstractId] = array('levels' => array()); - $abstract = &$abstracts[$abstractId]; - $subnodes = $xmlReader->getElements('*', $node); - foreach ($subnodes as $subnode) { - switch ($subnode->nodeName) { - case 'w:multiLevelType': - $abstract['type'] = $xmlReader->getAttribute('w:val', $subnode); - break; - case 'w:lvl': - $levelId = $xmlReader->getAttribute('w:ilvl', $subnode); - $abstract['levels'][$levelId] = $this->readNumberingLevel($xmlReader, $subnode, $levelId); - break; - } - } - } - } - - // Numbering instance definition - $nodes = $xmlReader->getElements('w:num'); - if ($nodes->length > 0) { - foreach ($nodes as $node) { - $numId = $xmlReader->getAttribute('w:numId', $node); - $abstractId = $xmlReader->getAttribute('w:val', $node, 'w:abstractNumId'); - $numberings[$numId] = $abstracts[$abstractId]; - $numberings[$numId]['numId'] = $numId; - $subnodes = $xmlReader->getElements('w:lvlOverride/w:lvl', $node); - foreach ($subnodes as $subnode) { - $levelId = $xmlReader->getAttribute('w:ilvl', $subnode); - $overrides = $this->readNumberingLevel($xmlReader, $subnode, $levelId); - foreach ($overrides as $key => $value) { - $numberings[$numId]['levels'][$levelId][$key] = $value; - } - } - } - } - - // Push to Style collection - foreach ($numberings as $numId => $numbering) { - $this->phpWord->addNumberingStyle("PHPWordList{$numId}", $numbering); - } - } - - /** - * Read numbering level definition from w:abstractNum and w:num - * - * @param integer $levelId - * @return array - */ - private function readNumberingLevel(XMLReader $xmlReader, \DOMElement $subnode, $levelId) - { - $level = array(); - - $level['level'] = $levelId; - $level['start'] = $xmlReader->getAttribute('w:val', $subnode, 'w:start'); - $level['format'] = $xmlReader->getAttribute('w:val', $subnode, 'w:numFmt'); - $level['restart'] = $xmlReader->getAttribute('w:val', $subnode, 'w:lvlRestart'); - $level['suffix'] = $xmlReader->getAttribute('w:val', $subnode, 'w:suff'); - $level['text'] = $xmlReader->getAttribute('w:val', $subnode, 'w:lvlText'); - $level['align'] = $xmlReader->getAttribute('w:val', $subnode, 'w:lvlJc'); - $level['tab'] = $xmlReader->getAttribute('w:pos', $subnode, 'w:pPr/w:tabs/w:tab'); - $level['left'] = $xmlReader->getAttribute('w:left', $subnode, 'w:pPr/w:ind'); - $level['hanging'] = $xmlReader->getAttribute('w:hanging', $subnode, 'w:pPr/w:ind'); - $level['font'] = $xmlReader->getAttribute('w:ascii', $subnode, 'w:rPr/w:rFonts'); - $level['hint'] = $xmlReader->getAttribute('w:hint', $subnode, 'w:rPr/w:rFonts'); - - foreach ($level as $key => $value) { - if (is_null($value)) { - unset($level[$key]); - } - } - - return $level; - } - - /** - * Read header footer - * - * @param string $filename - * @param array $settings - * @param Section $section - */ - private function readHeaderFooter($filename, $settings, &$section) - { - if (is_array($settings) && array_key_exists('hf', $settings)) { - foreach ($settings['hf'] as $rId => $hfSetting) { - if (array_key_exists($rId, $this->rels['document'])) { - list($hfType, $xmlFile, $docPart) = array_values($this->rels['document'][$rId]); - $method = "add{$hfType}"; - $hfObject = $section->$method($hfSetting['type']); - - // Read header/footer content - $xmlReader = new XMLReader(); - $xmlReader->getDomFromZip($filename, $xmlFile); - $nodes = $xmlReader->getElements('*'); - if ($nodes->length > 0) { - foreach ($nodes as $node) { - switch ($node->nodeName) { - - case 'w:p': // Paragraph - $this->readParagraph($xmlReader, $node, $hfObject, $docPart); - break; - - case 'w:tbl': // Table - $this->readTable($xmlReader, $node, $hfObject, $docPart); - break; - } - } - } - } - } - } - } - - /** - * Read (footnotes|endnotes).xml - * - * @param string $filename - * @param string $xmlFile - * @param string $notesType - */ - private function readNotes($filename, $xmlFile, $notesType = 'footnotes') - { - $notesType = ($notesType == 'endnotes') ? 'endnotes' : 'footnotes'; - $collectionClass = 'PhpOffice\\PhpWord\\' . ucfirst($notesType); - $collection = $collectionClass::getElements(); - - $xmlReader = new XMLReader(); - $xmlReader->getDomFromZip($filename, $xmlFile); - $nodes = $xmlReader->getElements('*'); - if ($nodes->length > 0) { - foreach ($nodes as $node) { - $id = $xmlReader->getAttribute('w:id', $node); - $type = $xmlReader->getAttribute('w:type', $node); - - // Avoid w:type "separator" and "continuationSeparator" - // Only look for or without w:type attribute - if (is_null($type) && array_key_exists($id, $collection)) { - $element = $collection[$id]; - $pNodes = $xmlReader->getElements('w:p/*', $node); - foreach ($pNodes as $pNode) { - $this->readRun($xmlReader, $pNode, $element, $notesType); - } - $collectionClass::setElement($id, $element); - } - } - } - } - - /** - * Read w:p - * - * @param mixed $parent - * @param string $docPart - * - * @todo Get font style for preserve text - */ - private function readParagraph(XMLReader $xmlReader, \DOMElement $domNode, &$parent, $docPart) - { - // Paragraph style - $pStyle = null; - if ($xmlReader->elementExists('w:pPr', $domNode)) { - $pStyle = $this->readParagraphStyle($xmlReader, $domNode); - } - - // PreserveText - if ($xmlReader->elementExists('w:r/w:instrText', $domNode)) { - $ignoreText = false; - $textContent = ''; - $fStyle = $this->readFontStyle($xmlReader, $domNode); - $nodes = $xmlReader->getElements('w:r', $domNode); - foreach ($nodes as $node) { - $instrText = $xmlReader->getValue('w:instrText', $node); - if ($xmlReader->elementExists('w:fldChar', $node)) { - $fldCharType = $xmlReader->getAttribute('w:fldCharType', $node, 'w:fldChar'); - if ($fldCharType == 'begin') { - $ignoreText = true; - } elseif ($fldCharType == 'end') { - $ignoreText = false; - } - } - if (!is_null($instrText)) { - $textContent .= '{' . $instrText . '}'; - } else { - if ($ignoreText === false) { - $textContent .= $xmlReader->getValue('w:t', $node); - } - } - } - $parent->addPreserveText($textContent, $fStyle, $pStyle); - - // List item - } elseif ($xmlReader->elementExists('w:pPr/w:numPr', $domNode)) { - $textContent = ''; - $numId = $xmlReader->getAttribute('w:val', $domNode, 'w:pPr/w:numPr/w:numId'); - $levelId = $xmlReader->getAttribute('w:val', $domNode, 'w:pPr/w:numPr/w:ilvl'); - $nodes = $xmlReader->getElements('w:r', $domNode); - foreach ($nodes as $node) { - $textContent .= $xmlReader->getValue('w:t', $node); - } - $parent->addListItem($textContent, $levelId, null, "PHPWordList{$numId}", $pStyle); - - // Text and TextRun - } else { - $runCount = $xmlReader->countElements('w:r', $domNode); - $linkCount = $xmlReader->countElements('w:hyperlink', $domNode); - $runLinkCount = $runCount + $linkCount; - if ($runLinkCount == 0) { - $parent->addTextBreak(null, $pStyle); - } else { - if ($runLinkCount > 1) { - $textrun = $parent->addTextRun($pStyle); - $textParent = &$textrun; - } else { - $textParent = &$parent; - } - $nodes = $xmlReader->getElements('*', $domNode); - foreach ($nodes as $node) { - $this->readRun($xmlReader, $node, $textParent, $docPart, $pStyle); - } - } - } - } - - /** - * Read w:r - * - * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader - * @param \DOMElement $domNode - * @param mixed $parent - * @param string $docPart - * @param mixed $pStyle - * - * @todo Footnote paragraph style - */ - private function readRun(XMLReader $xmlReader, \DOMElement $domNode, &$parent, $docPart, $pStyle = null) - { - if (!in_array($domNode->nodeName, array('w:r', 'w:hyperlink'))) { - return; - } - $fStyle = $this->readFontStyle($xmlReader, $domNode); - - // Link - if ($domNode->nodeName == 'w:hyperlink') { - $rId = $xmlReader->getAttribute('r:id', $domNode); - $textContent = $xmlReader->getValue('w:r/w:t', $domNode); - $target = $this->getMediaTarget($docPart, $rId); - if (!is_null($target)) { - $parent->addLink($target, $textContent, $fStyle, $pStyle); - } - } else { - // Footnote - if ($xmlReader->elementExists('w:footnoteReference', $domNode)) { - $parent->addFootnote(); - - // Endnote - } elseif ($xmlReader->elementExists('w:endnoteReference', $domNode)) { - $parent->addEndnote(); - - // Image - } elseif ($xmlReader->elementExists('w:pict', $domNode)) { - $rId = $xmlReader->getAttribute('r:id', $domNode, 'w:pict/v:shape/v:imagedata'); - $target = $this->getMediaTarget($docPart, $rId); - if (!is_null($target)) { - $textContent = ""; - $parent->addText($textContent, $fStyle, $pStyle); - } - - // Object - } elseif ($xmlReader->elementExists('w:object', $domNode)) { - $rId = $xmlReader->getAttribute('r:id', $domNode, 'w:object/o:OLEObject'); - // $rIdIcon = $xmlReader->getAttribute('r:id', $domNode, 'w:object/v:shape/v:imagedata'); - $target = $this->getMediaTarget($docPart, $rId); - if (!is_null($target)) { - $textContent = ""; - $parent->addText($textContent, $fStyle, $pStyle); - } - - // TextRun - } else { - $textContent = $xmlReader->getValue('w:t', $domNode); - $parent->addText($textContent, $fStyle, $pStyle); - } - } - } - - /** - * Read w:tbl - * - * @param mixed $parent - * @param string $docPart - */ - private function readTable(XMLReader $xmlReader, \DOMElement $domNode, &$parent, $docPart) - { - // Table style - $tblStyle = null; - if ($xmlReader->elementExists('w:tblPr', $domNode)) { - $tblStyle = $this->readTableStyle($xmlReader, $domNode); - } - - $table = $parent->addTable($tblStyle); - $tblNodes = $xmlReader->getElements('*', $domNode); - foreach ($tblNodes as $tblNode) { - if ($tblNode->nodeName == 'w:tblGrid') { // Column - // @todo Do something with table columns - - } elseif ($tblNode->nodeName == 'w:tr') { // Row - $rowHeight = $xmlReader->getAttribute('w:val', $tblNode, 'w:trPr/w:trHeight'); - $rowHRule = $xmlReader->getAttribute('w:hRule', $tblNode, 'w:trPr/w:trHeight'); - $rowHRule = $rowHRule == 'exact' ? true : false; - $rowStyle = array( - 'tblHeader' => $xmlReader->elementExists('w:trPr/w:tblHeader', $tblNode), - 'cantSplit' => $xmlReader->elementExists('w:trPr/w:cantSplit', $tblNode), - 'exactHeight' => $rowHRule, - ); - - $row = $table->addRow($rowHeight, $rowStyle); - $rowNodes = $xmlReader->getElements('*', $tblNode); - foreach ($rowNodes as $rowNode) { - if ($rowNode->nodeName == 'w:trPr') { // Row style - // @todo Do something with row style - - } elseif ($rowNode->nodeName == 'w:tc') { // Cell - $cellWidth = $xmlReader->getAttribute('w:w', $rowNode, 'w:tcPr/w:tcW'); - $cellStyle = null; - $cellStyleNode = $xmlReader->getElement('w:tcPr', $rowNode); - if (!is_null($cellStyleNode)) { - $cellStyle = $this->readCellStyle($xmlReader, $cellStyleNode); - } - - $cell = $row->addCell($cellWidth, $cellStyle); - $cellNodes = $xmlReader->getElements('*', $rowNode); - foreach ($cellNodes as $cellNode) { - if ($cellNode->nodeName == 'w:p') { // Paragraph - $this->readParagraph($xmlReader, $cellNode, $cell, $docPart); - } - } - } - } - } - } - } - - /** - * Read w:sectPr - * - * @return array|null - */ - private function readSectionStyle(XMLReader $xmlReader, \DOMElement $domNode) - { - $ret = null; - $mapping = array( - 'w:type' => 'breakType', 'w:pgSz' => 'pageSize', - 'w:pgMar' => 'pageMargin', 'w:cols' => 'columns', - 'w:headerReference' => 'header', 'w:footerReference' => 'footer', - ); - $nodes = $xmlReader->getElements('*', $domNode); - foreach ($nodes as $node) { - if (!array_key_exists($node->nodeName, $mapping)) { - continue; - } - $property = $mapping[$node->nodeName]; - switch ($node->nodeName) { - - case 'w:type': - $ret['breakType'] = $xmlReader->getAttribute('w:val', $node); - break; - - case 'w:pgSz': - $ret['pageSizeW'] = $xmlReader->getAttribute('w:w', $node); - $ret['pageSizeH'] = $xmlReader->getAttribute('w:h', $node); - $ret['orientation'] = $xmlReader->getAttribute('w:orient', $node); - break; - - case 'w:pgMar': - $ret['topMargin'] = $xmlReader->getAttribute('w:top', $node); - $ret['leftMargin'] = $xmlReader->getAttribute('w:left', $node); - $ret['bottomMargin'] = $xmlReader->getAttribute('w:bottom', $node); - $ret['rightMargin'] = $xmlReader->getAttribute('w:right', $node); - $ret['headerHeight'] = $xmlReader->getAttribute('w:header', $node); - $ret['footerHeight'] = $xmlReader->getAttribute('w:footer', $node); - $ret['gutter'] = $xmlReader->getAttribute('w:gutter', $node); - break; - - case 'w:cols': - $ret['colsNum'] = $xmlReader->getAttribute('w:num', $node); - $ret['colsSpace'] = $xmlReader->getAttribute('w:space', $node); - break; - - case 'w:headerReference': - case 'w:footerReference': - $id = $xmlReader->getAttribute('r:id', $node); - $ret['hf'][$id] = array( - 'method' => $property, - 'type' => $xmlReader->getAttribute('w:type', $node), - ); - break; - } - } - - return $ret; - } - - /** - * Read w:pPr - * - * @return string|array|null - */ - private function readParagraphStyle(XMLReader $xmlReader, \DOMElement $domNode) - { - $style = null; - if ($xmlReader->elementExists('w:pPr', $domNode)) { - if ($xmlReader->elementExists('w:pPr/w:pStyle', $domNode)) { - $style = $xmlReader->getAttribute('w:val', $domNode, 'w:pPr/w:pStyle'); - } else { - $style = array(); - $mapping = array( - 'w:ind' => 'indent', 'w:spacing' => 'spacing', - 'w:jc' => 'align', 'w:basedOn' => 'basedOn', 'w:next' => 'next', - 'w:widowControl' => 'widowControl', 'w:keepNext' => 'keepNext', - 'w:keepLines' => 'keepLines', 'w:pageBreakBefore' => 'pageBreakBefore', - ); - - $nodes = $xmlReader->getElements('w:pPr/*', $domNode); - foreach ($nodes as $node) { - if (!array_key_exists($node->nodeName, $mapping)) { - continue; - } - $property = $mapping[$node->nodeName]; - switch ($node->nodeName) { - - case 'w:ind': - $style['indent'] = $xmlReader->getAttribute('w:left', $node); - $style['hanging'] = $xmlReader->getAttribute('w:hanging', $node); - break; - - case 'w:spacing': - $style['spaceAfter'] = $xmlReader->getAttribute('w:after', $node); - $style['spaceBefore'] = $xmlReader->getAttribute('w:before', $node); - // Commented. Need to adjust the number when return value is null - // $style['spacing'] = $xmlReader->getAttribute('w:line', $node); - break; - - case 'w:keepNext': - case 'w:keepLines': - case 'w:pageBreakBefore': - $style[$property] = true; - break; - - case 'w:widowControl': - $style[$property] = false; - break; - - case 'w:jc': - case 'w:basedOn': - case 'w:next': - $style[$property] = $xmlReader->getAttribute('w:val', $node); - break; - } - } - } - } - - return $style; - } - - /** - * Read w:rPr - * - * @return string|array|null - */ - private function readFontStyle(XMLReader $xmlReader, \DOMElement $domNode) - { - $style = null; - // Hyperlink has an extra w:r child - if ($domNode->nodeName == 'w:hyperlink') { - $domNode = $xmlReader->getElement('w:r', $domNode); - } - if (is_null($domNode)) { - return $style; - } - if ($xmlReader->elementExists('w:rPr', $domNode)) { - if ($xmlReader->elementExists('w:rPr/w:rStyle', $domNode)) { - $style = $xmlReader->getAttribute('w:val', $domNode, 'w:rPr/w:rStyle'); - } else { - $style = array(); - $mapping = array( - 'w:b' => 'bold', 'w:i' => 'italic', 'w:color' => 'color', - 'w:strike' => 'strikethrough', 'w:u' => 'underline', - 'w:highlight' => 'fgColor', 'w:sz' => 'size', - 'w:rFonts' => 'name', 'w:vertAlign' => 'superScript', - ); - - $nodes = $xmlReader->getElements('w:rPr/*', $domNode); - foreach ($nodes as $node) { - if (!array_key_exists($node->nodeName, $mapping)) { - continue; - } - $property = $mapping[$node->nodeName]; - switch ($node->nodeName) { - - case 'w:rFonts': - $style['name'] = $xmlReader->getAttribute('w:ascii', $node); - $style['hint'] = $xmlReader->getAttribute('w:hint', $node); - break; - - case 'w:b': - case 'w:i': - case 'w:strike': - $style[$property] = true; - break; - - case 'w:u': - case 'w:highlight': - case 'w:color': - $style[$property] = $xmlReader->getAttribute('w:val', $node); - break; - - case 'w:sz': - $style[$property] = $xmlReader->getAttribute('w:val', $node) / 2; - break; - - case 'w:vertAlign': - $style[$property] = $xmlReader->getAttribute('w:val', $node); - if ($style[$property] == 'superscript') { - $style['superScript'] = true; - } else { - $style['superScript'] = false; - $style['subScript'] = true; - } - break; - } - } - } - } - - return $style; - } - /** - * Read w:tblPr - * - * @return string|array|null - * @todo Capture w:tblStylePr w:type="firstRow" - */ - private function readTableStyle(XMLReader $xmlReader, \DOMElement $domNode) - { - $style = null; - $margins = array('top', 'left', 'bottom', 'right'); - $borders = $margins + array('insideH', 'insideV'); - - if ($xmlReader->elementExists('w:tblPr', $domNode)) { - if ($xmlReader->elementExists('w:tblPr/w:tblStyle', $domNode)) { - $style = $xmlReader->getAttribute('w:val', $domNode, 'w:tblPr/w:tblStyle'); - } else { - $style = array(); - $mapping = array( - 'w:tblCellMar' => 'cellMargin', - 'w:tblBorders' => 'border', - ); - - $nodes = $xmlReader->getElements('w:tblPr/*', $domNode); - foreach ($nodes as $node) { - if (!array_key_exists($node->nodeName, $mapping)) { - continue; - } - // $property = $mapping[$node->nodeName]; - switch ($node->nodeName) { - - case 'w:tblCellMar': - foreach ($margins as $side) { - $ucfSide = ucfirst($side); - $style["cellMargin$ucfSide"] = $xmlReader->getAttribute('w:w', $node, "w:$side"); - } - break; - - case 'w:tblBorders': - foreach ($borders as $side) { - $ucfSide = ucfirst($side); - $style["border{$ucfSide}Size"] = $xmlReader->getAttribute('w:sz', $node, "w:$side"); - $style["border{$ucfSide}Color"] = $xmlReader->getAttribute('w:color', $node, "w:$side"); - } - break; - } - } - } - } - - return $style; - } - - /** - * Read w:tcPr - * - * @return array|null - */ - private function readCellStyle(XMLReader $xmlReader, \DOMElement $domNode) - { - $style = null; - $mapping = array( - 'w:shd' => 'bgColor', - 'w:vAlign' => 'valign', 'w:textDirection' => 'textDirection', - 'w:gridSpan' => 'gridSpan', 'w:vMerge' => 'vMerge', - ); - $nodes = $xmlReader->getElements('*', $domNode); - foreach ($nodes as $node) { - if (!array_key_exists($node->nodeName, $mapping)) { - continue; - } - $property = $mapping[$node->nodeName]; - switch ($node->nodeName) { - case 'w:shd': - $style['bgColor'] = $xmlReader->getAttribute('w:fill', $node); - break; - - default: - $style[$property] = $xmlReader->getAttribute('w:val', $node); - break; - } - } - - return $style; + return $relationships; } /** * Get relationship array * - * @param string $filename + * @param string $docFile * @param string $xmlFile * @param string $targetPrefix * @return array */ - private function getRels($filename, $xmlFile, $targetPrefix = '') + private function getRels($docFile, $xmlFile, $targetPrefix = '') { $metaPrefix = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/'; $officePrefix = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/'; @@ -956,7 +142,7 @@ class Word2007 extends AbstractReader implements ReaderInterface $rels = array(); $xmlReader = new XMLReader(); - $xmlReader->getDomFromZip($filename, $xmlFile); + $xmlReader->getDomFromZip($docFile, $xmlFile); $nodes = $xmlReader->getElements('*'); foreach ($nodes as $node) { $rId = $xmlReader->getAttribute('Id', $node); @@ -980,23 +166,4 @@ class Word2007 extends AbstractReader implements ReaderInterface return $rels; } - - /** - * Returns the target of image, object, or link as stored in ::readMainRels - * - * @param string $docPart - * @param string $rId - * @return string|null - */ - private function getMediaTarget($docPart, $rId) - { - $target = null; - if (array_key_exists($docPart, $this->rels)) { - if (array_key_exists($rId, $this->rels[$docPart])) { - $target = $this->rels[$docPart][$rId]['target']; - } - } - - return $target; - } } diff --git a/src/PhpWord/Reader/Word2007/AbstractPart.php b/src/PhpWord/Reader/Word2007/AbstractPart.php new file mode 100644 index 00000000..7d3e0f66 --- /dev/null +++ b/src/PhpWord/Reader/Word2007/AbstractPart.php @@ -0,0 +1,516 @@ +docFile = $docFile; + $this->xmlFile = $xmlFile; + } + + /** + * Set relationships. + * + * @param array $value + * @return void + */ + public function setRels($value) + { + $this->rels = $value; + } + + /** + * Read w:p. + * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $domNode + * @param mixed $parent + * @param string $docPart + * @return void + * + * @todo Get font style for preserve text + */ + protected function readParagraph(XMLReader $xmlReader, \DOMElement $domNode, $parent, $docPart = 'document') + { + // Paragraph style + $paragraphStyle = null; + $headingMatches = array(); + if ($xmlReader->elementExists('w:pPr', $domNode)) { + $paragraphStyle = $this->readParagraphStyle($xmlReader, $domNode); + if (is_array($paragraphStyle) && array_key_exists('styleName', $paragraphStyle)) { + preg_match('/Heading(\d)/', $paragraphStyle['styleName'], $headingMatches); + } + } + + // PreserveText + if ($xmlReader->elementExists('w:r/w:instrText', $domNode)) { + $ignoreText = false; + $textContent = ''; + $fontStyle = $this->readFontStyle($xmlReader, $domNode); + $nodes = $xmlReader->getElements('w:r', $domNode); + foreach ($nodes as $node) { + $instrText = $xmlReader->getValue('w:instrText', $node); + if ($xmlReader->elementExists('w:fldChar', $node)) { + $fldCharType = $xmlReader->getAttribute('w:fldCharType', $node, 'w:fldChar'); + if ($fldCharType == 'begin') { + $ignoreText = true; + } elseif ($fldCharType == 'end') { + $ignoreText = false; + } + } + if (!is_null($instrText)) { + $textContent .= '{' . $instrText . '}'; + } else { + if ($ignoreText === false) { + $textContent .= $xmlReader->getValue('w:t', $node); + } + } + } + $parent->addPreserveText($textContent, $fontStyle, $paragraphStyle); + + // List item + } elseif ($xmlReader->elementExists('w:pPr/w:numPr', $domNode)) { + $textContent = ''; + $numId = $xmlReader->getAttribute('w:val', $domNode, 'w:pPr/w:numPr/w:numId'); + $levelId = $xmlReader->getAttribute('w:val', $domNode, 'w:pPr/w:numPr/w:ilvl'); + $nodes = $xmlReader->getElements('w:r', $domNode); + foreach ($nodes as $node) { + $textContent .= $xmlReader->getValue('w:t', $node); + } + $parent->addListItem($textContent, $levelId, null, "PHPWordList{$numId}", $paragraphStyle); + + // Heading + } elseif (!empty($headingMatches)) { + $textContent = ''; + $nodes = $xmlReader->getElements('w:r', $domNode); + foreach ($nodes as $node) { + $textContent .= $xmlReader->getValue('w:t', $node); + } + $parent->addTitle($textContent, $headingMatches[1]); + + // Text and TextRun + } else { + $runCount = $xmlReader->countElements('w:r', $domNode); + $linkCount = $xmlReader->countElements('w:hyperlink', $domNode); + $runLinkCount = $runCount + $linkCount; + if ($runLinkCount == 0) { + $parent->addTextBreak(null, $paragraphStyle); + } else { + $nodes = $xmlReader->getElements('*', $domNode); + foreach ($nodes as $node) { + $this->readRun( + $xmlReader, + $node, + ($runLinkCount > 1) ? $parent->addTextRun($paragraphStyle) : $parent, + $docPart, + $paragraphStyle + ); + } + } + } + } + + /** + * Read w:r. + * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $domNode + * @param mixed $parent + * @param string $docPart + * @param mixed $paragraphStyle + * @return void + * + * @todo Footnote paragraph style + */ + protected function readRun(XMLReader $xmlReader, \DOMElement $domNode, $parent, $docPart, $paragraphStyle = null) + { + if (!in_array($domNode->nodeName, array('w:r', 'w:hyperlink'))) { + return; + } + $fontStyle = $this->readFontStyle($xmlReader, $domNode); + + // Link + if ($domNode->nodeName == 'w:hyperlink') { + $rId = $xmlReader->getAttribute('r:id', $domNode); + $textContent = $xmlReader->getValue('w:r/w:t', $domNode); + $target = $this->getMediaTarget($docPart, $rId); + if (!is_null($target)) { + $parent->addLink($target, $textContent, $fontStyle, $paragraphStyle); + } + } else { + // Footnote + if ($xmlReader->elementExists('w:footnoteReference', $domNode)) { + $parent->addFootnote(); + + // Endnote + } elseif ($xmlReader->elementExists('w:endnoteReference', $domNode)) { + $parent->addEndnote(); + + // Image + } elseif ($xmlReader->elementExists('w:pict', $domNode)) { + $rId = $xmlReader->getAttribute('r:id', $domNode, 'w:pict/v:shape/v:imagedata'); + $target = $this->getMediaTarget($docPart, $rId); + if (!is_null($target)) { + $imageSource = "zip://{$this->docFile}#{$target}"; + $parent->addImage($imageSource); + } + + // Object + } elseif ($xmlReader->elementExists('w:object', $domNode)) { + $rId = $xmlReader->getAttribute('r:id', $domNode, 'w:object/o:OLEObject'); + // $rIdIcon = $xmlReader->getAttribute('r:id', $domNode, 'w:object/v:shape/v:imagedata'); + $target = $this->getMediaTarget($docPart, $rId); + if (!is_null($target)) { + $textContent = ""; + $parent->addText($textContent, $fontStyle, $paragraphStyle); + } + + // TextRun + } else { + $textContent = $xmlReader->getValue('w:t', $domNode); + $parent->addText($textContent, $fontStyle, $paragraphStyle); + } + } + } + + /** + * Read w:tbl. + * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $domNode + * @param mixed $parent + * @param string $docPart + * @return void + */ + protected function readTable(XMLReader $xmlReader, \DOMElement $domNode, $parent, $docPart = 'document') + { + // Table style + $tblStyle = null; + if ($xmlReader->elementExists('w:tblPr', $domNode)) { + $tblStyle = $this->readTableStyle($xmlReader, $domNode); + } + + /** @var \PhpOffice\PhpWord\Element\Table $table Type hint */ + $table = $parent->addTable($tblStyle); + $tblNodes = $xmlReader->getElements('*', $domNode); + foreach ($tblNodes as $tblNode) { + if ($tblNode->nodeName == 'w:tblGrid') { // Column + // @todo Do something with table columns + + } elseif ($tblNode->nodeName == 'w:tr') { // Row + $rowHeight = $xmlReader->getAttribute('w:val', $tblNode, 'w:trPr/w:trHeight'); + $rowHRule = $xmlReader->getAttribute('w:hRule', $tblNode, 'w:trPr/w:trHeight'); + $rowHRule = $rowHRule == 'exact' ? true : false; + $rowStyle = array( + 'tblHeader' => $xmlReader->elementExists('w:trPr/w:tblHeader', $tblNode), + 'cantSplit' => $xmlReader->elementExists('w:trPr/w:cantSplit', $tblNode), + 'exactHeight' => $rowHRule, + ); + + $row = $table->addRow($rowHeight, $rowStyle); + $rowNodes = $xmlReader->getElements('*', $tblNode); + foreach ($rowNodes as $rowNode) { + if ($rowNode->nodeName == 'w:trPr') { // Row style + // @todo Do something with row style + + } elseif ($rowNode->nodeName == 'w:tc') { // Cell + $cellWidth = $xmlReader->getAttribute('w:w', $rowNode, 'w:tcPr/w:tcW'); + $cellStyle = null; + $cellStyleNode = $xmlReader->getElement('w:tcPr', $rowNode); + if (!is_null($cellStyleNode)) { + $cellStyle = $this->readCellStyle($xmlReader, $cellStyleNode); + } + + $cell = $row->addCell($cellWidth, $cellStyle); + $cellNodes = $xmlReader->getElements('*', $rowNode); + foreach ($cellNodes as $cellNode) { + if ($cellNode->nodeName == 'w:p') { // Paragraph + $this->readParagraph($xmlReader, $cellNode, $cell, $docPart); + } + } + } + } + } + } + } + + /** + * Read w:pPr. + * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $domNode + * @return array|null + */ + protected function readParagraphStyle(XMLReader $xmlReader, \DOMElement $domNode) + { + if (!$xmlReader->elementExists('w:pPr', $domNode)) { + return null; + } + + $styleNode = $xmlReader->getElement('w:pPr', $domNode); + $styleDefs = array( + 'styleName' => array(self::READ_VALUE, 'w:pStyle'), + 'align' => array(self::READ_VALUE, 'w:jc'), + 'basedOn' => array(self::READ_VALUE, 'w:basedOn'), + 'next' => array(self::READ_VALUE, 'w:next'), + 'indent' => array(self::READ_VALUE, 'w:ind', 'w:left'), + 'hanging' => array(self::READ_VALUE, 'w:ind', 'w:hanging'), + 'spaceAfter' => array(self::READ_VALUE, 'w:spacing', 'w:after'), + 'spaceBefore' => array(self::READ_VALUE, 'w:spacing', 'w:before'), + 'widowControl' => array(self::READ_FALSE, 'w:widowControl'), + 'keepNext' => array(self::READ_TRUE, 'w:keepNext'), + 'keepLines' => array(self::READ_TRUE, 'w:keepLines'), + 'pageBreakBefore' => array(self::READ_TRUE, 'w:pageBreakBefore'), + ); + + return $this->readStyleDefs($xmlReader, $styleNode, $styleDefs); + } + + /** + * Read w:rPr + * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $domNode + * @return array|null + */ + protected function readFontStyle(XMLReader $xmlReader, \DOMElement $domNode) + { + if (is_null($domNode)) { + return null; + } + // Hyperlink has an extra w:r child + if ($domNode->nodeName == 'w:hyperlink') { + $domNode = $xmlReader->getElement('w:r', $domNode); + } + if (!$xmlReader->elementExists('w:rPr', $domNode)) { + return null; + } + + $styleNode = $xmlReader->getElement('w:rPr', $domNode); + $styleDefs = array( + 'styleName' => array(self::READ_VALUE, 'w:rStyle'), + 'name' => array(self::READ_VALUE, 'w:rFonts', 'w:ascii'), + 'hint' => array(self::READ_VALUE, 'w:rFonts', 'w:hint'), + 'size' => array(self::READ_SIZE, 'w:sz'), + 'color' => array(self::READ_VALUE, 'w:color'), + 'underline' => array(self::READ_VALUE, 'w:u'), + 'bold' => array(self::READ_TRUE, 'w:b'), + 'italic' => array(self::READ_TRUE, 'w:i'), + 'strikethrough' => array(self::READ_TRUE, 'w:strike'), + 'doubleStrikethrough' => array(self::READ_TRUE, 'w:dstrike'), + 'smallCaps' => array(self::READ_TRUE, 'w:smallCaps'), + 'allCaps' => array(self::READ_TRUE, 'w:caps'), + 'superScript' => array(self::READ_EQUAL, 'w:vertAlign', 'w:val', 'superscript'), + 'subScript' => array(self::READ_EQUAL, 'w:vertAlign', 'w:val', 'subscript'), + 'fgColor' => array(self::READ_VALUE, 'w:highlight'), + 'rtl' => array(self::READ_TRUE, 'w:rtl'), + ); + + return $this->readStyleDefs($xmlReader, $styleNode, $styleDefs); + } + + /** + * Read w:tblPr + * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $domNode + * @return string|array|null + * @todo Capture w:tblStylePr w:type="firstRow" + */ + protected function readTableStyle(XMLReader $xmlReader, \DOMElement $domNode) + { + $style = null; + $margins = array('top', 'left', 'bottom', 'right'); + $borders = $margins + array('insideH', 'insideV'); + + if ($xmlReader->elementExists('w:tblPr', $domNode)) { + if ($xmlReader->elementExists('w:tblPr/w:tblStyle', $domNode)) { + $style = $xmlReader->getAttribute('w:val', $domNode, 'w:tblPr/w:tblStyle'); + } else { + $styleNode = $xmlReader->getElement('w:tblPr', $domNode); + $styleDefs = array(); + // $styleDefs['styleName'] = array(self::READ_VALUE, 'w:tblStyle'); + foreach ($margins as $side) { + $ucfSide = ucfirst($side); + $styleDefs["cellMargin$ucfSide"] = array(self::READ_VALUE, "w:tblCellMar/w:$side", 'w:w'); + } + foreach ($borders as $side) { + $ucfSide = ucfirst($side); + $styleDefs["border{$ucfSide}Size"] = array(self::READ_VALUE, "w:tblBorders/w:$side", 'w:sz'); + $styleDefs["border{$ucfSide}Color"] = array(self::READ_VALUE, "w:tblBorders/w:$side", 'w:color'); + } + $style = $this->readStyleDefs($xmlReader, $styleNode, $styleDefs); + } + } + + return $style; + } + + /** + * Read w:tcPr + * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $domNode + * @return array + */ + private function readCellStyle(XMLReader $xmlReader, \DOMElement $domNode) + { + $styleDefs = array( + 'valign' => array(self::READ_VALUE, 'w:vAlign'), + 'textDirection' => array(self::READ_VALUE, 'w:textDirection'), + 'gridSpan' => array(self::READ_VALUE, 'w:gridSpan'), + 'vMerge' => array(self::READ_VALUE, 'w:vMerge'), + 'bgColor' => array(self::READ_VALUE, 'w:shd/w:fill'), + ); + + return $this->readStyleDefs($xmlReader, $domNode, $styleDefs); + } + + /** + * Read style definition + * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $parentNode + * @param array $styleDefs + * @ignoreScrutinizerPatch + * @return array + */ + protected function readStyleDefs(XMLReader $xmlReader, \DOMElement $parentNode = null, $styleDefs = array()) + { + $styles = array(); + + foreach ($styleDefs as $styleProp => $styleVal) { + @list($method, $element, $attribute, $expected) = $styleVal; + + if ($xmlReader->elementExists($element, $parentNode)) { + $node = $xmlReader->getElement($element, $parentNode); + + // Use w:val as default if no attribute assigned + $attribute = ($attribute === null) ? 'w:val' : $attribute; + $attributeValue = $xmlReader->getAttribute($attribute, $node); + + $styleValue = $this->readStyleDef($method, $attributeValue, $expected); + if ($styleValue !== null) { + $styles[$styleProp] = $styleValue; + } + } + } + + return $styles; + } + + /** + * Return style definition based on conversion method + * + * @param string $method + * @ignoreScrutinizerPatch + * @param mixed $attributeValue + * @param mixed $expected + * @return mixed + */ + private function readStyleDef($method, $attributeValue, $expected) + { + $style = $attributeValue; + + if ($method == self::READ_SIZE) { + $style = $attributeValue / 2; + } elseif ($method == self::READ_TRUE) { + $style = true; + } elseif ($method == self::READ_FALSE) { + $style = false; + } elseif ($method == self::READ_EQUAL) { + $style = $attributeValue == $expected; + } + + return $style; + } + + /** + * Returns the target of image, object, or link as stored in ::readMainRels + * + * @param string $docPart + * @param string $rId + * @return string|null + */ + private function getMediaTarget($docPart, $rId) + { + $target = null; + if (array_key_exists($docPart, $this->rels)) { + if (array_key_exists($rId, $this->rels[$docPart])) { + $target = $this->rels[$docPart][$rId]['target']; + } + } + + return $target; + } +} diff --git a/src/PhpWord/Reader/Word2007/DocPropsApp.php b/src/PhpWord/Reader/Word2007/DocPropsApp.php new file mode 100644 index 00000000..ddbe474f --- /dev/null +++ b/src/PhpWord/Reader/Word2007/DocPropsApp.php @@ -0,0 +1,40 @@ + 'setCompany', 'Manager' => 'setManager'); + + /** + * Callback functions + * + * @var array + */ + protected $callbacks = array(); +} diff --git a/src/PhpWord/Reader/Word2007/DocPropsCore.php b/src/PhpWord/Reader/Word2007/DocPropsCore.php new file mode 100644 index 00000000..4c48ecbc --- /dev/null +++ b/src/PhpWord/Reader/Word2007/DocPropsCore.php @@ -0,0 +1,84 @@ + 'setCreator', + 'dc:title' => 'setTitle', + 'dc:description' => 'setDescription', + 'dc:subject' => 'setSubject', + 'cp:keywords' => 'setKeywords', + 'cp:category' => 'setCategory', + 'cp:lastModifiedBy' => 'setLastModifiedBy', + 'dcterms:created' => 'setCreated', + 'dcterms:modified' => 'setModified', + ); + + /** + * Callback functions + * + * @var array + */ + protected $callbacks = array('dcterms:created' => 'strtotime', 'dcterms:modified' => 'strtotime'); + + /** + * Read core/extended document properties. + * + * @param \PhpOffice\PhpWord\PhpWord $phpWord + * @return void + */ + public function read(PhpWord $phpWord) + { + $xmlReader = new XMLReader(); + $xmlReader->getDomFromZip($this->docFile, $this->xmlFile); + + $docProps = $phpWord->getDocInfo(); + + $nodes = $xmlReader->getElements('*'); + if ($nodes->length > 0) { + foreach ($nodes as $node) { + if (!array_key_exists($node->nodeName, $this->mapping)) { + continue; + } + $method = $this->mapping[$node->nodeName]; + $value = $node->nodeValue == '' ? null : $node->nodeValue; + if (array_key_exists($node->nodeName, $this->callbacks)) { + $value = $this->callbacks[$node->nodeName]($value); + } + if (method_exists($docProps, $method)) { + $docProps->$method($value); + } + } + } + } +} diff --git a/src/PhpWord/Reader/Word2007/DocPropsCustom.php b/src/PhpWord/Reader/Word2007/DocPropsCustom.php new file mode 100644 index 00000000..eb725b2e --- /dev/null +++ b/src/PhpWord/Reader/Word2007/DocPropsCustom.php @@ -0,0 +1,56 @@ +getDomFromZip($this->docFile, $this->xmlFile); + $docProps = $phpWord->getDocInfo(); + + $nodes = $xmlReader->getElements('*'); + if ($nodes->length > 0) { + foreach ($nodes as $node) { + $propertyName = $xmlReader->getAttribute('name', $node); + $attributeNode = $xmlReader->getElement('*', $node); + $attributeType = $attributeNode->nodeName; + $attributeValue = $attributeNode->nodeValue; + $attributeValue = DocInfo::convertProperty($attributeValue, $attributeType); + $attributeType = DocInfo::convertPropertyType($attributeType); + $docProps->setCustomProperty($propertyName, $attributeValue, $attributeType); + } + } + } +} diff --git a/src/PhpWord/Reader/Word2007/Document.php b/src/PhpWord/Reader/Word2007/Document.php new file mode 100644 index 00000000..3ced6763 --- /dev/null +++ b/src/PhpWord/Reader/Word2007/Document.php @@ -0,0 +1,186 @@ +phpWord = $phpWord; + $xmlReader = new XMLReader(); + $xmlReader->getDomFromZip($this->docFile, $this->xmlFile); + $readMethods = array('w:p' => 'readWPNode', 'w:tbl' => 'readTable', 'w:sectPr' => 'readWSectPrNode'); + + $nodes = $xmlReader->getElements('w:body/*'); + if ($nodes->length > 0) { + $section = $this->phpWord->addSection(); + foreach ($nodes as $node) { + if (array_key_exists($node->nodeName, $readMethods)) { + $readMethod = $readMethods[$node->nodeName]; + $this->$readMethod($xmlReader, $node, $section); + } + } + } + } + + /** + * Read header footer. + * + * @param array $settings + * @param \PhpOffice\PhpWord\Element\Section &$section + * @return void + */ + private function readHeaderFooter($settings, Section &$section) + { + $readMethods = array('w:p' => 'readParagraph', 'w:tbl' => 'readTable'); + + if (is_array($settings) && array_key_exists('hf', $settings)) { + foreach ($settings['hf'] as $rId => $hfSetting) { + if (array_key_exists($rId, $this->rels['document'])) { + list($hfType, $xmlFile, $docPart) = array_values($this->rels['document'][$rId]); + $addMethod = "add{$hfType}"; + $hfObject = $section->$addMethod($hfSetting['type']); + + // Read header/footer content + $xmlReader = new XMLReader(); + $xmlReader->getDomFromZip($this->docFile, $xmlFile); + $nodes = $xmlReader->getElements('*'); + if ($nodes->length > 0) { + foreach ($nodes as $node) { + if (array_key_exists($node->nodeName, $readMethods)) { + $readMethod = $readMethods[$node->nodeName]; + $this->$readMethod($xmlReader, $node, $hfObject, $docPart); + } + } + } + } + } + } + } + + /** + * Read w:sectPr + * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $domNode + * @ignoreScrutinizerPatch + * @return array + */ + private function readSectionStyle(XMLReader $xmlReader, \DOMElement $domNode) + { + $styleDefs = array( + 'breakType' => array(self::READ_VALUE, 'w:type'), + 'pageSizeW' => array(self::READ_VALUE, 'w:pgSz', 'w:w'), + 'pageSizeH' => array(self::READ_VALUE, 'w:pgSz', 'w:h'), + 'orientation' => array(self::READ_VALUE, 'w:pgSz', 'w:orient'), + 'colsNum' => array(self::READ_VALUE, 'w:cols', 'w:num'), + 'colsSpace' => array(self::READ_VALUE, 'w:cols', 'w:space'), + 'topMargin' => array(self::READ_VALUE, 'w:pgMar', 'w:top'), + 'leftMargin' => array(self::READ_VALUE, 'w:pgMar', 'w:left'), + 'bottomMargin' => array(self::READ_VALUE, 'w:pgMar', 'w:bottom'), + 'rightMargin' => array(self::READ_VALUE, 'w:pgMar', 'w:right'), + 'headerHeight' => array(self::READ_VALUE, 'w:pgMar', 'w:header'), + 'footerHeight' => array(self::READ_VALUE, 'w:pgMar', 'w:footer'), + 'gutter' => array(self::READ_VALUE, 'w:pgMar', 'w:gutter'), + ); + $styles = $this->readStyleDefs($xmlReader, $domNode, $styleDefs); + + // Header and footer + // @todo Cleanup this part + $nodes = $xmlReader->getElements('*', $domNode); + foreach ($nodes as $node) { + if ($node->nodeName == 'w:headerReference' || $node->nodeName == 'w:footerReference') { + $id = $xmlReader->getAttribute('r:id', $node); + $styles['hf'][$id] = array( + 'method' => str_replace('w:', '', str_replace('Reference', '', $node->nodeName)), + 'type' => $xmlReader->getAttribute('w:type', $node), + ); + } + } + + return $styles; + } + + /** + * Read w:p node. + * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $node + * @param \PhpOffice\PhpWord\Element\Section &$section + * @return void + * + * @todo + */ + private function readWPNode(XMLReader $xmlReader, \DOMElement $node, Section &$section) + { + // Page break + if ($xmlReader->getAttribute('w:type', $node, 'w:r/w:br') == 'page') { + $section->addPageBreak(); // PageBreak + } + + // Paragraph + $this->readParagraph($xmlReader, $node, $section); + + // Section properties + if ($xmlReader->elementExists('w:pPr/w:sectPr', $node)) { + $sectPrNode = $xmlReader->getElement('w:pPr/w:sectPr', $node); + if ($sectPrNode !== null) { + $this->readWSectPrNode($xmlReader, $sectPrNode, $section); + } + $section = $this->phpWord->addSection(); + } + } + + /** + * Read w:sectPr node. + * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $node + * @param \PhpOffice\PhpWord\Element\Section &$section + * @return void + */ + private function readWSectPrNode(XMLReader $xmlReader, \DOMElement $node, Section &$section) + { + $style = $this->readSectionStyle($xmlReader, $node); + $section->setStyle($style); + $this->readHeaderFooter($style, $section); + } +} diff --git a/src/PhpWord/Reader/Word2007/Endnotes.php b/src/PhpWord/Reader/Word2007/Endnotes.php new file mode 100644 index 00000000..c493c347 --- /dev/null +++ b/src/PhpWord/Reader/Word2007/Endnotes.php @@ -0,0 +1,40 @@ +collection}"; + $collection = $phpWord->$getMethod()->getItems(); + + $xmlReader = new XMLReader(); + $xmlReader->getDomFromZip($this->docFile, $this->xmlFile); + $nodes = $xmlReader->getElements('*'); + if ($nodes->length > 0) { + foreach ($nodes as $node) { + $id = $xmlReader->getAttribute('w:id', $node); + $type = $xmlReader->getAttribute('w:type', $node); + + // Avoid w:type "separator" and "continuationSeparator" + // Only look for or without w:type attribute + if (is_null($type) && array_key_exists($id, $collection)) { + $element = $collection[$id]; + $pNodes = $xmlReader->getElements('w:p/*', $node); + foreach ($pNodes as $pNode) { + $this->readRun($xmlReader, $pNode, $element, $this->collection); + } + $addMethod = "add{$this->element}"; + $phpWord->$addMethod($element); + } + } + } + } +} diff --git a/src/PhpWord/Reader/Word2007/Numbering.php b/src/PhpWord/Reader/Word2007/Numbering.php new file mode 100644 index 00000000..872d4503 --- /dev/null +++ b/src/PhpWord/Reader/Word2007/Numbering.php @@ -0,0 +1,123 @@ +getDomFromZip($this->docFile, $this->xmlFile); + + // Abstract numbering definition + $nodes = $xmlReader->getElements('w:abstractNum'); + if ($nodes->length > 0) { + foreach ($nodes as $node) { + $abstractId = $xmlReader->getAttribute('w:abstractNumId', $node); + $abstracts[$abstractId] = array('levels' => array()); + $abstract = &$abstracts[$abstractId]; + $subnodes = $xmlReader->getElements('*', $node); + foreach ($subnodes as $subnode) { + switch ($subnode->nodeName) { + case 'w:multiLevelType': + $abstract['type'] = $xmlReader->getAttribute('w:val', $subnode); + break; + case 'w:lvl': + $levelId = $xmlReader->getAttribute('w:ilvl', $subnode); + $abstract['levels'][$levelId] = $this->readLevel($xmlReader, $subnode, $levelId); + break; + } + } + } + } + + // Numbering instance definition + $nodes = $xmlReader->getElements('w:num'); + if ($nodes->length > 0) { + foreach ($nodes as $node) { + $numId = $xmlReader->getAttribute('w:numId', $node); + $abstractId = $xmlReader->getAttribute('w:val', $node, 'w:abstractNumId'); + $numberings[$numId] = $abstracts[$abstractId]; + $numberings[$numId]['numId'] = $numId; + $subnodes = $xmlReader->getElements('w:lvlOverride/w:lvl', $node); + foreach ($subnodes as $subnode) { + $levelId = $xmlReader->getAttribute('w:ilvl', $subnode); + $overrides = $this->readLevel($xmlReader, $subnode, $levelId); + foreach ($overrides as $key => $value) { + $numberings[$numId]['levels'][$levelId][$key] = $value; + } + } + } + } + + // Push to Style collection + foreach ($numberings as $numId => $numbering) { + $phpWord->addNumberingStyle("PHPWordList{$numId}", $numbering); + } + } + + /** + * Read numbering level definition from w:abstractNum and w:num + * + * @param \PhpOffice\PhpWord\Shared\XMLReader $xmlReader + * @param \DOMElement $subnode + * @param integer $levelId + * @return array + */ + private function readLevel(XMLReader $xmlReader, \DOMElement $subnode, $levelId) + { + $level = array(); + + $level['level'] = $levelId; + $level['start'] = $xmlReader->getAttribute('w:val', $subnode, 'w:start'); + $level['format'] = $xmlReader->getAttribute('w:val', $subnode, 'w:numFmt'); + $level['restart'] = $xmlReader->getAttribute('w:val', $subnode, 'w:lvlRestart'); + $level['suffix'] = $xmlReader->getAttribute('w:val', $subnode, 'w:suff'); + $level['text'] = $xmlReader->getAttribute('w:val', $subnode, 'w:lvlText'); + $level['align'] = $xmlReader->getAttribute('w:val', $subnode, 'w:lvlJc'); + $level['tab'] = $xmlReader->getAttribute('w:pos', $subnode, 'w:pPr/w:tabs/w:tab'); + $level['left'] = $xmlReader->getAttribute('w:left', $subnode, 'w:pPr/w:ind'); + $level['hanging'] = $xmlReader->getAttribute('w:hanging', $subnode, 'w:pPr/w:ind'); + $level['font'] = $xmlReader->getAttribute('w:ascii', $subnode, 'w:rPr/w:rFonts'); + $level['hint'] = $xmlReader->getAttribute('w:hint', $subnode, 'w:rPr/w:rFonts'); + + foreach ($level as $key => $value) { + if (is_null($value)) { + unset($level[$key]); + } + } + + return $level; + } +} diff --git a/src/PhpWord/Reader/Word2007/Styles.php b/src/PhpWord/Reader/Word2007/Styles.php new file mode 100644 index 00000000..299fe1df --- /dev/null +++ b/src/PhpWord/Reader/Word2007/Styles.php @@ -0,0 +1,86 @@ +getDomFromZip($this->docFile, $this->xmlFile); + + $nodes = $xmlReader->getElements('w:style'); + if ($nodes->length > 0) { + foreach ($nodes as $node) { + $type = $xmlReader->getAttribute('w:type', $node); + $name = $xmlReader->getAttribute('w:styleId', $node); + if (is_null($name)) { + $name = $xmlReader->getAttribute('w:val', $node, 'w:name'); + } + preg_match('/Heading(\d)/', $name, $headingMatches); + // $default = ($xmlReader->getAttribute('w:default', $node) == 1); + switch ($type) { + + case 'paragraph': + $paragraphStyle = $this->readParagraphStyle($xmlReader, $node); + $fontStyle = $this->readFontStyle($xmlReader, $node); + if (!empty($headingMatches)) { + $phpWord->addTitleStyle($headingMatches[1], $fontStyle, $paragraphStyle); + } else { + if (empty($fontStyle)) { + if (is_array($paragraphStyle)) { + $phpWord->addParagraphStyle($name, $paragraphStyle); + } + } else { + $phpWord->addFontStyle($name, $fontStyle, $paragraphStyle); + } + } + break; + + case 'character': + $fontStyle = $this->readFontStyle($xmlReader, $node); + if (!empty($fontStyle)) { + $phpWord->addFontStyle($name, $fontStyle); + } + break; + + case 'table': + $tStyle = $this->readTableStyle($xmlReader, $node); + if (!empty($tStyle)) { + $phpWord->addTableStyle($name, $tStyle); + } + break; + } + } + } + } +} diff --git a/src/PhpWord/Settings.php b/src/PhpWord/Settings.php index 0af6cf72..6c7f17e1 100644 --- a/src/PhpWord/Settings.php +++ b/src/PhpWord/Settings.php @@ -1,91 +1,416 @@ 0) { + self::$defaultFontSize = $value; + return true; + } + + return false; + } + + /** + * Load setting from phpword.yml or phpword.yml.dist + * + * @param string $filename + * @return array + */ + public static function loadConfig($filename = null) + { + // Get config file + $configFile = null; + $configPath = __DIR__ . '/../../'; + if ($filename !== null) { + $files = array($filename); + } else { + $files = array("{$configPath}phpword.ini", "{$configPath}phpword.ini.dist"); + } + foreach ($files as $file) { + if (file_exists($file)) { + $configFile = realpath($file); + break; + } + } + + // Parse config file + $config = array(); + if ($configFile !== null) { + $config = @parse_ini_file($configFile); + if ($config === false) { + return $config; + } + } + + // Set config value + foreach ($config as $key => $value) { + $method = "set{$key}"; + if (method_exists(__CLASS__, $method)) { + self::$method($value); + } + } + + return $config; + } + + /** + * Return the compatibility option used by the XMLWriter + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public static function getCompatibility() + { + return self::hasCompatibility(); + } } diff --git a/src/PhpWord/Shared/Converter.php b/src/PhpWord/Shared/Converter.php new file mode 100644 index 00000000..c6727edd --- /dev/null +++ b/src/PhpWord/Shared/Converter.php @@ -0,0 +1,278 @@ +' . $html . ''; + } + + // Load DOM + $dom = new \DOMDocument(); + $dom->preserveWhiteSpace = true; + $dom->loadXML($html); + $node = $dom->getElementsByTagName('body'); + + self::parseNode($node->item(0), $element); + } + + /** + * parse Inline style of a node + * + * @param \DOMNode $node Node to check on attributes and to compile a style array + * @param array $styles is supplied, the inline style attributes are added to the already existing style + * @return array + */ + protected static function parseInlineStyle($node, $styles = array()) + { + if ($node->nodeType == XML_ELEMENT_NODE) { + $attributes = $node->attributes; // get all the attributes(eg: id, class) + + foreach ($attributes as $attribute) { + switch ($attribute->name) { + case 'style': + $styles = self::parseStyle($attribute, $styles); + break; + } + } + } + + return $styles; + } + + /** + * Parse a node and add a corresponding element to the parent element. + * + * @param \DOMNode $node node to parse + * @param \PhpOffice\PhpWord\Element\AbstractContainer $element object to add an element corresponding with the node + * @param array $styles Array with all styles + * @param array $data Array to transport data to a next level in the DOM tree, for example level of listitems + * @return void + */ + protected static function parseNode($node, $element, $styles = array(), $data = array()) + { + // Populate styles array + $styleTypes = array('font', 'paragraph', 'list'); + foreach ($styleTypes as $styleType) { + if (!isset($styles[$styleType])) { + $styles[$styleType] = array(); + } + } + + // Node mapping table + $nodes = array( + // $method $node $element $styles $data $argument1 $argument2 + 'p' => array('Paragraph', $node, $element, $styles, null, null, null), + 'h1' => array('Heading', null, $element, $styles, null, 'Heading1', null), + 'h2' => array('Heading', null, $element, $styles, null, 'Heading2', null), + 'h3' => array('Heading', null, $element, $styles, null, 'Heading3', null), + 'h4' => array('Heading', null, $element, $styles, null, 'Heading4', null), + 'h5' => array('Heading', null, $element, $styles, null, 'Heading5', null), + 'h6' => array('Heading', null, $element, $styles, null, 'Heading6', null), + '#text' => array('Text', $node, $element, $styles, null, null, null), + 'strong' => array('Property', null, null, $styles, null, 'bold', true), + 'em' => array('Property', null, null, $styles, null, 'italic', true), + 'sup' => array('Property', null, null, $styles, null, 'superScript', true), + 'sub' => array('Property', null, null, $styles, null, 'subScript', true), + 'table' => array('Table', $node, $element, $styles, null, 'addTable', true), + 'tr' => array('Table', $node, $element, $styles, null, 'addRow', true), + 'td' => array('Table', $node, $element, $styles, null, 'addCell', true), + 'ul' => array('List', null, null, $styles, $data, 3, null), + 'ol' => array('List', null, null, $styles, $data, 7, null), + 'li' => array('ListItem', $node, $element, $styles, $data, null, null), + ); + + $newElement = null; + $keys = array('node', 'element', 'styles', 'data', 'argument1', 'argument2'); + + if (array_key_exists($node->nodeName, $nodes)) { + + // Execute method based on node mapping table and return $newElement or null + // Arguments are passed by reference + $arguments = array(); + $args = array(); + list($method, $args[0], $args[1], $args[2], $args[3], $args[4], $args[5]) = $nodes[$node->nodeName]; + for ($i = 0; $i <= 5; $i++) { + if ($args[$i] !== null) { + $arguments[$keys[$i]] = &$args[$i]; + } + } + $method = "parse{$method}"; + $newElement = call_user_func_array(array('PhpOffice\PhpWord\Shared\Html', $method), $arguments); + + // Retrieve back variables from arguments + foreach ($keys as $key) { + if (array_key_exists($key, $arguments)) { + $$key = $arguments[$key]; + } + } + } + + if ($newElement === null) { + $newElement = $element; + } + + self::parseChildNodes($node, $newElement, $styles, $data); + } + + /** + * Parse child nodes. + * + * @param \DOMNode $node + * @param \PhpOffice\PhpWord\Element\AbstractContainer $element + * @param array $styles + * @param array $data + * @return void + */ + private static function parseChildNodes($node, $element, $styles, $data) + { + if ($node->nodeName != 'li') { + $cNodes = $node->childNodes; + if (count($cNodes) > 0) { + foreach ($cNodes as $cNode) { + if ($element instanceof AbstractContainer) { + self::parseNode($cNode, $element, $styles, $data); + } + } + } + } + } + + /** + * Parse paragraph node + * + * @param \DOMNode $node + * @param \PhpOffice\PhpWord\Element\AbstractContainer $element + * @param array &$styles + * @return \PhpOffice\PhpWord\Element\TextRun + */ + private static function parseParagraph($node, $element, &$styles) + { + $styles['paragraph'] = self::parseInlineStyle($node, $styles['paragraph']); + $newElement = $element->addTextRun($styles['paragraph']); + + return $newElement; + } + + /** + * Parse heading node + * + * @param \PhpOffice\PhpWord\Element\AbstractContainer $element + * @param array &$styles + * @param string $argument1 Name of heading style + * @return \PhpOffice\PhpWord\Element\TextRun + * + * @todo Think of a clever way of defining header styles, now it is only based on the assumption, that + * Heading1 - Heading6 are already defined somewhere + */ + private static function parseHeading($element, &$styles, $argument1) + { + $styles['paragraph'] = $argument1; + $newElement = $element->addTextRun($styles['paragraph']); + + return $newElement; + } + + /** + * Parse text node + * + * @param \DOMNode $node + * @param \PhpOffice\PhpWord\Element\AbstractContainer $element + * @param array &$styles + * @return null + */ + private static function parseText($node, $element, &$styles) + { + $styles['font'] = self::parseInlineStyle($node, $styles['font']); + + // Commented as source of bug #257. `method_exists` doesn't seems to work properly in this case. + // @todo Find better error checking for this one + // if (method_exists($element, 'addText')) { + $element->addText($node->nodeValue, $styles['font'], $styles['paragraph']); + // } + + return null; + } + + /** + * Parse property node + * + * @param array &$styles + * @param string $argument1 Style name + * @param string $argument2 Style value + * @return null + */ + private static function parseProperty(&$styles, $argument1, $argument2) + { + $styles['font'][$argument1] = $argument2; + + return null; + } + + /** + * Parse table node + * + * @param \DOMNode $node + * @param \PhpOffice\PhpWord\Element\AbstractContainer $element + * @param array &$styles + * @param string $argument1 Method name + * @return \PhpOffice\PhpWord\Element\AbstractContainer $element + * + * @todo As soon as TableItem, RowItem and CellItem support relative width and height + */ + private static function parseTable($node, $element, &$styles, $argument1) + { + $styles['paragraph'] = self::parseInlineStyle($node, $styles['paragraph']); + + $newElement = $element->$argument1(); + + // $attributes = $node->attributes; + // if ($attributes->getNamedItem('width') !== null) { + // $newElement->setWidth($attributes->getNamedItem('width')->value); + // } + + // if ($attributes->getNamedItem('height') !== null) { + // $newElement->setHeight($attributes->getNamedItem('height')->value); + // } + // if ($attributes->getNamedItem('width') !== null) { + // $newElement=$element->addCell($width=$attributes->getNamedItem('width')->value); + // } + + return $newElement; + } + + /** + * Parse list node + * + * @param array &$styles + * @param array &$data + * @param string $argument1 List type + * @return null + */ + private static function parseList(&$styles, &$data, $argument1) + { + if (isset($data['listdepth'])) { + $data['listdepth']++; + } else { + $data['listdepth'] = 0; + } + $styles['list']['listType'] = $argument1; + + return null; + } + + /** + * Parse list item node + * + * @param \DOMNode $node + * @param \PhpOffice\PhpWord\Element\AbstractContainer $element + * @param array &$styles + * @param array $data + * @return null + * + * @todo This function is almost the same like `parseChildNodes`. Merged? + * @todo As soon as ListItem inherits from AbstractContainer or TextRun delete parsing part of childNodes + */ + private static function parseListItem($node, $element, &$styles, $data) + { + $cNodes = $node->childNodes; + if (count($cNodes) > 0) { + $text = ''; + foreach ($cNodes as $cNode) { + if ($cNode->nodeName == '#text') { + $text = $cNode->nodeValue; + } + } + $element->addListItem($text, $data['listdepth'], $styles['font'], $styles['list'], $styles['paragraph']); + } + + return null; + } + + /** + * Parse style + * + * @param \DOMAttr $attribute + * @param array $styles + * @return array + */ + private static function parseStyle($attribute, $styles) + { + $properties = explode(';', trim($attribute->value, " \t\n\r\0\x0B;")); + foreach ($properties as $property) { + list($cKey, $cValue) = explode(':', $property, 2); + $cValue = trim($cValue); + switch (trim($cKey)) { + case 'text-decoration': + switch ($cValue) { + case 'underline': + $styles['underline'] = 'single'; + break; + case 'line-through': + $styles['strikethrough'] = true; + break; + } + break; + case 'text-align': + $styles['align'] = $cValue; + break; + case 'color': + $styles['color'] = trim($cValue, "#"); + break; + case 'background-color': + $styles['bgColor'] = trim($cValue, "#"); + break; + } + } + + return $styles; + } +} diff --git a/src/PhpWord/Shared/String.php b/src/PhpWord/Shared/String.php index 95f75f13..be04fd0e 100644 --- a/src/PhpWord/Shared/String.php +++ b/src/PhpWord/Shared/String.php @@ -1,10 +1,18 @@ 127 ? '\uc0{\u' . $value . '}' : chr($value); + } + } + + return $entities; + } + /** * Return name without underscore for < 0.10.0 variable name compatibility * @@ -95,7 +178,9 @@ class String } /** - * Build control characters array + * Build control characters array. + * + * @return void */ private static function buildControlCharacters() { diff --git a/src/PhpWord/Shared/XMLReader.php b/src/PhpWord/Shared/XMLReader.php index b7f5549e..ca6869eb 100644 --- a/src/PhpWord/Shared/XMLReader.php +++ b/src/PhpWord/Shared/XMLReader.php @@ -1,16 +1,23 @@ open($zipFile); - if ($canOpen === false) { - throw new Exception('Cannot open archive file.'); - } - $contents = $zip->getFromName($xmlFile); + $zip = new ZipArchive(); + $zip->open($zipFile); + $content = $zip->getFromName($xmlFile); $zip->close(); - if ($contents === false) { + if ($content === false) { return false; } else { - $this->dom = new \DOMDocument(); - $this->dom->loadXML($contents); - return $this->dom; + return $this->getDomFromString($content); } } + /** + * Get DOMDocument from content string + * + * @param string $content + * @return \DOMDocument + */ + public function getDomFromString($content) + { + $this->dom = new \DOMDocument(); + $this->dom->loadXML($content); + + return $this->dom; + } + /** * Get elements * * @param string $path + * @param \DOMElement $contextNode * @return \DOMNodeList */ public function getElements($path, \DOMElement $contextNode = null) @@ -79,16 +96,21 @@ class XMLReader $this->xpath = new \DOMXpath($this->dom); } - return $this->xpath->query($path, $contextNode); + if (is_null($contextNode)) { + return $this->xpath->query($path); + } else { + return $this->xpath->query($path, $contextNode); + } } /** * Get element * * @param string $path + * @param \DOMElement $contextNode * @return \DOMElement|null */ - public function getElement($path, \DOMElement $contextNode) + public function getElement($path, \DOMElement $contextNode = null) { $elements = $this->getElements($path, $contextNode); if ($elements->length > 0) { @@ -102,19 +124,23 @@ class XMLReader * Get element attribute * * @param string $attribute + * @param \DOMElement $contextNode * @param string $path * @return string|null */ - public function getAttribute($attribute, \DOMElement $contextNode, $path = null) + public function getAttribute($attribute, \DOMElement $contextNode = null, $path = null) { - if (is_null($path)) { - $return = $contextNode->getAttribute($attribute); - } else { + $return = null; + if ($path !== null) { $elements = $this->getElements($path, $contextNode); if ($elements->length > 0) { - $return = $elements->item(0)->getAttribute($attribute); - } else { - $return = null; + /** @var \DOMElement $node Type hint */ + $node = $elements->item(0); + $return = $node->getAttribute($attribute); + } + } else { + if ($contextNode !== null) { + $return = $contextNode->getAttribute($attribute); } } @@ -125,9 +151,10 @@ class XMLReader * Get element value * * @param string $path + * @param \DOMElement $contextNode * @return string|null */ - public function getValue($path, \DOMElement $contextNode) + public function getValue($path, \DOMElement $contextNode = null) { $elements = $this->getElements($path, $contextNode); if ($elements->length > 0) { @@ -141,9 +168,10 @@ class XMLReader * Count elements * * @param string $path + * @param \DOMElement $contextNode * @return integer */ - public function countElements($path, \DOMElement $contextNode) + public function countElements($path, \DOMElement $contextNode = null) { $elements = $this->getElements($path, $contextNode); @@ -154,9 +182,10 @@ class XMLReader * Element exists * * @param string $path + * @param \DOMElement $contextNode * @return boolean */ - public function elementExists($path, \DOMElement $contextNode) + public function elementExists($path, \DOMElement $contextNode = null) { return $this->getElements($path, $contextNode)->length > 0; } diff --git a/src/PhpWord/Shared/XMLWriter.php b/src/PhpWord/Shared/XMLWriter.php index d4e959bc..2134f62a 100644 --- a/src/PhpWord/Shared/XMLWriter.php +++ b/src/PhpWord/Shared/XMLWriter.php @@ -1,35 +1,38 @@ xmlWriter = new \XMLWriter(); // Open temporary storage - if ($pTemporaryStorage == self::STORAGE_MEMORY) { + if ($tempLocation == self::STORAGE_MEMORY) { $this->xmlWriter->openMemory(); } else { // Create temporary filename - $this->tempFile = @tempnam($pTemporaryStorageFolder, 'xml'); + $this->tempFile = tempnam($tempFolder, 'xml'); - // Open storage - if ($this->xmlWriter->openUri($this->tempFile) === false) { - // Fallback to memory... + // Fallback to memory when temporary file cannot be used + // @codeCoverageIgnoreStart + // Can't find any test case. Uncomment when found. + if (false === $this->tempFile || false === $this->xmlWriter->openUri($this->tempFile)) { $this->xmlWriter->openMemory(); } + // @codeCoverageIgnoreEnd } // Set xml Compatibility - $compatibility = Settings::getCompatibility(); + $compatibility = Settings::hasCompatibility(); if ($compatibility) { $this->xmlWriter->setIndent(false); $this->xmlWriter->setIndentString(''); @@ -88,7 +93,7 @@ class XMLWriter */ public function __destruct() { - // Desctruct XMLWriter + // Destruct XMLWriter unset($this->xmlWriter); // Unlink temporary files @@ -102,9 +107,16 @@ class XMLWriter * * @param mixed $function * @param mixed $args + * @throws \BadMethodCallException */ public function __call($function, $args) { + // Catch exception + if (method_exists($this->xmlWriter, $function) === false) { + throw new \BadMethodCallException("Method '{$function}' does not exists."); + } + + // Run method try { @call_user_func_array(array($this->xmlWriter, $function), $args); } catch (\Exception $ex) { @@ -128,17 +140,63 @@ class XMLWriter } /** - * Fallback method for writeRaw, introduced in PHP 5.2 + * Write simple element and attribute(s) block * - * @param string $text - * @return bool + * There are two options: + * 1. If the `$attributes` is an array, then it's an associative array of attributes + * 2. If not, then it's a simple attribute-value pair + * + * @param string $element + * @param string|array $attributes + * @param string $value + * @return void */ - public function writeRaw($text) + public function writeElementBlock($element, $attributes, $value = null) { - if (isset($this->xmlWriter) && is_object($this->xmlWriter) && (method_exists($this->xmlWriter, 'writeRaw'))) { - return $this->xmlWriter->writeRaw($text); + $this->xmlWriter->startElement($element); + if (!is_array($attributes)) { + $attributes = array($attributes => $value); } + foreach ($attributes as $attribute => $value) { + $this->xmlWriter->writeAttribute($attribute, $value); + } + $this->xmlWriter->endElement(); + } - return $this->text($text); + /** + * Write element if ... + * + * @param bool $condition + * @param string $element + * @param string $attribute + * @param mixed $value + * @return void + */ + public function writeElementIf($condition, $element, $attribute = null, $value = null) + { + if ($condition == true) { + if (is_null($attribute)) { + $this->xmlWriter->writeElement($element, $value); + } else { + $this->xmlWriter->startElement($element); + $this->xmlWriter->writeAttribute($attribute, $value); + $this->xmlWriter->endElement(); + } + } + } + + /** + * Write attribute if ... + * + * @param bool $condition + * @param string $attribute + * @param mixed $value + * @return void + */ + public function writeAttributeIf($condition, $attribute, $value) + { + if ($condition == true) { + $this->xmlWriter->writeAttribute($attribute, $value); + } } } diff --git a/src/PhpWord/Shared/ZipArchive.php b/src/PhpWord/Shared/ZipArchive.php index 21d13cfe..157959e8 100644 --- a/src/PhpWord/Shared/ZipArchive.php +++ b/src/PhpWord/Shared/ZipArchive.php @@ -1,43 +1,59 @@ tempDir = sys_get_temp_dir(); - $this->zip = new \PclZip($filename); - $this->numFiles = count($this->zip->listContent()); + private $usePclzip = true; - return true; + /** + * Create new instance + */ + public function __construct() + { + $this->usePclzip = (Settings::getZipClass() != 'ZipArchive'); + if ($this->usePclzip) { + if (!defined('PCLZIP_TEMPORARY_DIR')) { + define('PCLZIP_TEMPORARY_DIR', Settings::getTempDir() . '/'); + } + require_once 'PCLZip/pclzip.lib.php'; + } } /** - * Close this zip archive + * Catch function calls: pass to ZipArchive or PCLZip * - * @codeCoverageIgnore + * `call_user_func_array` can only used for public function, hence the `public` in all `pcl...` methods + * + * @param mixed $function + * @param mixed $args + * @return mixed + */ + public function __call($function, $args) + { + // Set object and function + $zipFunction = $function; + if (!$this->usePclzip) { + $zipObject = $this->zip; + } else { + $zipObject = $this; + $zipFunction = "pclzip{$zipFunction}"; + } + + // Run function + $result = false; + if (method_exists($zipObject, $zipFunction)) { + $result = @call_user_func_array(array($zipObject, $zipFunction), $args); + } + + return $result; + } + + /** + * Open a new zip archive + * + * @param string $filename The file name of the ZIP archive to open + * @param int $flags The mode to use to open the archive + * @return bool + */ + public function open($filename, $flags = null) + { + $result = true; + $this->filename = $filename; + + if (!$this->usePclzip) { + $zip = new \ZipArchive(); + $result = $zip->open($this->filename, $flags); + + // Scrutizer will report the property numFiles does not exist + // See https://github.com/scrutinizer-ci/php-analyzer/issues/190 + $this->numFiles = $zip->numFiles; + } else { + $zip = new \PclZip($this->filename); + $this->tempDir = Settings::getTempDir(); + $this->numFiles = count($zip->listContent()); + } + $this->zip = $zip; + + return $result; + } + + /** + * Close the active archive + * + * @return bool + * @throws \PhpOffice\PhpWord\Exception\Exception + * @codeCoverageIgnore Can't find any test case. Uncomment when found. */ public function close() { - } - - /** - * Add a new file to the zip archive. - * - * @param string $filename Directory/Name of the file to add to the zip archive - * @param string $localname Directory/Name of the file added to the zip - */ - public function addFile($filename, $localname = null) - { - $filename = realpath($filename); - $filenameParts = pathinfo($filename); - $localnameParts = pathinfo($localname); - - // To Rename the file while adding it to the zip we - // need to create a temp file with the correct name - if ($filenameParts['basename'] != $localnameParts['basename']) { - $temppath = $this->tempDir . '/' . $localnameParts['basename']; - copy($filename, $temppath); - $filename = $temppath; - $filenameParts = pathinfo($temppath); - } - - $res = $this->zip->add( - $filename, - PCLZIP_OPT_REMOVE_PATH, - $filenameParts['dirname'], - PCLZIP_OPT_ADD_PATH, - $localnameParts["dirname"] - ); - - if ($res == 0) { - throw new Exception("Error zipping files : " . $this->zip->errorInfo(true)); - } - - return true; - } - - /** - * Add a new file to the zip archive from a string of raw data. - * - * @param string $localname Directory/Name of the file to add to the zip archive - * @param string $contents String of data to add to the zip archive - */ - public function addFromString($localname, $contents) - { - $filenameParts = pathinfo($localname); - - // Write $contents to a temp file - $handle = fopen($this->tempDir . '/' . $filenameParts["basename"], "wb"); - fwrite($handle, $contents); - fclose($handle); - - // Add temp file to zip - $res = $this->zip->add( - $this->tempDir . '/' . $filenameParts["basename"], - PCLZIP_OPT_REMOVE_PATH, - $this->tempDir, - PCLZIP_OPT_ADD_PATH, - $filenameParts["dirname"] - ); - if ($res == 0) { - throw new Exception("Error zipping files : " . $this->zip->errorInfo(true)); - } - - // Remove temp file - unlink($this->tempDir . '/' . $filenameParts["basename"]); - - return true; - } - - /** - * Find if given file name exist in archive (Emulate ZipArchive locateName()) - * - * @param string $filename Filename for the file in zip archive - * @return boolean - */ - public function locateName($filename) - { - $list = $this->zip->listContent(); - $listCount = count($list); - $listIndex = -1; - for ($i = 0; $i < $listCount; ++$i) { - if (strtolower($list[$i]["filename"]) == strtolower($filename) || - strtolower($list[$i]["stored_filename"]) == strtolower($filename)) { - $listIndex = $i; - break; + if (!$this->usePclzip) { + if ($this->zip->close() === false) { + throw new Exception("Could not close zip file {$this->filename}."); } } - return ($listIndex > -1); + return true; } /** - * Extract file from archive by given file name (Emulate ZipArchive getFromName()) + * Extract the archive contents (emulate \ZipArchive) + * + * @param string $destination + * @param string|array $entries + * @return bool + * @since 0.10.0 + */ + public function extractTo($destination, $entries = null) + { + if (!is_dir($destination)) { + return false; + } + + if (!$this->usePclzip) { + return $this->zip->extractTo($destination, $entries); + } else { + return $this->pclzipExtractTo($destination, $entries); + } + } + + /** + * Extract file from archive by given file name (emulate \ZipArchive) * * @param string $filename Filename for the file in zip archive * @return string $contents File string contents */ public function getFromName($filename) { - $list = $this->zip->listContent(); - $listCount = count($list); - $listIndex = -1; - $contents = null; - - for ($i = 0; $i < $listCount; ++$i) { - if (strtolower($list[$i]["filename"]) == strtolower($filename) || - strtolower($list[$i]["stored_filename"]) == strtolower($filename)) { - $listIndex = $i; - break; + if (!$this->usePclzip) { + $contents = $this->zip->getFromName($filename); + if ($contents === false) { + $filename = substr($filename, 1); + $contents = $this->zip->getFromName($filename); } - } - - if ($listIndex != -1) { - $extracted = $this->zip->extractByIndex($listIndex, PCLZIP_OPT_EXTRACT_AS_STRING); } else { - $filename = substr($filename, 1); - $listIndex = -1; - for ($i = 0; $i < $listCount; ++$i) { - if (strtolower($list[$i]["filename"]) == strtolower($filename) || - strtolower($list[$i]["stored_filename"]) == strtolower($filename)) { - $listIndex = $i; - break; - } - } - $extracted = $this->zip->extractByIndex($listIndex, PCLZIP_OPT_EXTRACT_AS_STRING); - } - if ((is_array($extracted)) && ($extracted != 0)) { - $contents = $extracted[0]["content"]; + $contents = $this->pclzipGetFromName($filename); } return $contents; } /** - * Returns the name of an entry using its index + * Add a new file to the zip archive (emulate \ZipArchive) * - * @param integer $index - * @return string|false + * @param string $filename Directory/Name of the file to add to the zip archive + * @param string $localname Directory/Name of the file added to the zip + * @return bool */ - public function getNameIndex($index) + public function pclzipAddFile($filename, $localname = null) { - $list = $this->zip->listContent(); + /** @var \PclZip $zip Type hint */ + $zip = $this->zip; + + // Bugfix GH-261 https://github.com/PHPOffice/PHPWord/pull/261 + $realpathFilename = realpath($filename); + if ($realpathFilename !== false) { + $filename = $realpathFilename; + } + + $filenameParts = pathinfo($filename); + $localnameParts = pathinfo($localname); + + // To Rename the file while adding it to the zip we + // need to create a temp file with the correct name + $tempFile = false; + if ($filenameParts['basename'] != $localnameParts['basename']) { + $tempFile = true; // temp file created + $temppath = $this->tempDir . DIRECTORY_SEPARATOR . $localnameParts['basename']; + copy($filename, $temppath); + $filename = $temppath; + $filenameParts = pathinfo($temppath); + } + + $pathRemoved = $filenameParts['dirname']; + $pathAdded = $localnameParts['dirname']; + + $res = $zip->add($filename, PCLZIP_OPT_REMOVE_PATH, $pathRemoved, PCLZIP_OPT_ADD_PATH, $pathAdded); + + if ($tempFile) { + // Remove temp file, if created + unlink($this->tempDir . DIRECTORY_SEPARATOR . $localnameParts['basename']); + } + + return ($res == 0) ? false : true; + } + + /** + * Add a new file to the zip archive from a string of raw data (emulate \ZipArchive) + * + * @param string $localname Directory/Name of the file to add to the zip archive + * @param string $contents String of data to add to the zip archive + * @return bool + */ + public function pclzipAddFromString($localname, $contents) + { + /** @var \PclZip $zip Type hint */ + $zip = $this->zip; + $filenameParts = pathinfo($localname); + + // Write $contents to a temp file + $handle = fopen($this->tempDir . DIRECTORY_SEPARATOR . $filenameParts['basename'], 'wb'); + fwrite($handle, $contents); + fclose($handle); + + // Add temp file to zip + $filename = $this->tempDir . DIRECTORY_SEPARATOR . $filenameParts['basename']; + $pathRemoved = $this->tempDir; + $pathAdded = $filenameParts['dirname']; + + $res = $zip->add($filename, PCLZIP_OPT_REMOVE_PATH, $pathRemoved, PCLZIP_OPT_ADD_PATH, $pathAdded); + + // Remove temp file + @unlink($this->tempDir . DIRECTORY_SEPARATOR . $filenameParts['basename']); + + return ($res == 0) ? false : true; + } + + /** + * Extract the archive contents (emulate \ZipArchive) + * + * @param string $destination + * @param string|array $entries + * @return bool + * @since 0.10.0 + */ + public function pclzipExtractTo($destination, $entries = null) + { + /** @var \PclZip $zip Type hint */ + $zip = $this->zip; + + // Extract all files + if (is_null($entries)) { + $result = $zip->extract(PCLZIP_OPT_PATH, $destination); + return ($result > 0) ? true : false; + } + + // Extract by entries + if (!is_array($entries)) { + $entries = array($entries); + } + foreach ($entries as $entry) { + $entryIndex = $this->locateName($entry); + $result = $zip->extractByIndex($entryIndex, PCLZIP_OPT_PATH, $destination); + if ($result <= 0) { + return false; + } + } + + return true; + } + + /** + * Extract file from archive by given file name (emulate \ZipArchive) + * + * @param string $filename Filename for the file in zip archive + * @return string $contents File string contents + */ + public function pclzipGetFromName($filename) + { + /** @var \PclZip $zip Type hint */ + $zip = $this->zip; + $listIndex = $this->pclzipLocateName($filename); + $contents = false; + + if ($listIndex !== false) { + $extracted = $zip->extractByIndex($listIndex, PCLZIP_OPT_EXTRACT_AS_STRING); + } else { + $filename = substr($filename, 1); + $listIndex = $this->pclzipLocateName($filename); + $extracted = $zip->extractByIndex($listIndex, PCLZIP_OPT_EXTRACT_AS_STRING); + } + if ((is_array($extracted)) && ($extracted != 0)) { + $contents = $extracted[0]['content']; + } + + return $contents; + } + + /** + * Returns the name of an entry using its index (emulate \ZipArchive) + * + * @param int $index + * @return string + * @since 0.10.0 + */ + public function pclzipGetNameIndex($index) + { + /** @var \PclZip $zip Type hint */ + $zip = $this->zip; + $list = $zip->listContent(); if (isset($list[$index])) { return $list[$index]['filename']; } else { return false; } } + + /** + * Returns the index of the entry in the archive (emulate \ZipArchive) + * + * @param string $filename Filename for the file in zip archive + * @return int + */ + public function pclzipLocateName($filename) + { + /** @var \PclZip $zip Type hint */ + $zip = $this->zip; + $list = $zip->listContent(); + $listCount = count($list); + $listIndex = -1; + for ($i = 0; $i < $listCount; ++$i) { + if (strtolower($list[$i]['filename']) == strtolower($filename) || + strtolower($list[$i]['stored_filename']) == strtolower($filename)) { + $listIndex = $i; + break; + } + } + + return ($listIndex > -1) ? $listIndex : false; + } } diff --git a/src/PhpWord/Style.php b/src/PhpWord/Style.php old mode 100755 new mode 100644 index e0b5d439..73af4f5d --- a/src/PhpWord/Style.php +++ b/src/PhpWord/Style.php @@ -1,18 +1,27 @@ $value) { - $styleObject->setStyleValue($key, $value); + if (!array_key_exists($name, self::$styles)) { + if ($value !== null) { + if (is_array($value)) { + $style->setStyleByArray($value); + } elseif ($value instanceof AbstractStyle) { + if (get_class($style) == get_class($value)) { + $style = $value; + } } } - $styleObject->setIndex(self::countStyles() + 1); // One based index - self::$styles[$styleName] = $styleObject; + $style->setStyleName($name); + $style->setIndex(self::countStyles() + 1); // One based index + self::$styles[$name] = $style; } + + return self::getStyle($name); } } diff --git a/src/PhpWord/Style/AbstractStyle.php b/src/PhpWord/Style/AbstractStyle.php index ea77dc70..aec490b5 100644 --- a/src/PhpWord/Style/AbstractStyle.php +++ b/src/PhpWord/Style/AbstractStyle.php @@ -1,10 +1,18 @@ styleName; + } + + /** + * Set style name + * + * @param string $value + * @return self + */ + public function setStyleName($value) + { + $this->styleName = $value; + + return $this; + } + /** * Get index number * - * @return integer|null + * @return int|null */ public function getIndex() { @@ -40,7 +93,8 @@ abstract class AbstractStyle /** * Set index number * - * @param integer|null $value + * @param int|null $value + * @return self */ public function setIndex($value = null) { @@ -49,6 +103,47 @@ abstract class AbstractStyle return $this; } + /** + * Get is automatic style flag + * + * @return bool + */ + public function isAuto() + { + return $this->isAuto; + } + + /** + * Set is automatic style flag + * + * @param bool $value + * @return self + */ + public function setAuto($value = true) + { + $this->isAuto = $this->setBoolVal($value, $this->isAuto); + + return $this; + } + + /** + * Return style value of child style object, e.g. `left` from `Indentation` child style of `Paragraph` + * + * @param \PhpOffice\PhpWord\Style\AbstractStyle $substyleObject + * @param string $substyleProperty + * @return mixed + * @since 0.12.0 + */ + public function getChildStyleValue($substyleObject, $substyleProperty) + { + if ($substyleObject !== null) { + $method = "get{$substyleProperty}"; + return $substyleObject->$method(); + } else { + return null; + } + } + /** * Set style value template method * @@ -63,6 +158,9 @@ abstract class AbstractStyle */ public function setStyleValue($key, $value) { + if (isset($this->aliases[$key])) { + $key = $this->aliases[$key]; + } $method = 'set' . String::removeUnderscorePrefix($key); if (method_exists($this, $method)) { $this->$method($value); @@ -74,12 +172,12 @@ abstract class AbstractStyle /** * Set style by using associative array * - * @param array $styles + * @param array $values * @return self */ - public function setStyleByArray($styles = array()) + public function setStyleByArray($values = array()) { - foreach ($styles as $key => $value) { + foreach ($values as $key => $value) { $this->setStyleValue($key, $value); } @@ -87,13 +185,29 @@ abstract class AbstractStyle } /** - * Set boolean value + * Set default for null and empty value * - * @param mixed $value - * @param boolean|null $default - * @return boolean|null + * @param string $value (was: mixed) + * @param string $default (was: mixed) + * @return string (was: mixed) */ - protected function setBoolVal($value, $default = null) + protected function setNonEmptyVal($value, $default) + { + if ($value === null || $value == '') { + $value = $default; + } + + return $value; + } + + /** + * Set bool value + * + * @param bool $value + * @param bool $default + * @return bool + */ + protected function setBoolVal($value, $default) { if (!is_bool($value)) { $value = $default; @@ -103,15 +217,15 @@ abstract class AbstractStyle } /** - * Set integer value + * Set numeric value * * @param mixed $value - * @param integer|null $default - * @return integer|null + * @param int|float|null $default + * @return int|float|null */ - protected function setIntVal($value, $default = null) + protected function setNumericVal($value, $default = null) { - if (!is_int($value)) { + if (!is_numeric($value)) { $value = $default; } @@ -119,7 +233,28 @@ abstract class AbstractStyle } /** - * Set float value + * Set integer value: Convert string that contains only numeric into integer + * + * @param int|null $value + * @param int|null $default + * @return int|null + */ + protected function setIntVal($value, $default = null) + { + if (is_string($value) && (preg_match('/[^\d]/', $value) == 0)) { + $value = intval($value); + } + if (!is_numeric($value)) { + $value = $default; + } else { + $value = intval($value); + } + + return $value; + } + + /** + * Set float value: Convert string that contains only numeric into float * * @param mixed $value * @param float|null $default @@ -127,7 +262,10 @@ abstract class AbstractStyle */ protected function setFloatVal($value, $default = null) { - if (!is_float($value)) { + if (is_string($value) && (preg_match('/[^\d\.\,]/', $value) == 0)) { + $value = floatval($value); + } + if (!is_numeric($value)) { $value = $default; } @@ -140,13 +278,72 @@ abstract class AbstractStyle * @param mixed $value * @param array $enum * @param mixed $default + * @return mixed + * @throws \InvalidArgumentException */ - protected function setEnumVal($value, $enum, $default = null) + protected function setEnumVal($value = null, $enum = array(), $default = null) { - if (!in_array($value, $enum)) { + if ($value != null && trim($value) != '' && !empty($enum) && !in_array($value, $enum)) { + throw new \InvalidArgumentException("Invalid style value: {$value}"); + } elseif ($value === null || trim($value) == '') { $value = $default; } return $value; } + + /** + * Set object value + * + * @param mixed $value + * @param string $styleName + * @param mixed &$style + * @return mixed + */ + protected function setObjectVal($value, $styleName, &$style) + { + $styleClass = substr(get_class($this), 0, strrpos(get_class($this), '\\')) . '\\' . $styleName; + if (is_array($value)) { + /** @var \PhpOffice\PhpWord\Style\AbstractStyle $style Type hint */ + if (!$style instanceof $styleClass) { + $style = new $styleClass(); + } + $style->setStyleByArray($value); + } else { + $style = $value; + } + + return $style; + } + + /** + * Set $property value and set $pairProperty = false when $value = true + * + * @param bool &$property + * @param bool &$pairProperty + * @param bool $value + * @return self + */ + protected function setPairedVal(&$property, &$pairProperty, $value) + { + $property = $this->setBoolVal($value, $property); + if ($value == true) { + $pairProperty = false; + } + + return $this; + } + + /** + * Set style using associative array + * + * @param array $style + * @return self + * @deprecated 0.11.0 + * @codeCoverageIgnore + */ + public function setArrayStyle(array $style = array()) + { + return $this->setStyleByArray($style); + } } diff --git a/src/PhpWord/Style/Alignment.php b/src/PhpWord/Style/Alignment.php new file mode 100644 index 00000000..3beabe37 --- /dev/null +++ b/src/PhpWord/Style/Alignment.php @@ -0,0 +1,78 @@ +setStyleByArray($style); + } + + /** + * Get alignment + * + * @return string + */ + public function getValue() + { + return $this->value; + } + + /** + * Set alignment + * + * @param string $value + * @return self + */ + public function setValue($value = null) + { + if (strtolower($value) == self::ALIGN_JUSTIFY) { + $value = self::ALIGN_BOTH; + } + $enum = array(self::ALIGN_LEFT, self::ALIGN_RIGHT, self::ALIGN_CENTER, self::ALIGN_BOTH, self::ALIGN_JUSTIFY); + $this->value = $this->setEnumVal($value, $enum, $this->value); + + return $this; + } +} diff --git a/src/PhpWord/Style/Border.php b/src/PhpWord/Style/Border.php new file mode 100644 index 00000000..84116d7a --- /dev/null +++ b/src/PhpWord/Style/Border.php @@ -0,0 +1,338 @@ +getBorderTopSize(), + $this->getBorderLeftSize(), + $this->getBorderRightSize(), + $this->getBorderBottomSize(), + ); + } + + /** + * Set border size + * + * @param int|float $value + * @return self + */ + public function setBorderSize($value = null) + { + $this->setBorderTopSize($value); + $this->setBorderLeftSize($value); + $this->setBorderRightSize($value); + $this->setBorderBottomSize($value); + + return $this; + } + + /** + * Get border color + * + * @return string[] + */ + public function getBorderColor() + { + return array( + $this->getBorderTopColor(), + $this->getBorderLeftColor(), + $this->getBorderRightColor(), + $this->getBorderBottomColor(), + ); + } + + /** + * Set border color + * + * @param string $value + * @return self + */ + public function setBorderColor($value = null) + { + $this->setBorderTopColor($value); + $this->setBorderLeftColor($value); + $this->setBorderRightColor($value); + $this->setBorderBottomColor($value); + + return $this; + } + + /** + * Get border top size + * + * @return int|float + */ + public function getBorderTopSize() + { + return $this->borderTopSize; + } + + /** + * Set border top size + * + * @param int|float $value + * @return self + */ + public function setBorderTopSize($value = null) + { + $this->borderTopSize = $this->setNumericVal($value, $this->borderTopSize); + + return $this; + } + + /** + * Get border top color + * + * @return string + */ + public function getBorderTopColor() + { + return $this->borderTopColor; + } + + /** + * Set border top color + * + * @param string $value + * @return self + */ + public function setBorderTopColor($value = null) + { + $this->borderTopColor = $value; + + return $this; + } + + /** + * Get border left size + * + * @return int|float + */ + public function getBorderLeftSize() + { + return $this->borderLeftSize; + } + + /** + * Set border left size + * + * @param int|float $value + * @return self + */ + public function setBorderLeftSize($value = null) + { + $this->borderLeftSize = $this->setNumericVal($value, $this->borderLeftSize); + + return $this; + } + + /** + * Get border left color + * + * @return string + */ + public function getBorderLeftColor() + { + return $this->borderLeftColor; + } + + /** + * Set border left color + * + * @param string $value + * @return self + */ + public function setBorderLeftColor($value = null) + { + $this->borderLeftColor = $value; + + return $this; + } + + /** + * Get border right size + * + * @return int|float + */ + public function getBorderRightSize() + { + return $this->borderRightSize; + } + + /** + * Set border right size + * + * @param int|float $value + * @return self + */ + public function setBorderRightSize($value = null) + { + $this->borderRightSize = $this->setNumericVal($value, $this->borderRightSize); + + return $this; + } + + /** + * Get border right color + * + * @return string + */ + public function getBorderRightColor() + { + return $this->borderRightColor; + } + + /** + * Set border right color + * + * @param string $value + * @return self + */ + public function setBorderRightColor($value = null) + { + $this->borderRightColor = $value; + + return $this; + } + + /** + * Get border bottom size + * + * @return int|float + */ + public function getBorderBottomSize() + { + return $this->borderBottomSize; + } + + /** + * Set border bottom size + * + * @param int|float $value + * @return self + */ + public function setBorderBottomSize($value = null) + { + $this->borderBottomSize = $this->setNumericVal($value, $this->borderBottomSize); + + return $this; + } + + /** + * Get border bottom color + * + * @return string + */ + public function getBorderBottomColor() + { + return $this->borderBottomColor; + } + + /** + * Set border bottom color + * + * @param string $value + * @return self + */ + public function setBorderBottomColor($value = null) + { + $this->borderBottomColor = $value; + + return $this; + } + + /** + * Check if any of the border is not null + * + * @return bool + */ + public function hasBorder() + { + $borders = $this->getBorderSize(); + + return $borders !== array_filter($borders, 'is_null'); + } +} diff --git a/src/PhpWord/Style/Cell.php b/src/PhpWord/Style/Cell.php index 64a7f35a..11290c87 100644 --- a/src/PhpWord/Style/Cell.php +++ b/src/PhpWord/Style/Cell.php @@ -1,30 +1,66 @@ valign = null; - $this->textDirection = null; - $this->bgColor = null; - $this->borderTopSize = null; - $this->borderTopColor = null; - $this->borderLeftSize = null; - $this->borderLeftColor = null; - $this->borderRightSize = null; - $this->borderRightColor = null; - $this->borderBottomSize = null; - $this->borderBottomColor = null; - $this->defaultBorderColor = '000000'; - } - - /** - * Set style value + * Shading * - * @param string $key - * @param mixed $value + * @var \PhpOffice\PhpWord\Style\Shading */ - public function setStyleValue($key, $value) - { - $key = String::removeUnderscorePrefix($key); - if ($key == 'borderSize') { - $this->setBorderSize($value); - } elseif ($key == 'borderColor') { - $this->setBorderColor($value); - } else { - $this->$key = $value; - } - } + private $shading; /** - * Get vertical align + * Get vertical align. + * + * @return string */ public function getVAlign() { - return $this->valign; + return $this->vAlign; } /** * Set vertical align * - * @param string $pValue + * @param string $value + * @return self */ - public function setVAlign($pValue = null) + public function setVAlign($value = null) { - $this->valign = $pValue; + $enum = array(self::VALIGN_TOP, self::VALIGN_CENTER, self::VALIGN_BOTTOM, self::VALIGN_BOTH); + $this->vAlign = $this->setEnumVal($value, $enum, $this->vAlign); + + return $this; } /** - * Get text direction + * Get text direction. + * + * @return string */ public function getTextDirection() { @@ -186,247 +130,46 @@ class Cell extends AbstractStyle /** * Set text direction * - * @param string $pValue + * @param string $value + * @return self */ - public function setTextDirection($pValue = null) + public function setTextDirection($value = null) { - $this->textDirection = $pValue; + $enum = array(self::TEXT_DIR_BTLR, self::TEXT_DIR_TBRL); + $this->textDirection = $this->setEnumVal($value, $enum, $this->textDirection); + + return $this; } /** - * Get background color + * Get background + * + * @return string */ public function getBgColor() { - return $this->bgColor; + if ($this->shading !== null) { + return $this->shading->getFill(); + } else { + return null; + } } /** - * Set background color + * Set background * - * @param string $pValue + * @param string $value + * @return self */ - public function setBgColor($pValue = null) + public function setBgColor($value = null) { - $this->bgColor = $pValue; + return $this->setShading(array('fill' => $value)); } /** - * Set border size + * Get grid span (colspan). * - * @param int $pValue - */ - public function setBorderSize($pValue = null) - { - $this->borderTopSize = $pValue; - $this->borderLeftSize = $pValue; - $this->borderRightSize = $pValue; - $this->borderBottomSize = $pValue; - } - - /** - * Get border size - */ - public function getBorderSize() - { - $t = $this->getBorderTopSize(); - $l = $this->getBorderLeftSize(); - $r = $this->getBorderRightSize(); - $b = $this->getBorderBottomSize(); - - return array($t, $l, $r, $b); - } - - /** - * Set border color - * - * @param string $pValue - */ - public function setBorderColor($pValue = null) - { - $this->borderTopColor = $pValue; - $this->borderLeftColor = $pValue; - $this->borderRightColor = $pValue; - $this->borderBottomColor = $pValue; - } - - /** - * Get border color - */ - public function getBorderColor() - { - $t = $this->getBorderTopColor(); - $l = $this->getBorderLeftColor(); - $r = $this->getBorderRightColor(); - $b = $this->getBorderBottomColor(); - - return array($t, $l, $r, $b); - } - - /** - * Set border top size - * - * @param int $pValue - */ - public function setBorderTopSize($pValue = null) - { - $this->borderTopSize = $pValue; - } - - /** - * Get border top size - */ - public function getBorderTopSize() - { - return $this->borderTopSize; - } - - /** - * Set border top color - * - * @param string $pValue - */ - public function setBorderTopColor($pValue = null) - { - $this->borderTopColor = $pValue; - } - - /** - * Get border top color - */ - public function getBorderTopColor() - { - return $this->borderTopColor; - } - - /** - * Set border left size - * - * @param int $pValue - */ - public function setBorderLeftSize($pValue = null) - { - $this->borderLeftSize = $pValue; - } - - /** - * Get border left size - */ - public function getBorderLeftSize() - { - return $this->borderLeftSize; - } - - /** - * Set border left color - * - * @param string $pValue - */ - public function setBorderLeftColor($pValue = null) - { - $this->borderLeftColor = $pValue; - } - - /** - * Get border left color - */ - public function getBorderLeftColor() - { - return $this->borderLeftColor; - } - - /** - * Set border right size - * - * @param int $pValue - */ - public function setBorderRightSize($pValue = null) - { - $this->borderRightSize = $pValue; - } - - /** - * Get border right size - */ - public function getBorderRightSize() - { - return $this->borderRightSize; - } - - /** - * Set border right color - * - * @param string $pValue - */ - public function setBorderRightColor($pValue = null) - { - $this->borderRightColor = $pValue; - } - - /** - * Get border right color - */ - public function getBorderRightColor() - { - return $this->borderRightColor; - } - - /** - * Set border bottom size - * - * @param int $pValue - */ - public function setBorderBottomSize($pValue = null) - { - $this->borderBottomSize = $pValue; - } - - /** - * Get border bottom size - */ - public function getBorderBottomSize() - { - return $this->borderBottomSize; - } - - /** - * Set border bottom color - * - * @param string $pValue - */ - public function setBorderBottomColor($pValue = null) - { - $this->borderBottomColor = $pValue; - } - - /** - * Get border bottom color - */ - public function getBorderBottomColor() - { - return $this->borderBottomColor; - } - - /** - * Get default border color - */ - public function getDefaultBorderColor() - { - return $this->defaultBorderColor; - } - - /** - * Set grid span (colspan) - * - * @param int $pValue - */ - public function setGridSpan($pValue = null) - { - $this->gridSpan = $pValue; - } - - /** - * Get grid span (colspan) + * @return integer */ public function getGridSpan() { @@ -434,20 +177,73 @@ class Cell extends AbstractStyle } /** - * Set vertical merge (rowspan) + * Set grid span (colspan) * - * @param string $pValue + * @param int $value + * @return self */ - public function setVMerge($pValue = null) + public function setGridSpan($value = null) { - $this->vMerge = $pValue; + $this->gridSpan = $this->setIntVal($value, $this->gridSpan); + + return $this; } /** - * Get vertical merge (rowspan) + * Get vertical merge (rowspan). + * + * @return string */ public function getVMerge() { return $this->vMerge; } + + /** + * Set vertical merge (rowspan) + * + * @param string $value + * @return self + */ + public function setVMerge($value = null) + { + $enum = array(self::VMERGE_RESTART, self::VMERGE_CONTINUE); + $this->vMerge = $this->setEnumVal($value, $enum, $this->vMerge); + + return $this; + } + + /** + * Get shading + * + * @return \PhpOffice\PhpWord\Style\Shading + */ + public function getShading() + { + return $this->shading; + } + + /** + * Set shading + * + * @param mixed $value + * @return self + */ + public function setShading($value = null) + { + $this->setObjectVal($value, 'Shading', $this->shading); + + return $this; + } + + /** + * Get default border color + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getDefaultBorderColor() + { + return self::DEFAULT_BORDER_COLOR; + } } diff --git a/src/PhpWord/Style/Chart.php b/src/PhpWord/Style/Chart.php new file mode 100644 index 00000000..13b72a33 --- /dev/null +++ b/src/PhpWord/Style/Chart.php @@ -0,0 +1,127 @@ +setStyleByArray($style); + } + + /** + * Get width + * + * @return int + */ + public function getWidth() + { + return $this->width; + } + + /** + * Set width + * + * @param int $value + * @return self + */ + public function setWidth($value = null) + { + $this->width = $this->setIntVal($value, $this->width); + + return $this; + } + + /** + * Get height + * + * @return int + */ + public function getHeight() + { + return $this->height; + } + + /** + * Set height + * + * @param int $value + * @return self + */ + public function setHeight($value = null) + { + $this->height = $this->setIntVal($value, $this->height); + + return $this; + } + + /** + * Is 3D + * + * @return bool + */ + public function is3d() + { + return $this->is3d; + } + + /** + * Set 3D + * + * @param bool $value + * @return self + */ + public function set3d($value = true) + { + $this->is3d = $this->setBoolVal($value, $this->is3d); + + return $this; + } +} diff --git a/src/PhpWord/Style/Extrusion.php b/src/PhpWord/Style/Extrusion.php new file mode 100644 index 00000000..ccbb2650 --- /dev/null +++ b/src/PhpWord/Style/Extrusion.php @@ -0,0 +1,106 @@ +setStyleByArray($style); + } + + /** + * Get type + * + * @return string + */ + public function getType() + { + return $this->type; + } + + /** + * Set pattern + * + * @param string $value + * @return self + */ + public function setType($value = null) + { + $enum = array(self::EXTRUSION_PARALLEL, self::EXTRUSION_PERSPECTIVE); + $this->type = $this->setEnumVal($value, $enum, null); + + return $this; + } + + /** + * Get color + * + * @return string + */ + public function getColor() + { + return $this->color; + } + + /** + * Set color + * + * @param string $value + * @return self + */ + public function setColor($value = null) + { + $this->color = $value; + + return $this; + } +} diff --git a/src/PhpWord/Style/Fill.php b/src/PhpWord/Style/Fill.php new file mode 100644 index 00000000..08c7a857 --- /dev/null +++ b/src/PhpWord/Style/Fill.php @@ -0,0 +1,69 @@ +setStyleByArray($style); + } + + /** + * Get color + * + * @return string + */ + public function getColor() + { + return $this->color; + } + + /** + * Set color + * + * @param string $value + * @return self + */ + public function setColor($value = null) + { + $this->color = $value; + + return $this; + } +} diff --git a/src/PhpWord/Style/Font.php b/src/PhpWord/Style/Font.php index 149f7c54..8980258b 100644 --- a/src/PhpWord/Style/Font.php +++ b/src/PhpWord/Style/Font.php @@ -1,22 +1,32 @@ 'lineHeight'); + /** * Font style type * @@ -58,26 +81,33 @@ class Font extends AbstractStyle */ private $type; - /** - * Paragraph style - * - * @var \PhpOffice\PhpWord\Style\Paragraph - */ - private $paragraphStyle; - /** * Font name * - * @var int|float + * @var string */ - private $name = PhpWord::DEFAULT_FONT_NAME; + private $name; + + /** + * Font Content Type + * + * @var string + */ + private $hint; /** * Font size * * @var int|float */ - private $size = PhpWord::DEFAULT_FONT_SIZE; + private $size; + + /** + * Font color + * + * @var string + */ + private $color; /** * Bold @@ -93,6 +123,13 @@ class Font extends AbstractStyle */ private $italic = false; + /** + * Undeline + * + * @var string + */ + private $underline = self::UNDERLINE_NONE; + /** * Superscript * @@ -107,13 +144,6 @@ class Font extends AbstractStyle */ private $subScript = false; - /** - * Undeline - * - * @var string - */ - private $underline = self::UNDERLINE_NONE; - /** * Strikethrough * @@ -122,88 +152,149 @@ class Font extends AbstractStyle private $strikethrough = false; /** - * Font color + * Double strikethrough * - * @var string + * @var bool */ - private $color = PhpWord::DEFAULT_FONT_COLOR; + private $doubleStrikethrough = false; + + /** + * Small caps + * + * @var bool + * @link http://www.schemacentral.com/sc/ooxml/e-w_smallCaps-1.html + */ + private $smallCaps = false; + + /** + * All caps + * + * @var bool + * @link http://www.schemacentral.com/sc/ooxml/e-w_caps-1.html + */ + private $allCaps = false; /** * Foreground/highlight * * @var string */ - private $fgColor = null; + private $fgColor; /** - * Background color - * - * @var string - */ - private $bgColor = null; - /** - * Text line height + * Expanded/compressed text: 0-600 (percent) * * @var int + * @since 0.12.0 + * @link http://www.schemacentral.com/sc/ooxml/e-w_w-1.html */ + private $scale; /** - * Text line height + * Character spacing adjustment: twip * - * @var int + * @var int|float + * @since 0.12.0 + * @link http://www.schemacentral.com/sc/ooxml/e-w_spacing-2.html */ - private $lineHeight = 1.0; + private $spacing; /** - * Font Content Type + * Font kerning: halfpoint * - * @var string + * @var int|float + * @since 0.12.0 + * @link http://www.schemacentral.com/sc/ooxml/e-w_kern-1.html */ - private $hint = PhpWord::DEFAULT_FONT_CONTENT_TYPE; + private $kerning; + + /** + * Paragraph style + * + * @var \PhpOffice\PhpWord\Style\Paragraph + */ + private $paragraph; + + /** + * Shading + * + * @var \PhpOffice\PhpWord\Style\Shading + */ + private $shading; + + /** + * Right to left languages + * @var boolean + */ + private $rtl = false; /** * Create new font style * * @param string $type Type of font - * @param array $paragraphStyle Paragraph styles definition + * @param array $paragraph Paragraph styles definition */ - public function __construct($type = 'text', $paragraphStyle = null) + public function __construct($type = 'text', $paragraph = null) { $this->type = $type; - - if ($paragraphStyle instanceof Paragraph) { - $this->paragraphStyle = $paragraphStyle; - } elseif (is_array($paragraphStyle)) { - $this->paragraphStyle = new Paragraph; - $this->paragraphStyle->setArrayStyle($paragraphStyle); - } else { - $this->paragraphStyle = $paragraphStyle; - } + $this->setParagraph($paragraph); } /** - * Set style using associative array + * Get style values * - * @param array $style - * @return $this + * @return array + * @since 0.12.0 */ - public function setArrayStyle(array $style = array()) + public function getStyleValues() { - foreach ($style as $key => $value) { - if ($key === 'line-height') { - $this->setLineHeight($value); - null; - } - $this->setStyleValue($key, $value); - } + $styles = array( + 'name' => $this->getStyleName(), + 'basic' => array( + 'name' => $this->getName(), + 'size' => $this->getSize(), + 'color' => $this->getColor(), + 'hint' => $this->getHint(), + ), + 'style' => array( + 'bold' => $this->isBold(), + 'italic' => $this->isItalic(), + 'underline' => $this->getUnderline(), + 'strike' => $this->isStrikethrough(), + 'dStrike' => $this->isDoubleStrikethrough(), + 'super' => $this->isSuperScript(), + 'sub' => $this->isSubScript(), + 'smallCaps' => $this->isSmallCaps(), + 'allCaps' => $this->isAllCaps(), + 'fgColor' => $this->getFgColor(), + ), + 'spacing' => array( + 'scale' => $this->getScale(), + 'spacing' => $this->getSpacing(), + 'kerning' => $this->getKerning(), + ), + 'paragraph' => $this->getParagraph(), + 'rtl' => $this->isRTL(), + 'shading' => $this->getShading(), + ); - return $this; + return $styles; + } + + /** + * Get style type + * + * @return string + */ + public function getStyleType() + { + return $this->type; } /** * Get font name * - * @return bool + * @return string */ public function getName() { @@ -213,22 +304,43 @@ class Font extends AbstractStyle /** * Set font name * - * @param string $pValue - * @return \PhpOffice\PhpWord\Style\Font + * @param string $value + * @return self */ - public function setName($pValue = PhpWord::DEFAULT_FONT_NAME) + public function setName($value = null) { - if (is_null($pValue) || $pValue == '') { - $pValue = PhpWord::DEFAULT_FONT_NAME; - } - $this->name = $pValue; + $this->name = $value; + + return $this; + } + + /** + * Get Font Content Type + * + * @return string + */ + public function getHint() + { + return $this->hint; + } + + /** + * Set Font Content Type + * + * @param string $value + * @return self + */ + public function setHint($value = null) + { + $this->hint = $value; + return $this; } /** * Get font size * - * @return int|float + * @return int|float */ public function getSize() { @@ -238,167 +350,13 @@ class Font extends AbstractStyle /** * Set font size * - * @param int|float $pValue - * @return \PhpOffice\PhpWord\Style\Font + * @param int|float $value + * @return self */ - public function setSize($pValue = PhpWord::DEFAULT_FONT_SIZE) + public function setSize($value = null) { - if (!is_numeric($pValue)) { - $pValue = PhpWord::DEFAULT_FONT_SIZE; - } - $this->size = $pValue; - return $this; - } + $this->size = $this->setNumericVal($value, $this->size); - /** - * Get bold - * - * @return bool - */ - public function getBold() - { - return $this->bold; - } - - /** - * Set bold - * - * @param bool $pValue - * @return \PhpOffice\PhpWord\Style\Font - */ - public function setBold($pValue = false) - { - if (!is_bool($pValue)) { - $pValue = false; - } - $this->bold = $pValue; - return $this; - } - - /** - * Get italic - * - * @return bool - */ - public function getItalic() - { - return $this->italic; - } - - /** - * Set italic - * - * @param bool $pValue - * @return \PhpOffice\PhpWord\Style\Font - */ - public function setItalic($pValue = false) - { - if (!is_bool($pValue)) { - $pValue = false; - } - $this->italic = $pValue; - return $this; - } - - /** - * Get superscript - * - * @return bool - */ - public function getSuperScript() - { - return $this->superScript; - } - - /** - * Set superscript - * - * @param bool $pValue - * @return \PhpOffice\PhpWord\Style\Font - */ - public function setSuperScript($pValue = false) - { - if (!is_bool($pValue)) { - $pValue = false; - } - $this->superScript = $pValue; - $this->subScript = !$pValue; - return $this; - } - - /** - * Get subscript - * - * @return bool - */ - public function getSubScript() - { - return $this->subScript; - } - - /** - * Set subscript - * - * @param bool $pValue - * @return \PhpOffice\PhpWord\Style\Font - */ - public function setSubScript($pValue = false) - { - if (!is_bool($pValue)) { - $pValue = false; - } - $this->subScript = $pValue; - $this->superScript = !$pValue; - return $this; - } - - /** - * Get underline - * - * @return string - */ - public function getUnderline() - { - return $this->underline; - } - - /** - * Set underline - * - * @param string $pValue - * @return \PhpOffice\PhpWord\Style\Font - */ - public function setUnderline($pValue = self::UNDERLINE_NONE) - { - if ($pValue == '') { - $pValue = self::UNDERLINE_NONE; - } - $this->underline = $pValue; - return $this; - } - - /** - * Get strikethrough - * - * @return bool - */ - public function getStrikethrough() - { - return $this->strikethrough; - } - - /** - * Set strikethrough - * - * @param bool $pValue - * @return \PhpOffice\PhpWord\Style\Font - */ - public function setStrikethrough($pValue = false) - { - if (!is_bool($pValue)) { - $pValue = false; - } - $this->strikethrough = $pValue; return $this; } @@ -415,18 +373,211 @@ class Font extends AbstractStyle /** * Set font color * - * @param string $pValue - * @return \PhpOffice\PhpWord\Style\Font + * @param string $value + * @return self */ - public function setColor($pValue = PhpWord::DEFAULT_FONT_COLOR) + public function setColor($value = null) { - if (is_null($pValue) || $pValue == '') { - $pValue = PhpWord::DEFAULT_FONT_COLOR; - } - $this->color = $pValue; + $this->color = $value; + return $this; } + /** + * Get bold + * + * @return bool + */ + public function isBold() + { + return $this->bold; + } + + /** + * Set bold + * + * @param bool $value + * @return self + */ + public function setBold($value = true) + { + $this->bold = $this->setBoolVal($value, $this->bold); + + return $this; + } + + /** + * Get italic + * + * @return bool + */ + public function isItalic() + { + return $this->italic; + } + + /** + * Set italic + * + * @param bool $value + * @return self + */ + public function setItalic($value = true) + { + $this->italic = $this->setBoolVal($value, $this->italic); + + return $this; + } + + /** + * Get underline + * + * @return string + */ + public function getUnderline() + { + return $this->underline; + } + + /** + * Set underline + * + * @param string $value + * @return self + */ + public function setUnderline($value = self::UNDERLINE_NONE) + { + $this->underline = $this->setNonEmptyVal($value, self::UNDERLINE_NONE); + + return $this; + } + + /** + * Get superscript + * + * @return bool + */ + public function isSuperScript() + { + return $this->superScript; + } + + /** + * Set superscript + * + * @param bool $value + * @return self + */ + public function setSuperScript($value = true) + { + return $this->setPairedVal($this->superScript, $this->subScript, $value); + } + + /** + * Get subscript + * + * @return bool + */ + public function isSubScript() + { + return $this->subScript; + } + + /** + * Set subscript + * + * @param bool $value + * @return self + */ + public function setSubScript($value = true) + { + return $this->setPairedVal($this->subScript, $this->superScript, $value); + } + + /** + * Get strikethrough + * + * @return bool + */ + public function isStrikethrough() + { + return $this->strikethrough; + } + + /** + * Set strikethrough + * + * @param bool $value + * @return self + */ + public function setStrikethrough($value = true) + { + return $this->setPairedVal($this->strikethrough, $this->doubleStrikethrough, $value); + } + + /** + * Get double strikethrough + * + * @return bool + */ + public function isDoubleStrikethrough() + { + return $this->doubleStrikethrough; + } + + /** + * Set double strikethrough + * + * @param bool $value + * @return self + */ + public function setDoubleStrikethrough($value = true) + { + return $this->setPairedVal($this->doubleStrikethrough, $this->strikethrough, $value); + } + + /** + * Get small caps + * + * @return bool + */ + public function isSmallCaps() + { + return $this->smallCaps; + } + + /** + * Set small caps + * + * @param bool $value + * @return self + */ + public function setSmallCaps($value = true) + { + return $this->setPairedVal($this->smallCaps, $this->allCaps, $value); + } + + /** + * Get all caps + * + * @return bool + */ + public function isAllCaps() + { + return $this->allCaps; + } + + /** + * Set all caps + * + * @param bool $value + * @return self + */ + public function setAllCaps($value = true) + { + return $this->setPairedVal($this->allCaps, $this->smallCaps, $value); + } + /** * Get foreground/highlight color * @@ -440,76 +591,103 @@ class Font extends AbstractStyle /** * Set foreground/highlight color * - * @param string $pValue - * @return \PhpOffice\PhpWord\Style\Font + * @param string $value + * @return self */ - public function setFgColor($pValue = null) + public function setFgColor($value = null) { - $this->fgColor = $pValue; + $this->fgColor = $value; + return $this; } /** - * Get background color - * - * @return string - */ - public function getBgColor() - { - return $this->bgColor; - } - - /** - * Set background color - * - * @param string $pValue - * @return $this - */ - public function setBgColor($pValue = null) - { - $this->bgColor = $pValue; - return $this; - } - - /** - * Get style type + * Get background * * @return string */ - public function getStyleType() + public function getBgColor() { - return $this->type; + return $this->getChildStyleValue($this->shading, 'fill'); } /** - * Get paragraph style + * Set background * - * @return \PhpOffice\PhpWord\Style\Paragraph + * @param string $value + * @return \PhpOffice\PhpWord\Style\Table */ - public function getParagraphStyle() + public function setBgColor($value = null) { - return $this->paragraphStyle; + $this->setShading(array('fill' => $value)); } /** - * Set lineheight + * Get scale * - * @param int|float|string $lineHeight - * @return $this - * @throws \PhpOffice\PhpWord\Exception\InvalidStyleException + * @return int */ - public function setLineHeight($lineHeight) + public function getScale() { - if (is_string($lineHeight)) { - $lineHeight = floatval(preg_replace('/[^0-9\.\,]/', '', $lineHeight)); - } + return $this->scale; + } - if ((!is_integer($lineHeight) && !is_float($lineHeight)) || !$lineHeight) { - throw new InvalidStyleException('Line height must be a valid number'); - } + /** + * Set scale + * + * @param int $value + * @return self + */ + public function setScale($value = null) + { + $this->scale = $this->setIntVal($value, null); + + return $this; + } + + /** + * Get font spacing + * + * @return int|float + */ + public function getSpacing() + { + return $this->spacing; + } + + /** + * Set font spacing + * + * @param int|float $value + * @return self + */ + public function setSpacing($value = null) + { + $this->spacing = $this->setNumericVal($value, null); + + return $this; + } + + /** + * Get font kerning + * + * @return int|float + */ + public function getKerning() + { + return $this->kerning; + } + + /** + * Set font kerning + * + * @param int|float $value + * @return self + */ + public function setKerning($value = null) + { + $this->kerning = $this->setNumericVal($value, null); - $this->lineHeight = $lineHeight; - $this->getParagraphStyle()->setLineHeight($lineHeight); return $this; } @@ -520,31 +698,154 @@ class Font extends AbstractStyle */ public function getLineHeight() { - return $this->lineHeight; + return $this->getParagraph()->getLineHeight(); } /** - * Get Font Content Type + * Set lineheight * - * @return string + * @param int|float|string $value + * @return self */ - public function getHint() + public function setLineHeight($value) { - return $this->hint; - } + $this->setParagraph(array('lineHeight' => $value)); - /** - * Set Font Content Type - * - * @param string $pValue - * @return \PhpOffice\PhpWord\Style\Font - */ - public function setHint($pValue = PhpWord::DEFAULT_FONT_CONTENT_TYPE) - { - if (is_null($pValue) || $pValue == '') { - $pValue = PhpWord::DEFAULT_FONT_CONTENT_TYPE; - } - $this->hint = $pValue; return $this; } + + /** + * Get paragraph style + * + * @return \PhpOffice\PhpWord\Style\Paragraph + */ + public function getParagraph() + { + return $this->paragraph; + } + + /** + * Set shading + * + * @param mixed $value + * @return self + */ + public function setParagraph($value = null) + { + $this->setObjectVal($value, 'Paragraph', $this->paragraph); + + return $this; + } + + /** + * Get rtl + * + * @return bool + */ + public function isRTL() + { + return $this->rtl; + } + + /** + * Set rtl + * + * @param bool $value + * @return self + */ + public function setRTL($value = true) + { + $this->rtl = $this->setBoolVal($value, $this->rtl); + + return $this; + } + + /** + * Get shading + * + * @return \PhpOffice\PhpWord\Style\Shading + */ + public function getShading() + { + return $this->shading; + } + + /** + * Set shading + * + * @param mixed $value + * @return self + */ + public function setShading($value = null) + { + $this->setObjectVal($value, 'Shading', $this->shading); + + return $this; + } + + /** + * Get bold + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getBold() + { + return $this->isBold(); + } + + /** + * Get italic + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getItalic() + { + return $this->isItalic(); + } + + /** + * Get superscript + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getSuperScript() + { + return $this->isSuperScript(); + } + + /** + * Get subscript + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getSubScript() + { + return $this->isSubScript(); + } + + /** + * Get strikethrough + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getStrikethrough() + { + return $this->isStrikethrough(); + } + + /** + * Get paragraph style + * + * @deprecated 0.11.0 + * @codeCoverageIgnore + */ + public function getParagraphStyle() + { + return $this->getParagraph(); + } } diff --git a/src/PhpWord/Style/Frame.php b/src/PhpWord/Style/Frame.php new file mode 100644 index 00000000..21b27716 --- /dev/null +++ b/src/PhpWord/Style/Frame.php @@ -0,0 +1,475 @@ +alignment = new Alignment(); + $this->setStyleByArray($style); + } + + /** + * Get alignment + * + * @return string + */ + public function getAlign() + { + return $this->alignment->getValue(); + } + + /** + * Set alignment + * + * @param string $value + * @return self + */ + public function setAlign($value = null) + { + $this->alignment->setValue($value); + + return $this; + } + + /** + * Get unit + * + * @return string + */ + public function getUnit() + { + return $this->unit; + } + + /** + * Set unit + * + * @param string $value + * @return self + */ + public function setUnit($value) + { + $this->unit = $value; + + return $this; + } + + /** + * Get width + * + * @return int|float + */ + public function getWidth() + { + return $this->width; + } + + /** + * Set width + * + * @param int|float $value + * @return self + */ + public function setWidth($value = null) + { + $this->width = $this->setNumericVal($value, null); + + return $this; + } + + /** + * Get height + * + * @return int|float + */ + public function getHeight() + { + return $this->height; + } + + /** + * Set height + * + * @param int|float $value + * @return self + */ + public function setHeight($value = null) + { + $this->height = $this->setNumericVal($value, null); + + return $this; + } + + /** + * Get left + * + * @return int|float + */ + public function getLeft() + { + return $this->left; + } + + /** + * Set left + * + * @param int|float $value + * @return self + */ + public function setLeft($value = 0) + { + $this->left = $this->setNumericVal($value, 0); + + return $this; + } + + /** + * Get topmost position + * + * @return int|float + */ + public function getTop() + { + return $this->top; + } + + /** + * Set topmost position + * + * @param int|float $value + * @return self + */ + public function setTop($value = 0) + { + $this->top = $this->setNumericVal($value, 0); + + return $this; + } + + /** + * Get position type + * + * @return string + */ + public function getPos() + { + return $this->pos; + } + + /** + * Set position type + * + * @param string $value + * @return self + */ + public function setPos($value) + { + $enum = array(self::POS_RELATIVE, self::POS_ABSOLUTE); + $this->pos = $this->setEnumVal($value, $enum, $this->pos); + + return $this; + } + + /** + * Get horizontal position + * + * @return string + */ + public function getHPos() + { + return $this->hPos; + } + + /** + * Set horizontal position + * + * @param string $value + * @return self + */ + public function setHPos($value) + { + $enum = array(self::POS_LEFT, self::POS_CENTER, self::POS_RIGHT, self::POS_INSIDE, self::POS_OUTSIDE); + $this->hPos = $this->setEnumVal($value, $enum, $this->hPos); + + return $this; + } + + /** + * Get vertical position + * + * @return string + */ + public function getVPos() + { + return $this->vPos; + } + + /** + * Set vertical position + * + * @param string $value + * @return self + */ + public function setVPos($value) + { + $enum = array(self::POS_TOP, self::POS_CENTER, self::POS_BOTTOM, self::POS_INSIDE, self::POS_OUTSIDE); + $this->vPos = $this->setEnumVal($value, $enum, $this->vPos); + + return $this; + } + + /** + * Get horizontal position relative to + * + * @return string + */ + public function getHPosRelTo() + { + return $this->hPosRelTo; + } + + /** + * Set horizontal position relative to + * + * @param string $value + * @return self + */ + public function setHPosRelTo($value) + { + $enum = array( + self::POS_RELTO_MARGIN, self::POS_RELTO_PAGE, self::POS_RELTO_COLUMN, self::POS_RELTO_CHAR, + self::POS_RELTO_LMARGIN, self::POS_RELTO_RMARGIN, self::POS_RELTO_IMARGIN, self::POS_RELTO_OMARGIN, + ); + $this->hPosRelTo = $this->setEnumVal($value, $enum, $this->hPosRelTo); + + return $this; + } + + /** + * Get vertical position relative to + * + * @return string + */ + public function getVPosRelTo() + { + return $this->vPosRelTo; + } + + /** + * Set vertical position relative to + * + * @param string $value + * @return self + */ + public function setVPosRelTo($value) + { + $enum = array( + self::POS_RELTO_MARGIN, self::POS_RELTO_PAGE, self::POS_RELTO_TEXT, self::POS_RELTO_LINE, + self::POS_RELTO_TMARGIN, self::POS_RELTO_BMARGIN, self::POS_RELTO_IMARGIN, self::POS_RELTO_OMARGIN, + ); + $this->vPosRelTo = $this->setEnumVal($value, $enum, $this->vPosRelTo); + + return $this; + } + + /** + * Get wrap type + * + * @return string + */ + public function getWrap() + { + return $this->wrap; + } + + /** + * Set wrap type + * + * @param string $value + * @return self + */ + public function setWrap($value) + { + $enum = array( + self::WRAP_INLINE, self::WRAP_SQUARE, self::WRAP_TIGHT, self::WRAP_THROUGH, + self::WRAP_TOPBOTTOM, self::WRAP_BEHIND, self::WRAP_INFRONT + ); + $this->wrap = $this->setEnumVal($value, $enum, $this->wrap); + + return $this; + } +} diff --git a/src/PhpWord/Style/Image.php b/src/PhpWord/Style/Image.php index f21e6674..babfa679 100644 --- a/src/PhpWord/Style/Image.php +++ b/src/PhpWord/Style/Image.php @@ -1,198 +1,121 @@ width = null; - $this->height = null; - $this->align = null; - $this->marginTop = null; - $this->marginLeft = null; - $this->setWrappingStyle(self::WRAPPING_STYLE_INLINE); + parent::__construct(); + $this->setUnit('px'); + + // Backward compatilibity setting + // @todo Remove on 1.0.0 + $this->setWrap(self::WRAPPING_STYLE_INLINE); + $this->setHPos(self::POSITION_HORIZONTAL_LEFT); + $this->setHPosRelTo(self::POSITION_RELATIVE_TO_CHAR); + $this->setVPos(self::POSITION_VERTICAL_TOP); + $this->setVPosRelTo(self::POSITION_RELATIVE_TO_LINE); } /** - * Get width - */ - public function getWidth() - { - return $this->width; - } - - /** - * Set width + * Get margin top * - * @param int $pValue - */ - public function setWidth($pValue = null) - { - $this->width = $pValue; - } - - /** - * Get height - */ - public function getHeight() - { - return $this->height; - } - - /** - * Set height - * - * @param int $pValue - */ - public function setHeight($pValue = null) - { - $this->height = $pValue; - } - - /** - * Get alignment - */ - public function getAlign() - { - return $this->align; - } - - /** - * Set alignment - * - * @param string $pValue - */ - public function setAlign($pValue = null) - { - $this->align = $pValue; - } - - /** - * Get Margin Top - * - * @return int + * @return int|float */ public function getMarginTop() { - return $this->marginTop; + return $this->getTop(); } /** - * Set Margin Top + * Set margin top * - * @param int $pValue - * @return $this + * @ignoreScrutinizerPatch + * @param int|float $value + * @return self */ - public function setMarginTop($pValue = null) + public function setMarginTop($value = 0) { - $this->marginTop = $pValue; + $this->setTop($value); + return $this; } /** - * Get Margin Left + * Get margin left * - * @return int + * @return int|float */ public function getMarginLeft() { - return $this->marginLeft; + return $this->getLeft(); } /** - * Set Margin Left + * Set margin left * - * @param int $pValue - * @return $this + * @ignoreScrutinizerPatch + * @param int|float $value + * @return self */ - public function setMarginLeft($pValue = null) + public function setMarginLeft($value = 0) { - $this->marginLeft = $pValue; - return $this; - } + $this->setLeft($value); - /** - * Set wrapping style - * - * @param string $wrappingStyle - * @throws \InvalidArgumentException - * @return $this - */ - public function setWrappingStyle($wrappingStyle) - { - switch ($wrappingStyle) { - case self::WRAPPING_STYLE_BEHIND: - case self::WRAPPING_STYLE_INFRONT: - case self::WRAPPING_STYLE_INLINE: - case self::WRAPPING_STYLE_SQUARE: - case self::WRAPPING_STYLE_TIGHT: - $this->wrappingStyle = $wrappingStyle; - break; - default: - throw new \InvalidArgumentException('Wrapping style does not exists'); - } return $this; } @@ -203,6 +126,140 @@ class Image extends AbstractStyle */ public function getWrappingStyle() { - return $this->wrappingStyle; + return $this->getWrap(); + } + + /** + * Set wrapping style + * + * @param string $wrappingStyle + * @throws \InvalidArgumentException + * @return self + */ + public function setWrappingStyle($wrappingStyle) + { + $this->setWrap($wrappingStyle); + + return $this; + } + + /** + * Get positioning type + * + * @return string + */ + public function getPositioning() + { + return $this->getPos(); + } + + /** + * Set positioning type + * + * @param string $positioning + * @throws \InvalidArgumentException + * @return self + */ + public function setPositioning($positioning) + { + $this->setPos($positioning); + + return $this; + } + + /** + * Get horizontal alignment + * + * @return string + */ + public function getPosHorizontal() + { + return $this->getHPos(); + } + + /** + * Set horizontal alignment + * + * @param string $alignment + * @throws \InvalidArgumentException + * @return self + */ + public function setPosHorizontal($alignment) + { + $this->setHPos($alignment); + + return $this; + } + + /** + * Get vertical alignment + * + * @return string + */ + public function getPosVertical() + { + return $this->getVPos(); + } + + /** + * Set vertical alignment + * + * @param string $alignment + * @throws \InvalidArgumentException + * @return self + */ + public function setPosVertical($alignment) + { + $this->setVPos($alignment); + + return $this; + } + + /** + * Get horizontal relation + * + * @return string + */ + public function getPosHorizontalRel() + { + return $this->getHPosRelTo(); + } + + /** + * Set horizontal relation + * + * @param string $relto + * @throws \InvalidArgumentException + * @return self + */ + public function setPosHorizontalRel($relto) + { + $this->setHPosRelTo($relto); + + return $this; + } + + /** + * Get vertical relation + * + * @return string + */ + public function getPosVerticalRel() + { + return $this->getVPosRelTo(); + } + + /** + * Set vertical relation + * + * @param string $relto + * @throws \InvalidArgumentException + * @return self + */ + public function setPosVerticalRel($relto) + { + $this->setVPosRelTo($relto); + + return $this; } } diff --git a/src/PhpWord/Style/Indentation.php b/src/PhpWord/Style/Indentation.php new file mode 100644 index 00000000..5854204a --- /dev/null +++ b/src/PhpWord/Style/Indentation.php @@ -0,0 +1,157 @@ +setStyleByArray($style); + } + + /** + * Get left + * + * @return int|float + */ + public function getLeft() + { + return $this->left; + } + + /** + * Set left + * + * @param int|float $value + * @return self + */ + public function setLeft($value = null) + { + $this->left = $this->setNumericVal($value, $this->left); + + return $this; + } + + /** + * Get right + * + * @return int|float + */ + public function getRight() + { + return $this->right; + } + + /** + * Set right + * + * @param int|float $value + * @return self + */ + public function setRight($value = null) + { + $this->right = $this->setNumericVal($value, $this->right); + + return $this; + } + + /** + * Get first line + * + * @return int|float + */ + public function getFirstLine() + { + return $this->firstLine; + } + + /** + * Set first line + * + * @param int|float $value + * @return self + */ + public function setFirstLine($value = null) + { + $this->firstLine = $this->setNumericVal($value, $this->firstLine); + + return $this; + } + + /** + * Get hanging + * + * @return int|float + */ + public function getHanging() + { + return $this->hanging; + } + + /** + * Set hanging + * + * @param int|float $value + * @return self + */ + public function setHanging($value = null) + { + $this->hanging = $this->setNumericVal($value, $this->hanging); + + return $this; + } +} diff --git a/src/PhpWord/Style/Line.php b/src/PhpWord/Style/Line.php new file mode 100644 index 00000000..44f54229 --- /dev/null +++ b/src/PhpWord/Style/Line.php @@ -0,0 +1,280 @@ +flip; + } + + /** + * Set flip + * + * @param boolean $value + * @return self + */ + public function setFlip($value = false) + { + $this->flip = $this->setBoolVal($value, $this->flip); + + return $this; + } + + /** + * Get connectorType + * + * @return string + */ + public function getConnectorType() + { + return $this->connectorType; + } + + /** + * Set connectorType + * + * @param string $value + * @return self + */ + public function setConnectorType($value = null) + { + $enum = array( + self::CONNECTOR_TYPE_STRAIGHT + ); + $this->connectorType = $this->setEnumVal($value, $enum, $this->connectorType); + + return $this; + } + + /** + * Get weight + * + * @return int + */ + public function getWeight() + { + return $this->weight; + } + + /** + * Set weight + * + * @param int $value Weight in points + * @return self + */ + public function setWeight($value = null) + { + $this->weight = $this->setNumericVal($value, $this->weight); + + return $this; + } + + /** + * Get color + * + * @return string + */ + public function getColor() + { + return $this->color; + } + + /** + * Set color + * + * @param string $value + * @return self + */ + public function setColor($value = null) + { + $this->color = $value; + + return $this; + } + + /** + * Get beginArrow + * + * @return string + */ + public function getBeginArrow() + { + return $this->beginArrow; + } + + /** + * Set beginArrow + * + * @param string $value + * @return self + */ + public function setBeginArrow($value = null) + { + $enum = array( + self::ARROW_STYLE_BLOCK, self::ARROW_STYLE_CLASSIC, self::ARROW_STYLE_DIAMOND, + self::ARROW_STYLE_OPEN, self::ARROW_STYLE_OVAL + ); + $this->beginArrow = $this->setEnumVal($value, $enum, $this->beginArrow); + + return $this; + } + + /** + * Get endArrow + * + * @return string + */ + public function getEndArrow() + { + return $this->endArrow; + } + + /** + * Set endArrow + * + * @param string $value + * @return self + */ + public function setEndArrow($value = null) + { + $enum = array( + self::ARROW_STYLE_BLOCK, self::ARROW_STYLE_CLASSIC, self::ARROW_STYLE_DIAMOND, + self::ARROW_STYLE_OPEN, self::ARROW_STYLE_OVAL + ); + $this->endArrow = $this->setEnumVal($value, $enum, $this->endArrow); + + return $this; + } + + /** + * Get Dash + * + * @return string + */ + public function getDash() + { + return $this->dash; + } + + /** + * Set Dash + * + * @param string $value + * @return self + */ + public function setDash($value = null) + { + $enum = array( + self::DASH_STYLE_DASH, self::DASH_STYLE_DASH_DOT, self::DASH_STYLE_LONG_DASH, + self::DASH_STYLE_LONG_DASH_DOT, self::DASH_STYLE_LONG_DASH_DOT_DOT, self::DASH_STYLE_ROUND_DOT, + self::DASH_STYLE_SQUARE_DOT + ); + $this->dash = $this->setEnumVal($value, $enum, $this->dash); + + return $this; + } +} diff --git a/src/PhpWord/Style/LineNumbering.php b/src/PhpWord/Style/LineNumbering.php new file mode 100644 index 00000000..b93ce03f --- /dev/null +++ b/src/PhpWord/Style/LineNumbering.php @@ -0,0 +1,164 @@ +setStyleByArray($style); + } + + /** + * Get start + * + * @return int + */ + public function getStart() + { + return $this->start; + } + + /** + * Set start + * + * @param int $value + * @return self + */ + public function setStart($value = null) + { + $this->start = $this->setIntVal($value, $this->start); + + return $this; + } + + /** + * Get increment + * + * @return int + */ + public function getIncrement() + { + return $this->increment; + } + + /** + * Set increment + * + * @param int $value + * @return self + */ + public function setIncrement($value = null) + { + $this->increment = $this->setIntVal($value, $this->increment); + + return $this; + } + + /** + * Get distance + * + * @return int|float + */ + public function getDistance() + { + return $this->distance; + } + + /** + * Set distance + * + * @param int|float $value + * @return self + */ + public function setDistance($value = null) + { + $this->distance = $this->setNumericVal($value, $this->distance); + + return $this; + } + + /** + * Get restart + * + * @return string + */ + public function getRestart() + { + return $this->restart; + } + + /** + * Set distance + * + * @param string $value + * @return self + */ + public function setRestart($value = null) + { + $enum = array(self::LINE_NUMBERING_CONTINUOUS, self::LINE_NUMBERING_NEW_PAGE, self::LINE_NUMBERING_NEW_SECTION); + $this->restart = $this->setEnumVal($value, $enum, $this->restart); + + return $this; + } +} diff --git a/src/PhpWord/Style/ListItem.php b/src/PhpWord/Style/ListItem.php index a4f4933d..a689c691 100644 --- a/src/PhpWord/Style/ListItem.php +++ b/src/PhpWord/Style/ListItem.php @@ -1,10 +1,18 @@ setNumStyle($numStyle); } else { $this->setListType(); @@ -78,14 +86,19 @@ class ListItem extends AbstractStyle * Set legacy list type for version < 0.10.0 * * @param integer $value + * @return self */ public function setListType($value = self::TYPE_BULLET_FILLED) { - $enum = array(self::TYPE_SQUARE_FILLED, self::TYPE_BULLET_FILLED, + $enum = array( + self::TYPE_SQUARE_FILLED, self::TYPE_BULLET_FILLED, self::TYPE_BULLET_EMPTY, self::TYPE_NUMBER, - self::TYPE_NUMBER_NESTED, self::TYPE_ALPHANUM); + self::TYPE_NUMBER_NESTED, self::TYPE_ALPHANUM + ); $this->listType = $this->setEnumVal($value, $enum, $this->listType); $this->getListTypeStyle(); + + return $this; } /** @@ -102,6 +115,7 @@ class ListItem extends AbstractStyle * Set numbering style name * * @param string $value + * @return self */ public function setNumStyle($value) { @@ -111,6 +125,8 @@ class ListItem extends AbstractStyle $this->numId = $numStyleObject->getIndex(); $numStyleObject->setNumId($this->numId); } + + return $this; } /** @@ -133,7 +149,7 @@ class ListItem extends AbstractStyle { // Check if legacy style already registered in global Style collection $numStyle = "PHPWordList{$this->listType}"; - if (!is_null(Style::getStyle($numStyle))) { + if (Style::getStyle($numStyle) !== null) { $this->setNumStyle($numStyle); return; } diff --git a/src/PhpWord/Style/Numbering.php b/src/PhpWord/Style/Numbering.php index 8c2e4a69..726af2be 100644 --- a/src/PhpWord/Style/Numbering.php +++ b/src/PhpWord/Style/Numbering.php @@ -1,16 +1,22 @@ numId = $this->setIntVal($value, $this->numId); + return $this; } @@ -86,6 +93,7 @@ class Numbering extends AbstractStyle { $enum = array('singleLevel', 'multilevel', 'hybridMultilevel'); $this->type = $this->setEnumVal($value, $enum, $this->type); + return $this; } diff --git a/src/PhpWord/Style/NumberingLevel.php b/src/PhpWord/Style/NumberingLevel.php index dff7de22..32e61c89 100644 --- a/src/PhpWord/Style/NumberingLevel.php +++ b/src/PhpWord/Style/NumberingLevel.php @@ -1,10 +1,18 @@ pStyle; + } + + /** + * Set related paragraph style + * + * @param string $value + * @return self + */ + public function setPStyle($value) + { + $this->pStyle = $value; + return $this; + } + /** * Get suffix * @@ -369,10 +407,11 @@ class NumberingLevel extends AbstractStyle * @param string $value * @return self */ - public function setHint($value) + public function setHint($value = null) { $enum = array('default', 'eastAsia', 'cs'); $this->hint = $this->setEnumVal($value, $enum, $this->hint); + return $this; } } diff --git a/src/PhpWord/Style/Outline.php b/src/PhpWord/Style/Outline.php new file mode 100644 index 00000000..bfd14a14 --- /dev/null +++ b/src/PhpWord/Style/Outline.php @@ -0,0 +1,308 @@ +setStyleByArray($style); + } + + /** + * Get unit + * + * @return string + */ + public function getUnit() + { + return $this->unit; + } + + /** + * Get weight + * + * @return int|float + */ + public function getWeight() + { + return $this->weight; + } + + /** + * Set weight + * + * @param int|float $value + * @return self + */ + public function setWeight($value = null) + { + $this->weight = $this->setNumericVal($value, null); + + return $this; + } + + /** + * Get color + * + * @return string + */ + public function getColor() + { + return $this->color; + } + + /** + * Set color + * + * @param string $value + * @return self + */ + public function setColor($value = null) + { + $this->color = $value; + + return $this; + } + + /** + * Get dash type + * + * @return string + */ + public function getDash() + { + return $this->dash; + } + + /** + * Set dash type + * + * @param string $value + * @return self + */ + public function setDash($value = null) + { + $this->dash = $value; + + return $this; + } + + /** + * Get line style + * + * @return string + */ + public function getLine() + { + return $this->line; + } + + /** + * Set line style + * + * @param string $value + * @return self + */ + public function setLine($value = null) + { + $enum = array(self::LINE_SINGLE, self::LINE_THIN_THIN, self::LINE_THIN_THICK, + self::LINE_THICK_THIN, self::LINE_THICK_BETWEEN_THIN); + $this->line = $this->setEnumVal($value, $enum, null); + + return $this; + } + + /** + * Get endCap style + * + * @return string + */ + public function getEndCap() + { + return $this->endCap; + } + + /** + * Set endCap style + * + * @param string $value + * @return self + */ + public function setEndCap($value = null) + { + $enum = array(self::ENDCAP_FLAT, self::ENDCAP_SQUARE, self::ENDCAP_ROUND); + $this->endCap = $this->setEnumVal($value, $enum, null); + + return $this; + } + + /** + * Get startArrow + * + * @return string + */ + public function getStartArrow() + { + return $this->startArrow; + } + + /** + * Set pattern + * + * @param string $value + * @return self + */ + public function setStartArrow($value = null) + { + $enum = array(self::ARROW_NONE, self::ARROW_BLOCK, self::ARROW_CLASSIC, + self::ARROW_OVAL, self::ARROW_DIAMOND, self::ARROW_OPEN); + $this->startArrow = $this->setEnumVal($value, $enum, null); + + return $this; + } + + /** + * Get endArrow + * + * @return string + */ + public function getEndArrow() + { + return $this->endArrow; + } + + /** + * Set pattern + * + * @param string $value + * @return self + */ + public function setEndArrow($value = null) + { + $enum = array(self::ARROW_NONE, self::ARROW_BLOCK, self::ARROW_CLASSIC, + self::ARROW_OVAL, self::ARROW_DIAMOND, self::ARROW_OPEN); + $this->endArrow = $this->setEnumVal($value, $enum, null); + + return $this; + } +} diff --git a/src/PhpWord/Style/Paper.php b/src/PhpWord/Style/Paper.php new file mode 100644 index 00000000..642666b5 --- /dev/null +++ b/src/PhpWord/Style/Paper.php @@ -0,0 +1,188 @@ + array(297, 420, 'mm'), + 'A4' => array(210, 297, 'mm'), + 'A5' => array(148, 210, 'mm'), + 'Folio' => array(8.5, 13, 'in'), + 'Legal' => array(8.5, 14, 'in'), + 'Letter' => array(8.5, 11, 'in'), + ); + + /** + * Paper size + * + * @var string + */ + private $size = 'A4'; + + /** + * Width + * + * @var int (twip) + */ + private $width; + + /** + * Height + * + * @var int (twip) + */ + private $height; + + /** + * Create a new instance + * + * @param string $size + */ + public function __construct($size = 'A4') + { + $this->setSize($size); + } + + /** + * Get size + * + * @return string + */ + public function getSize() + { + return $this->size; + } + + /** + * Set size + * + * @param string $size + * @return self + */ + public function setSize($size) + { + $this->size = $this->setEnumVal($size, array_keys($this->sizes), $this->size); + + list($width, $height, $unit) = $this->sizes[$this->size]; + $multipliers = array('mm' => 56.5217, 'in' => 1440); + $multiplier = $multipliers[$unit]; + + $this->width = (int)round($width * $multiplier); + $this->height = (int)round($height * $multiplier); + + return $this; + } + + /** + * Get width + * + * @return int + */ + public function getWidth() + { + return $this->width; + } + + /** + * Get height + * + * @return int + */ + public function getHeight() + { + return $this->height; + } +} diff --git a/src/PhpWord/Style/Paragraph.php b/src/PhpWord/Style/Paragraph.php old mode 100755 new mode 100644 index 57ad4405..964a4ec9 --- a/src/PhpWord/Style/Paragraph.php +++ b/src/PhpWord/Style/Paragraph.php @@ -1,10 +1,18 @@ 'lineHeight'); /** * Parent style @@ -89,6 +75,34 @@ class Paragraph extends AbstractStyle */ private $next; + /** + * Alignment + * + * @var \PhpOffice\PhpWord\Style\Alignment + */ + private $alignment; + + /** + * Indentation + * + * @var \PhpOffice\PhpWord\Style\Indentation + */ + private $indentation; + + /** + * Spacing + * + * @var \PhpOffice\PhpWord\Style\Spacing + */ + private $spacing; + + /** + * Text line height + * + * @var int + */ + private $lineHeight; + /** * Allow first/last line to display on a separate page * @@ -118,21 +132,39 @@ class Paragraph extends AbstractStyle private $pageBreakBefore = false; /** - * Set style by array + * Numbering style name * - * @param array $style - * @return $this + * @var string */ - public function setArrayStyle(array $style = array()) - { - foreach ($style as $key => $value) { - if ($key === 'line-height') { - null; - } - $this->setStyleValue($key, $value); - } + private $numStyle; - return $this; + /** + * Numbering level + * + * @var int + */ + private $numLevel = 0; + + /** + * Set of Custom Tab Stops + * + * @var \PhpOffice\PhpWord\Style\Tab[] + */ + private $tabs = array(); + + /** + * Shading + * + * @var \PhpOffice\PhpWord\Style\Shading + */ + private $shading; + + /** + * Create new instance + */ + public function __construct() + { + $this->alignment = new Alignment(); } /** @@ -140,6 +172,7 @@ class Paragraph extends AbstractStyle * * @param string $key * @param mixed $value + * @return self */ public function setStyleValue($key, $value) { @@ -148,180 +181,74 @@ class Paragraph extends AbstractStyle $value = $value * 720; } elseif ($key == 'spacing') { $value += 240; // because line height of 1 matches 240 twips - } elseif ($key === 'line-height') { - $this->setLineHeight($value); - return; - } - $method = 'set' . $key; - if (method_exists($this, $method)) { - $this->$method($value); } + + return parent::setStyleValue($key, $value); } /** - * Get Paragraph Alignment + * Get style values + * + * An experiment to retrieve all style values in one function. This will + * reduce function call and increase cohesion between functions. Should be + * implemented in all styles. + * + * @ignoreScrutinizerPatch + * @return array + */ + public function getStyleValues() + { + $styles = array( + 'name' => $this->getStyleName(), + 'basedOn' => $this->getBasedOn(), + 'next' => $this->getNext(), + 'alignment' => $this->getAlign(), + 'indentation' => $this->getIndentation(), + 'spacing' => $this->getSpace(), + 'pagination' => array( + 'widowControl' => $this->hasWidowControl(), + 'keepNext' => $this->isKeepNext(), + 'keepLines' => $this->isKeepLines(), + 'pageBreak' => $this->hasPageBreakBefore(), + ), + 'numbering' => array( + 'style' => $this->getNumStyle(), + 'level' => $this->getNumLevel(), + ), + 'tabs' => $this->getTabs(), + 'shading' => $this->getShading(), + ); + + return $styles; + } + + /** + * Get alignment * * @return string */ public function getAlign() { - return $this->align; + return $this->alignment->getValue(); } /** - * Set Paragraph Alignment + * Set alignment * - * @param string $pValue - * @return \PhpOffice\PhpWord\Style\Paragraph + * @param string $value + * @return self */ - public function setAlign($pValue = null) + public function setAlign($value = null) { - if (strtolower($pValue) == 'justify') { - // justify becames both - $pValue = 'both'; - } - $this->align = $pValue; - return $this; - } + $this->alignment->setValue($value); - /** - * Get Space before Paragraph - * - * @return integer - */ - public function getSpaceBefore() - { - return $this->spaceBefore; - } - - /** - * Set Space before Paragraph - * - * @param int $pValue - * @return \PhpOffice\PhpWord\Style\Paragraph - */ - public function setSpaceBefore($pValue = null) - { - $this->spaceBefore = $pValue; - return $this; - } - - /** - * Get Space after Paragraph - * - * @return integer - */ - public function getSpaceAfter() - { - return $this->spaceAfter; - } - - /** - * Set Space after Paragraph - * - * @param int $pValue - * @return \PhpOffice\PhpWord\Style\Paragraph - */ - public function setSpaceAfter($pValue = null) - { - $this->spaceAfter = $pValue; - return $this; - } - - /** - * Get Spacing between breaks - * - * @return int - */ - public function getSpacing() - { - return $this->spacing; - } - - /** - * Set Spacing between breaks - * - * @param int $pValue - * @return \PhpOffice\PhpWord\Style\Paragraph - */ - public function setSpacing($pValue = null) - { - $this->spacing = $pValue; - return $this; - } - - /** - * Get indentation - * - * @return int - */ - public function getIndent() - { - return $this->indent; - } - - /** - * Set indentation - * - * @param int $pValue - * @return \PhpOffice\PhpWord\Style\Paragraph - */ - public function setIndent($pValue = null) - { - $this->indent = $pValue; - return $this; - } - - /** - * Get hanging - * - * @return int - */ - public function getHanging() - { - return $this->hanging; - } - - /** - * Set hanging - * - * @param int $pValue - * @return \PhpOffice\PhpWord\Style\Paragraph - */ - public function setHanging($pValue = null) - { - $this->hanging = $pValue; - return $this; - } - - /** - * Get tabs - * - * @return \PhpOffice\PhpWord\Style\Tabs - */ - public function getTabs() - { - return $this->tabs; - } - - /** - * Set tabs - * - * @param array $pValue - * @return \PhpOffice\PhpWord\Style\Paragraph - */ - public function setTabs($pValue = null) - { - if (is_array($pValue)) { - $this->tabs = new Tabs($pValue); - } return $this; } /** * Get parent style ID * - * @return string + * @return string */ public function getBasedOn() { @@ -331,12 +258,13 @@ class Paragraph extends AbstractStyle /** * Set parent style ID * - * @param string $pValue - * @return \PhpOffice\PhpWord\Style\Paragraph + * @param string $value + * @return self */ - public function setBasedOn($pValue = 'Normal') + public function setBasedOn($value = 'Normal') { - $this->basedOn = $pValue; + $this->basedOn = $value; + return $this; } @@ -353,120 +281,184 @@ class Paragraph extends AbstractStyle /** * Set style for next paragraph * - * @param string $pValue - * @return \PhpOffice\PhpWord\Style\Paragraph + * @param string $value + * @return self */ - public function setNext($pValue = null) + public function setNext($value = null) { - $this->next = $pValue; + $this->next = $value; + return $this; } /** - * Get allow first/last line to display on a separate page setting + * Get shading * - * @return bool + * @return \PhpOffice\PhpWord\Style\Indentation */ - public function getWidowControl() + public function getIndentation() { - return $this->widowControl; + return $this->indentation; } /** - * Set keep paragraph with next paragraph setting + * Set shading * - * @param bool $pValue - * @return \PhpOffice\PhpWord\Style\Paragraph + * @param mixed $value + * @return self */ - public function setWidowControl($pValue = true) + public function setIndentation($value = null) { - if (!is_bool($pValue)) { - $pValue = true; - } - $this->widowControl = $pValue; + $this->setObjectVal($value, 'Indentation', $this->indentation); + return $this; } /** - * Get keep paragraph with next paragraph setting + * Get indentation * - * @return bool + * @return int */ - public function getKeepNext() + public function getIndent() { - return $this->keepNext; + return $this->getChildStyleValue($this->indentation, 'left'); } /** - * Set keep paragraph with next paragraph setting + * Set indentation * - * @param bool $pValue - * @return \PhpOffice\PhpWord\Style\Paragraph + * @param int $value + * @return self */ - public function setKeepNext($pValue = false) + public function setIndent($value = null) { - if (!is_bool($pValue)) { - $pValue = false; - } - $this->keepNext = $pValue; + return $this->setIndentation(array('left' => $value)); + } + + /** + * Get hanging + * + * @return int + */ + public function getHanging() + { + return $this->getChildStyleValue($this->indentation, 'hanging'); + } + + /** + * Set hanging + * + * @param int $value + * @return self + */ + public function setHanging($value = null) + { + return $this->setIndentation(array('hanging' => $value)); + } + + /** + * Get spacing + * + * @return \PhpOffice\PhpWord\Style\Spacing + * @todo Rename to getSpacing in 1.0 + */ + public function getSpace() + { + return $this->spacing; + } + + /** + * Set spacing + * + * @param mixed $value + * @return self + * @todo Rename to setSpacing in 1.0 + */ + public function setSpace($value = null) + { + $this->setObjectVal($value, 'Spacing', $this->spacing); + return $this; } /** - * Get keep all lines on one page setting + * Get space before paragraph * - * @return bool + * @return integer */ - public function getKeepLines() + public function getSpaceBefore() { - return $this->keepLines; + return $this->getChildStyleValue($this->spacing, 'before'); } /** - * Set keep all lines on one page setting + * Set space before paragraph * - * @param bool $pValue - * @return \PhpOffice\PhpWord\Style\Paragraph + * @param int $value + * @return self */ - public function setKeepLines($pValue = false) + public function setSpaceBefore($value = null) { - if (!is_bool($pValue)) { - $pValue = false; - } - $this->keepLines = $pValue; - return $this; + return $this->setSpace(array('before' => $value)); } /** - * Get start paragraph on next page setting + * Get space after paragraph * - * @return bool + * @return integer */ - public function getPageBreakBefore() + public function getSpaceAfter() { - return $this->pageBreakBefore; + return $this->getChildStyleValue($this->spacing, 'after'); } /** - * Set start paragraph on next page setting + * Set space after paragraph * - * @param bool $pValue - * @return \PhpOffice\PhpWord\Style\Paragraph + * @param int $value + * @return self */ - public function setPageBreakBefore($pValue = false) + public function setSpaceAfter($value = null) { - if (!is_bool($pValue)) { - $pValue = false; - } - $this->pageBreakBefore = $pValue; - return $this; + return $this->setSpace(array('after' => $value)); + } + + /** + * Get spacing between lines + * + * @return int + */ + public function getSpacing() + { + return $this->getChildStyleValue($this->spacing, 'line'); + } + + /** + * Set spacing between lines + * + * @param int $value + * @return self + */ + public function setSpacing($value = null) + { + return $this->setSpace(array('line' => $value)); + } + + /** + * Get line height + * + * @return int|float + */ + public function getLineHeight() + { + return $this->lineHeight; } /** * Set the line height * * @param int|float|string $lineHeight - * @return $this + * @return self * @throws \PhpOffice\PhpWord\Exception\InvalidStyleException */ public function setLineHeight($lineHeight) @@ -485,12 +477,232 @@ class Paragraph extends AbstractStyle } /** - * Get line height + * Get allow first/last line to display on a separate page setting * - * @return int|float + * @return bool */ - public function getLineHeight() + public function hasWidowControl() { - return $this->lineHeight; + return $this->widowControl; + } + + /** + * Set keep paragraph with next paragraph setting + * + * @param bool $value + * @return self + */ + public function setWidowControl($value = true) + { + $this->widowControl = $this->setBoolVal($value, $this->widowControl); + + return $this; + } + + /** + * Get keep paragraph with next paragraph setting + * + * @return bool + */ + public function isKeepNext() + { + return $this->keepNext; + } + + /** + * Set keep paragraph with next paragraph setting + * + * @param bool $value + * @return self + */ + public function setKeepNext($value = true) + { + $this->keepNext = $this->setBoolVal($value, $this->keepNext); + + return $this; + } + + /** + * Get keep all lines on one page setting + * + * @return bool + */ + public function isKeepLines() + { + return $this->keepLines; + } + + /** + * Set keep all lines on one page setting + * + * @param bool $value + * @return self + */ + public function setKeepLines($value = true) + { + $this->keepLines = $this->setBoolVal($value, $this->keepLines); + + return $this; + } + + /** + * Get start paragraph on next page setting + * + * @return bool + */ + public function hasPageBreakBefore() + { + return $this->pageBreakBefore; + } + + /** + * Set start paragraph on next page setting + * + * @param bool $value + * @return self + */ + public function setPageBreakBefore($value = true) + { + $this->pageBreakBefore = $this->setBoolVal($value, $this->pageBreakBefore); + + return $this; + } + + /** + * Get numbering style name + * + * @return string + */ + public function getNumStyle() + { + return $this->numStyle; + } + + /** + * Set numbering style name + * + * @param string $value + * @return self + */ + public function setNumStyle($value) + { + $this->numStyle = $value; + + return $this; + } + + /** + * Get numbering level + * + * @return int + */ + public function getNumLevel() + { + return $this->numLevel; + } + + /** + * Set numbering level + * + * @param int $value + * @return self + */ + public function setNumLevel($value = 0) + { + $this->numLevel = $this->setIntVal($value, $this->numLevel); + + return $this; + } + + /** + * Get tabs + * + * @return \PhpOffice\PhpWord\Style\Tab[] + */ + public function getTabs() + { + return $this->tabs; + } + + /** + * Set tabs + * + * @param array $value + * @return self + */ + public function setTabs($value = null) + { + if (is_array($value)) { + $this->tabs = $value; + } + + return $this; + } + + /** + * Get allow first/last line to display on a separate page setting + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getWidowControl() + { + return $this->hasWidowControl(); + } + + /** + * Get keep paragraph with next paragraph setting + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getKeepNext() + { + return $this->isKeepNext(); + } + + /** + * Get keep all lines on one page setting + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getKeepLines() + { + return $this->isKeepLines(); + } + + /** + * Get start paragraph on next page setting + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getPageBreakBefore() + { + return $this->hasPageBreakBefore(); + } + + /** + * Get shading + * + * @return \PhpOffice\PhpWord\Style\Shading + */ + public function getShading() + { + return $this->shading; + } + + /** + * Set shading + * + * @param mixed $value + * @return self + */ + public function setShading($value = null) + { + $this->setObjectVal($value, 'Shading', $this->shading); + + return $this; } } diff --git a/src/PhpWord/Style/Row.php b/src/PhpWord/Style/Row.php index 698adea4..45897aed 100644 --- a/src/PhpWord/Style/Row.php +++ b/src/PhpWord/Style/Row.php @@ -1,16 +1,26 @@ tblHeader = $this->setBoolVal($value, $this->tblHeader); - } - - /** - * Get tblHeader - * - * @return boolean - */ - public function getTblHeader() + public function isTblHeader() { return $this->tblHeader; } /** - * Set cantSplit + * Is tblHeader * - * @param boolean $value + * @param bool $value * @return self */ - public function setCantSplit($value = false) + public function setTblHeader($value = true) { - $this->cantSplit = $this->setBoolVal($value, $this->cantSplit); + $this->tblHeader = $this->setBoolVal($value, $this->tblHeader); + + return $this; } /** - * Get cantSplit + * Is cantSplit * - * @return boolean + * @return bool */ - public function getCantSplit() + public function isCantSplit() { return $this->cantSplit; } + /** + * Is cantSplit + * + * @param bool $value + * @return self + */ + public function setCantSplit($value = true) + { + $this->cantSplit = $this->setBoolVal($value, $this->cantSplit); + + return $this; + } + + /** + * Is exactHeight + * + * @return bool + */ + public function isExactHeight() + { + return $this->exactHeight; + } + /** * Set exactHeight * * @param bool $value * @return self */ - public function setExactHeight($value = false) + public function setExactHeight($value = true) { $this->exactHeight = $this->setBoolVal($value, $this->exactHeight); + return $this; } + /** + * Get tblHeader + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getTblHeader() + { + return $this->isTblHeader(); + } + + /** + * Get cantSplit + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getCantSplit() + { + return $this->isCantSplit(); + } + /** * Get exactHeight * - * @return boolean + * @deprecated 0.10.0 + * @codeCoverageIgnore */ public function getExactHeight() { - return $this->exactHeight; + return $this->isExactHeight(); } } diff --git a/src/PhpWord/Style/Section.php b/src/PhpWord/Style/Section.php index 717fdaf7..c56b0a19 100644 --- a/src/PhpWord/Style/Section.php +++ b/src/PhpWord/Style/Section.php @@ -1,139 +1,127 @@ orientation = null; - $this->marginTop = 1418; - $this->marginLeft = 1418; - $this->marginRight = 1418; - $this->marginBottom = 1134; - $this->pageSizeW = $this->defaultPageSizeW; - $this->pageSizeH = $this->defaultPageSizeH; - $this->borderTopSize = null; - $this->borderTopColor = null; - $this->borderLeftSize = null; - $this->borderLeftColor = null; - $this->borderRightSize = null; - $this->borderRightColor = null; - $this->borderBottomSize = null; - $this->borderBottomColor = null; - $this->headerHeight = 720; // set default header and footer to 720 twips (.5 inches) - $this->footerHeight = 720; - $this->colsNum = 1; - $this->colsSpace = 720; - $this->breakType = null; + $this->setPaperSize(); + } + + /** + * Get paper size + * + * @return string + */ + public function getPaperSize() + { + return $this->paper->getSize(); + } + + /** + * Set paper size + * + * @param string $value + * @return self + */ + public function setPaperSize($value = 'A4') + { + if ($this->paper === null) { + $this->paper = new Paper(); + } + $this->paper->setSize($value); + $this->pageSizeW = $this->paper->getWidth(); + $this->pageSizeH = $this->paper->getHeight(); + + return $this; } /** @@ -216,150 +207,41 @@ class Section extends AbstractStyle * * @param string $key * @param string $value + * @return self */ public function setSettingValue($key, $value) { - $key = String::removeUnderscorePrefix($key); - if ($key == 'orientation' && $value == 'landscape') { - $this->setLandscape(); - } elseif ($key == 'orientation' && is_null($value)) { - $this->setPortrait(); - } elseif ($key == 'borderSize') { - $this->setBorderSize($value); - } elseif ($key == 'borderColor') { - $this->setBorderColor($value); + return $this->setStyleValue($key, $value); + } + + /** + * Set orientation + * + * @param string $value + * @return self + */ + public function setOrientation($value = null) + { + $enum = array(self::ORIENTATION_PORTRAIT, self::ORIENTATION_LANDSCAPE); + $this->orientation = $this->setEnumVal($value, $enum, $this->orientation); + + /** @var int|float $longSide Type hint */ + $longSide = $this->pageSizeW >= $this->pageSizeH ? $this->pageSizeW : $this->pageSizeH; + + /** @var int|float $shortSide Type hint */ + $shortSide = $this->pageSizeW < $this->pageSizeH ? $this->pageSizeW : $this->pageSizeH; + + if ($this->orientation == self::ORIENTATION_PORTRAIT) { + $this->pageSizeW = $shortSide; + $this->pageSizeH = $longSide; } else { - $method = 'set' . $key; - if (method_exists($this, $method)) { - $this->$method($value); - } + $this->pageSizeW = $longSide; + $this->pageSizeH = $shortSide; } - } - /** - * Get Margin Top - * - * @return int - */ - public function getMarginTop() - { - return $this->marginTop; - } - - /** - * Set Margin Top - * - * @param int $pValue - */ - public function setMarginTop($pValue = '') - { - $this->marginTop = $pValue; return $this; } - /** - * Get Margin Left - * - * @return int - */ - public function getMarginLeft() - { - return $this->marginLeft; - } - - /** - * Set Margin Left - * - * @param int $pValue - */ - public function setMarginLeft($pValue = '') - { - $this->marginLeft = $pValue; - return $this; - } - - /** - * Get Margin Right - * - * @return int - */ - public function getMarginRight() - { - return $this->marginRight; - } - - /** - * Set Margin Right - * - * @param int $pValue - */ - public function setMarginRight($pValue = '') - { - $this->marginRight = $pValue; - return $this; - } - - /** - * Get Margin Bottom - * - * @return int - */ - public function getMarginBottom() - { - return $this->marginBottom; - } - - /** - * Set Margin Bottom - * - * @param int $pValue - */ - public function setMarginBottom($pValue = '') - { - $this->marginBottom = $pValue; - return $this; - } - - /** - * Set Landscape Orientation - */ - public function setLandscape() - { - $this->orientation = 'landscape'; - $this->pageSizeW = $this->defaultPageSizeH; - $this->pageSizeH = $this->defaultPageSizeW; - } - - /** - * Set Portrait Orientation - */ - public function setPortrait() - { - $this->orientation = null; - $this->pageSizeW = $this->defaultPageSizeW; - $this->pageSizeH = $this->defaultPageSizeH; - } - - /** - * Get Page Size Width - * - * @return int - */ - public function getPageSizeW() - { - return $this->pageSizeW; - } - - /** - * Get Page Size Height - * - * @return int - */ - public function getPageSizeH() - { - return $this->pageSizeH; - } - /** * Get Page Orientation * @@ -371,230 +253,203 @@ class Section extends AbstractStyle } /** - * Set Border Size + * Set Portrait Orientation * - * @param int $pValue + * @return self */ - public function setBorderSize($pValue = null) + public function setPortrait() { - $this->borderTopSize = $pValue; - $this->borderLeftSize = $pValue; - $this->borderRightSize = $pValue; - $this->borderBottomSize = $pValue; + return $this->setOrientation(self::ORIENTATION_PORTRAIT); } /** - * Get Border Size + * Set Landscape Orientation * - * @return array + * @return self */ - public function getBorderSize() + public function setLandscape() { - $t = $this->getBorderTopSize(); - $l = $this->getBorderLeftSize(); - $r = $this->getBorderRightSize(); - $b = $this->getBorderBottomSize(); - - return array($t, $l, $r, $b); + return $this->setOrientation(self::ORIENTATION_LANDSCAPE); } /** - * Set Border Color + * Get Page Size Width * - * @param string $pValue + * @return int|float */ - public function setBorderColor($pValue = null) + public function getPageSizeW() { - $this->borderTopColor = $pValue; - $this->borderLeftColor = $pValue; - $this->borderRightColor = $pValue; - $this->borderBottomColor = $pValue; + return $this->pageSizeW; } /** - * Get Border Color + * Get Page Size Height * - * @return array + * @return int|float */ - public function getBorderColor() + public function getPageSizeH() { - $t = $this->getBorderTopColor(); - $l = $this->getBorderLeftColor(); - $r = $this->getBorderRightColor(); - $b = $this->getBorderBottomColor(); - - return array($t, $l, $r, $b); + return $this->pageSizeH; } /** - * Set Border Top Size + * Get Margin Top * - * @param int $pValue + * @return int|float */ - public function setBorderTopSize($pValue = null) + public function getMarginTop() { - $this->borderTopSize = $pValue; + return $this->marginTop; } /** - * Get Border Top Size + * Set Margin Top * - * @return int + * @param int|float $value + * @return self */ - public function getBorderTopSize() + public function setMarginTop($value = null) { - return $this->borderTopSize; + $this->marginTop = $this->setNumericVal($value, self::DEFAULT_MARGIN); + + return $this; } /** - * Set Border Top Color + * Get Margin Left * - * @param string $pValue + * @return int|float */ - public function setBorderTopColor($pValue = null) + public function getMarginLeft() { - $this->borderTopColor = $pValue; + return $this->marginLeft; } /** - * Get Border Top Color + * Set Margin Left * - * @return string + * @param int|float $value + * @return self */ - public function getBorderTopColor() + public function setMarginLeft($value = null) { - return $this->borderTopColor; + $this->marginLeft = $this->setNumericVal($value, self::DEFAULT_MARGIN); + + return $this; } /** - * Set Border Left Size + * Get Margin Right * - * @param int $pValue + * @return int|float */ - public function setBorderLeftSize($pValue = null) + public function getMarginRight() { - $this->borderLeftSize = $pValue; + return $this->marginRight; } /** - * Get Border Left Size + * Set Margin Right * - * @return int + * @param int|float $value + * @return self */ - public function getBorderLeftSize() + public function setMarginRight($value = null) { - return $this->borderLeftSize; + $this->marginRight = $this->setNumericVal($value, self::DEFAULT_MARGIN); + + return $this; } /** - * Set Border Left Color + * Get Margin Bottom * - * @param string $pValue + * @return int|float */ - public function setBorderLeftColor($pValue = null) + public function getMarginBottom() { - $this->borderLeftColor = $pValue; + return $this->marginBottom; } /** - * Get Border Left Color + * Set Margin Bottom * - * @return string + * @param int|float $value + * @return self */ - public function getBorderLeftColor() + public function setMarginBottom($value = null) { - return $this->borderLeftColor; + $this->marginBottom = $this->setNumericVal($value, self::DEFAULT_MARGIN); + + return $this; } /** - * Set Border Right Size + * Get gutter * - * @param int $pValue + * @return int|float */ - public function setBorderRightSize($pValue = null) + public function getGutter() { - $this->borderRightSize = $pValue; + return $this->gutter; } /** - * Get Border Right Size + * Set gutter * - * @return int + * @param int|float $value + * @return self */ - public function getBorderRightSize() + public function setGutter($value = null) { - return $this->borderRightSize; + $this->gutter = $this->setNumericVal($value, self::DEFAULT_GUTTER); + + return $this; } /** - * Set Border Right Color + * Get Header Height * - * @param string $pValue + * @return int|float */ - public function setBorderRightColor($pValue = null) + public function getHeaderHeight() { - $this->borderRightColor = $pValue; + return $this->headerHeight; } /** - * Get Border Right Color + * Set Header Height * - * @return string + * @param int|float $value + * @return self */ - public function getBorderRightColor() + public function setHeaderHeight($value = null) { - return $this->borderRightColor; + $this->headerHeight = $this->setNumericVal($value, self::DEFAULT_HEADER_HEIGHT); + + return $this; } /** - * Set Border Bottom Size + * Get Footer Height * - * @param int $pValue + * @return int|float */ - public function setBorderBottomSize($pValue = null) + public function getFooterHeight() { - $this->borderBottomSize = $pValue; + return $this->footerHeight; } /** - * Get Border Bottom Size + * Set Footer Height * - * @return int + * @param int|float $value + * @return self */ - public function getBorderBottomSize() + public function setFooterHeight($value = null) { - return $this->borderBottomSize; - } + $this->footerHeight = $this->setNumericVal($value, self::DEFAULT_FOOTER_HEIGHT); - /** - * Set Border Bottom Color - * - * @param string $pValue - */ - public function setBorderBottomColor($pValue = null) - { - $this->borderBottomColor = $pValue; - } - - /** - * Get Border Bottom Color - * - * @return string - */ - public function getBorderBottomColor() - { - return $this->borderBottomColor; - } - - /** - * Set page numbering start - * - * @param null|int $pageNumberingStart - * @return $this - */ - public function setPageNumberingStart($pageNumberingStart = null) - { - $this->pageNumberingStart = $pageNumberingStart; return $this; } @@ -609,64 +464,14 @@ class Section extends AbstractStyle } /** - * Get Header Height + * Set page numbering start * - * @return int + * @param null|int $pageNumberingStart + * @return self */ - public function getHeaderHeight() + public function setPageNumberingStart($pageNumberingStart = null) { - return $this->headerHeight; - } - - /** - * Set Header Height - * - * @param int $pValue - */ - public function setHeaderHeight($pValue = '') - { - if (!is_numeric($pValue)) { - $pValue = 720; - } - $this->headerHeight = $pValue; - return $this; - } - - /** - * Get Footer Height - * - * @return int - */ - public function getFooterHeight() - { - return $this->footerHeight; - } - - /** - * Set Footer Height - * - * @param int $pValue - */ - public function setFooterHeight($pValue = '') - { - if (!is_numeric($pValue)) { - $pValue = 720; - } - $this->footerHeight = $pValue; - return $this; - } - - /** - * Set Section Columns Count - * - * @param int $pValue - */ - public function setColsNum($pValue = '') - { - if (!is_numeric($pValue)) { - $pValue = 1; - } - $this->colsNum = $pValue; + $this->pageNumberingStart = $pageNumberingStart; return $this; } @@ -681,23 +486,22 @@ class Section extends AbstractStyle } /** - * Set Section Space Between Columns + * Set Section Columns Count * - * @param int $pValue + * @param int $value + * @return self */ - public function setColsSpace($pValue = '') + public function setColsNum($value = null) { - if (!is_numeric($pValue)) { - $pValue = 720; - } - $this->colsSpace = $pValue; + $this->colsNum = $this->setIntVal($value, self::DEFAULT_COLUMN_COUNT); + return $this; } /** * Get Section Space Between Columns * - * @return int + * @return int|float */ public function getColsSpace() { @@ -705,13 +509,15 @@ class Section extends AbstractStyle } /** - * Set Break Type + * Set Section Space Between Columns * - * @param string $pValue + * @param int|float $value + * @return self */ - public function setBreakType($pValue = null) + public function setColsSpace($value = null) { - $this->breakType = $pValue; + $this->colsSpace = $this->setNumericVal($value, self::DEFAULT_COLUMN_SPACING); + return $this; } @@ -724,4 +530,39 @@ class Section extends AbstractStyle { return $this->breakType; } + + /** + * Set Break Type + * + * @param string $value + * @return self + */ + public function setBreakType($value = null) + { + $this->breakType = $value; + return $this; + } + + /** + * Get line numbering + * + * @return \PhpOffice\PhpWord\Style\LineNumbering + */ + public function getLineNumbering() + { + return $this->lineNumbering; + } + + /** + * Set line numbering + * + * @param mixed $value + * @return self + */ + public function setLineNumbering($value = null) + { + $this->setObjectVal($value, 'LineNumbering', $this->lineNumbering); + + return $this; + } } diff --git a/src/PhpWord/Style/Shading.php b/src/PhpWord/Style/Shading.php new file mode 100644 index 00000000..5c9742c9 --- /dev/null +++ b/src/PhpWord/Style/Shading.php @@ -0,0 +1,146 @@ +setStyleByArray($style); + } + + /** + * Get pattern + * + * @return string + */ + public function getPattern() + { + return $this->pattern; + } + + /** + * Set pattern + * + * @param string $value + * @return self + */ + public function setPattern($value = null) + { + $enum = array( + self::PATTERN_CLEAR, self::PATTERN_SOLID, self::PATTERN_HSTRIPE, + self::PATTERN_VSTRIPE, self::PATTERN_DSTRIPE, self::PATTERN_HCROSS, self::PATTERN_DCROSS + ); + $this->pattern = $this->setEnumVal($value, $enum, $this->pattern); + + return $this; + } + + /** + * Get color + * + * @return string + */ + public function getColor() + { + return $this->color; + } + + /** + * Set pattern + * + * @param string $value + * @return self + */ + public function setColor($value = null) + { + $this->color = $value; + + return $this; + } + + /** + * Get fill + * + * @return string + */ + public function getFill() + { + return $this->fill; + } + + /** + * Set fill + * + * @param string $value + * @return self + */ + public function setFill($value = null) + { + $this->fill = $value; + + return $this; + } +} diff --git a/src/PhpWord/Style/Shadow.php b/src/PhpWord/Style/Shadow.php new file mode 100644 index 00000000..deafbff0 --- /dev/null +++ b/src/PhpWord/Style/Shadow.php @@ -0,0 +1,97 @@ +setStyleByArray($style); + } + + /** + * Get color + * + * @return string + */ + public function getColor() + { + return $this->color; + } + + /** + * Set color + * + * @param string $value + * @return self + */ + public function setColor($value = null) + { + $this->color = $value; + + return $this; + } + + /** + * Get offset + * + * @return string + */ + public function getOffset() + { + return $this->offset; + } + + /** + * Set offset + * + * @param string $value + * @return self + */ + public function setOffset($value = null) + { + $this->offset = $value; + + return $this; + } +} diff --git a/src/PhpWord/Style/Shape.php b/src/PhpWord/Style/Shape.php new file mode 100644 index 00000000..c9809920 --- /dev/null +++ b/src/PhpWord/Style/Shape.php @@ -0,0 +1,255 @@ +setStyleByArray($style); + } + + /** + * Get points + * + * @return string + */ + public function getPoints() + { + return $this->points; + } + + /** + * Set points + * + * @param string $value + * @return self + */ + public function setPoints($value = null) + { + $this->points = $value; + + return $this; + } + + /** + * Get roundness + * + * @return int|float + */ + public function getRoundness() + { + return $this->roundness; + } + + /** + * Set roundness + * + * @param int|float $value + * @return self + */ + public function setRoundness($value = null) + { + $this->roundness = $this->setNumericVal($value, null); + + return $this; + } + + /** + * Get frame + * + * @return \PhpOffice\PhpWord\Style\Frame + */ + public function getFrame() + { + return $this->frame; + } + + /** + * Set frame + * + * @param mixed $value + * @return self + */ + public function setFrame($value = null) + { + $this->setObjectVal($value, 'Frame', $this->frame); + + return $this; + } + + /** + * Get fill + * + * @return \PhpOffice\PhpWord\Style\Fill + */ + public function getFill() + { + return $this->fill; + } + + /** + * Set fill + * + * @param mixed $value + * @return self + */ + public function setFill($value = null) + { + $this->setObjectVal($value, 'Fill', $this->fill); + + return $this; + } + + /** + * Get outline + * + * @return \PhpOffice\PhpWord\Style\Outline + */ + public function getOutline() + { + return $this->outline; + } + + /** + * Set outline + * + * @param mixed $value + * @return self + */ + public function setOutline($value = null) + { + $this->setObjectVal($value, 'Outline', $this->outline); + + return $this; + } + + /** + * Get shadow + * + * @return \PhpOffice\PhpWord\Style\Shadow + */ + public function getShadow() + { + return $this->shadow; + } + + /** + * Set shadow + * + * @param mixed $value + * @return self + */ + public function setShadow($value = null) + { + $this->setObjectVal($value, 'Shadow', $this->shadow); + + return $this; + } + + /** + * Get 3D extrusion + * + * @return \PhpOffice\PhpWord\Style\Extrusion + */ + public function getExtrusion() + { + return $this->extrusion; + } + + /** + * Set 3D extrusion + * + * @param mixed $value + * @return self + */ + public function setExtrusion($value = null) + { + $this->setObjectVal($value, 'Extrusion', $this->extrusion); + + return $this; + } +} diff --git a/src/PhpWord/Style/Spacing.php b/src/PhpWord/Style/Spacing.php new file mode 100644 index 00000000..9c9f3a81 --- /dev/null +++ b/src/PhpWord/Style/Spacing.php @@ -0,0 +1,157 @@ +setStyleByArray($style); + } + + /** + * Get before + * + * @return int|float + */ + public function getBefore() + { + return $this->before; + } + + /** + * Set before + * + * @param int|float $value + * @return self + */ + public function setBefore($value = null) + { + $this->before = $this->setNumericVal($value, $this->before); + + return $this; + } + + /** + * Get after + * + * @return int|float + */ + public function getAfter() + { + return $this->after; + } + + /** + * Set after + * + * @param int|float $value + * @return self + */ + public function setAfter($value = null) + { + $this->after = $this->setNumericVal($value, $this->after); + + return $this; + } + + /** + * Get line + * + * @return int|float + */ + public function getLine() + { + return $this->line; + } + + /** + * Set distance + * + * @param int|float $value + * @return self + */ + public function setLine($value = null) + { + $this->line = $this->setNumericVal($value, $this->line); + + return $this; + } + + /** + * Get line rule + * + * @return string + */ + public function getRule() + { + return $this->rule; + } + + /** + * Set line rule + * + * @param string $value + * @return self + */ + public function setRule($value = null) + { + $this->rule = $value; + + return $this; + } +} diff --git a/src/PhpWord/Style/TOC.php b/src/PhpWord/Style/TOC.php index e8a781b0..52855652 100644 --- a/src/PhpWord/Style/TOC.php +++ b/src/PhpWord/Style/TOC.php @@ -1,10 +1,18 @@ tabPos = 9062; - $this->tabLeader = self::TABLEADER_DOT; - $this->indent = 200; + parent::__construct(self::TAB_STOP_RIGHT, 9062, self::TAB_LEADER_DOT); } /** * Get Tab Position * - * @return int + * @return int|float */ public function getTabPos() { - return $this->tabPos; + return $this->getPosition(); } /** * Set Tab Position * - * @param int $pValue + * @param int|float $value + * @return self */ - public function setTabPos($pValue) + public function setTabPos($value) { - $this->tabPos = $pValue; + return $this->setPosition($value); } /** @@ -78,23 +76,24 @@ class TOC extends AbstractStyle */ public function getTabLeader() { - return $this->tabLeader; + return $this->getLeader(); } /** * Set Tab Leader * - * @param string $pValue + * @param string $value + * @return self */ - public function setTabLeader($pValue = self::TABLEADER_DOT) + public function setTabLeader($value = self::TAB_LEADER_DOT) { - $this->tabLeader = $pValue; + return $this->setLeader($value); } /** * Get Indent * - * @return int + * @return int|float */ public function getIndent() { @@ -104,10 +103,13 @@ class TOC extends AbstractStyle /** * Set Indent * - * @param string $pValue + * @param int|float $value + * @return self */ - public function setIndent($pValue) + public function setIndent($value) { - $this->indent = $pValue; + $this->indent = $this->setNumericVal($value, $this->indent); + + return $this; } } diff --git a/src/PhpWord/Style/Tab.php b/src/PhpWord/Style/Tab.php index e9c044f1..900e1fbd 100644 --- a/src/PhpWord/Style/Tab.php +++ b/src/PhpWord/Style/Tab.php @@ -1,131 +1,173 @@ val = (self::isStopType($val)) ? $val : 'clear'; + $stopTypes = array( + self::TAB_STOP_CLEAR, self::TAB_STOP_LEFT,self::TAB_STOP_CENTER, + self::TAB_STOP_RIGHT, self::TAB_STOP_DECIMAL, self::TAB_STOP_BAR, self::TAB_STOP_NUM + ); + $leaderTypes = array( + self::TAB_LEADER_NONE, self::TAB_LEADER_DOT, self::TAB_LEADER_HYPHEN, + self::TAB_LEADER_UNDERSCORE, self::TAB_LEADER_HEAVY, self::TAB_LEADER_MIDDLEDOT + ); - // Default to 0 if the position is non-numeric - $this->position = (is_numeric($position)) ? intval($position) : 0; - - // Default to null if no tab leader - $this->leader = (self::isLeaderType($leader)) ? $leader : null; + $this->type = $this->setEnumVal($type, $stopTypes, $this->type); + $this->position = $this->setNumericVal($position, $this->position); + $this->leader = $this->setEnumVal($leader, $leaderTypes, $this->leader); } /** - * Creates the XML DOM for the instance of Tab. + * Get stop type * - * @param \PhpOffice\PhpWord\Shared\XMLWriter &$xmlWriter + * @return string */ - public function toXml(XMLWriter &$xmlWriter = null) + public function getType() { - if (isset($xmlWriter)) { - $xmlWriter->startElement("w:tab"); - $xmlWriter->writeAttribute("w:val", $this->val); - if (!is_null($this->leader)) { - $xmlWriter->writeAttribute("w:leader", $this->leader); - } - $xmlWriter->writeAttribute("w:pos", $this->position); - $xmlWriter->endElement(); - } + return $this->type; } /** - * Test if attribute is a valid stop type. + * Set stop type * - * @param string $attribute - * @return bool True if it is; false otherwise. + * @param string $value + * @return self */ - private static function isStopType($attribute) + public function setType($value) { - return in_array($attribute, self::$possibleStopTypes); + $enum = array( + self::TAB_STOP_CLEAR, self::TAB_STOP_LEFT, self::TAB_STOP_CENTER, + self::TAB_STOP_RIGHT, self::TAB_STOP_DECIMAL, self::TAB_STOP_BAR, + self::TAB_STOP_NUM, + ); + $this->type = $this->setEnumVal($value, $enum, $this->type); + + return $this; } /** - * Test if attribute is a valid leader type. + * Get leader * - * @param string $attribute - * @return bool True if it is; false otherwise. + * @return string */ - private static function isLeaderType($attribute) + public function getLeader() { - return in_array($attribute, self::$possibleLeaders); + return $this->leader; + } + + /** + * Set leader + * + * @param string $value + * @return self + */ + public function setLeader($value) + { + $enum = array( + self::TAB_LEADER_NONE, self::TAB_LEADER_DOT, self::TAB_LEADER_HYPHEN, + self::TAB_LEADER_UNDERSCORE, self::TAB_LEADER_HEAVY, self::TAB_LEADER_MIDDLEDOT, + ); + $this->leader = $this->setEnumVal($value, $enum, $this->leader); + + return $this; + } + + /** + * Get position + * + * @return int|float + */ + public function getPosition() + { + return $this->position; + } + + /** + * Set position + * + * @param int|float $value + * @return self + */ + public function setPosition($value) + { + $this->position = $this->setNumericVal($value, $this->position); + + return $this; } } diff --git a/src/PhpWord/Style/Table.php b/src/PhpWord/Style/Table.php old mode 100755 new mode 100644 index 000ecff7..24f50667 --- a/src/PhpWord/Style/Table.php +++ b/src/PhpWord/Style/Table.php @@ -1,118 +1,75 @@ firstRow = clone $this; + $this->alignment = new Alignment(); - unset($this->firstRow->firstRow); - unset($this->firstRow->cellMarginBottom); - unset($this->firstRow->cellMarginTop); - unset($this->firstRow->cellMarginLeft); - unset($this->firstRow->cellMarginRight); - unset($this->firstRow->borderInsideVColor); - unset($this->firstRow->borderInsideVSize); - unset($this->firstRow->borderInsideHColor); - unset($this->firstRow->borderInsideHSize); - foreach ($styleFirstRow as $key => $value) { - $this->firstRow->setStyleValue($key, $value); - } + // Clone first row from table style, but with certain properties disabled + if ($firstRowStyle !== null && is_array($firstRowStyle)) { + $this->firstRowStyle = clone $this; + $this->firstRowStyle->isFirstRow = true; + unset($this->firstRowStyle->firstRowStyle); + unset($this->firstRowStyle->borderInsideHSize); + unset($this->firstRowStyle->borderInsideHColor); + unset($this->firstRowStyle->borderInsideVSize); + unset($this->firstRowStyle->borderInsideVColor); + unset($this->firstRowStyle->cellMarginTop); + unset($this->firstRowStyle->cellMarginLeft); + unset($this->firstRowStyle->cellMarginRight); + unset($this->firstRowStyle->cellMarginBottom); + $this->firstRowStyle->setStyleByArray($firstRowStyle); } - if (!is_null($styleTable) && is_array($styleTable)) { - foreach ($styleTable as $key => $value) { - $this->setStyleValue($key, $value); - } + if ($tableStyle !== null && is_array($tableStyle)) { + $this->setStyleByArray($tableStyle); } } /** - * Set style value - * - * @param string $key - * @param mixed $value - */ - public function setStyleValue($key, $value) - { - $key = String::removeUnderscorePrefix($key); - if ($key == 'borderSize') { - $this->setBorderSize($value); - } elseif ($key == 'borderColor') { - $this->setBorderColor($value); - } elseif ($key == 'cellMargin') { - $this->setCellMargin($value); - } else { - $this->$key = $value; - } - } - - /** - * Get First Row Style + * Set first row * * @return \PhpOffice\PhpWord\Style\Table */ public function getFirstRow() { - return $this->firstRow; + return $this->firstRowStyle; } /** @@ -211,331 +169,178 @@ class Table extends AbstractStyle */ public function getBgColor() { - return $this->bgColor; + if ($this->shading !== null) { + return $this->shading->getFill(); + } + + return null; } /** * Set background * - * @param string $pValue - * @return \PhpOffice\PhpWord\Style\Table + * @param string $value + * @return self */ - public function setBgColor($pValue = null) + public function setBgColor($value = null) { - $this->bgColor = $pValue; + $this->setShading(array('fill' => $value)); + + return $this; } /** - * Set TLRBVH Border Size + * Get TLRBHV Border Size * - * @param int $pValue Border size in eighths of a point (1/8 point) - */ - public function setBorderSize($pValue = null) - { - $this->borderTopSize = $pValue; - $this->borderLeftSize = $pValue; - $this->borderRightSize = $pValue; - $this->borderBottomSize = $pValue; - $this->borderInsideHSize = $pValue; - $this->borderInsideVSize = $pValue; - } - - /** - * Get TLRBVH Border Size - * - * @return array + * @return integer[] */ public function getBorderSize() { - $t = $this->getBorderTopSize(); - $l = $this->getBorderLeftSize(); - $r = $this->getBorderRightSize(); - $b = $this->getBorderBottomSize(); - $h = $this->getBorderInsideHSize(); - $v = $this->getBorderInsideVSize(); - - return array($t, $l, $r, $b, $h, $v); + return array( + $this->getBorderTopSize(), + $this->getBorderLeftSize(), + $this->getBorderRightSize(), + $this->getBorderBottomSize(), + $this->getBorderInsideHSize(), + $this->getBorderInsideVSize(), + ); } /** - * Set TLRBVH Border Color - * @param string $pValue - */ - public function setBorderColor($pValue = null) - { - $this->borderTopColor = $pValue; - $this->borderLeftColor = $pValue; - $this->borderRightColor = $pValue; - $this->borderBottomColor = $pValue; - $this->borderInsideHColor = $pValue; - $this->borderInsideVColor = $pValue; - } - - /** - * Get TLRB Border Color + * Set TLRBHV Border Size * - * @return array + * @param int $value Border size in eighths of a point (1/8 point) + * @return self + */ + public function setBorderSize($value = null) + { + $this->setBorderTopSize($value); + $this->setBorderLeftSize($value); + $this->setBorderRightSize($value); + $this->setBorderBottomSize($value); + $this->setBorderInsideHSize($value); + $this->setBorderInsideVSize($value); + + return $this; + } + + /** + * Get TLRBHV Border Color + * + * @return string[] */ public function getBorderColor() { - $t = $this->getBorderTopColor(); - $l = $this->getBorderLeftColor(); - $r = $this->getBorderRightColor(); - $b = $this->getBorderBottomColor(); - $h = $this->getBorderInsideHColor(); - $v = $this->getBorderInsideVColor(); - - return array($t, $l, $r, $b, $h, $v); + return array( + $this->getBorderTopColor(), + $this->getBorderLeftColor(), + $this->getBorderRightColor(), + $this->getBorderBottomColor(), + $this->getBorderInsideHColor(), + $this->getBorderInsideVColor(), + ); } /** - * Set border size top + * Set TLRBHV Border Color * - * @param $pValue + * @param string $value + * @return self */ - public function setBorderTopSize($pValue = null) + public function setBorderColor($value = null) { - $this->borderTopSize = $pValue; - } + $this->setBorderTopColor($value); + $this->setBorderLeftColor($value); + $this->setBorderRightColor($value); + $this->setBorderBottomColor($value); + $this->setBorderInsideHColor($value); + $this->setBorderInsideVColor($value); - /** - * Get border size top - * - * @return - */ - public function getBorderTopSize() - { - return $this->borderTopSize; - } - - /** - * Set border color top - * - * @param $pValue - */ - public function setBorderTopColor($pValue = null) - { - $this->borderTopColor = $pValue; - } - - /** - * Get border color top - * - * @return - */ - public function getBorderTopColor() - { - return $this->borderTopColor; - } - - /** - * Set border size left - * - * @param $pValue - */ - public function setBorderLeftSize($pValue = null) - { - $this->borderLeftSize = $pValue; - } - - /** - * Get border size left - * - * @return - */ - public function getBorderLeftSize() - { - return $this->borderLeftSize; - } - - /** - * Set border color left - * - * @param $pValue - */ - public function setBorderLeftColor($pValue = null) - { - $this->borderLeftColor = $pValue; - } - - /** - * Get border color left - * - * @return - */ - public function getBorderLeftColor() - { - return $this->borderLeftColor; - } - - /** - * Set border size right - * - * @param $pValue - */ - public function setBorderRightSize($pValue = null) - { - $this->borderRightSize = $pValue; - } - - /** - * Get border size right - * - * @return - */ - public function getBorderRightSize() - { - return $this->borderRightSize; - } - - /** - * Set border color right - * - * @param $pValue - */ - public function setBorderRightColor($pValue = null) - { - $this->borderRightColor = $pValue; - } - - /** - * Get border color right - * - * @return - */ - public function getBorderRightColor() - { - return $this->borderRightColor; - } - - /** - * Set border size bottom - * - * @param $pValue - */ - public function setBorderBottomSize($pValue = null) - { - $this->borderBottomSize = $pValue; - } - - /** - * Get border size bottom - * - * @return - */ - public function getBorderBottomSize() - { - return $this->borderBottomSize; - } - - /** - * Set border color bottom - * - * @param $pValue - */ - public function setBorderBottomColor($pValue = null) - { - $this->borderBottomColor = $pValue; - } - - /** - * Get border color bottom - * - * @return - */ - public function getBorderBottomColor() - { - return $this->borderBottomColor; - } - - /** - * Set border color inside horizontal - * - * @param $pValue - */ - public function setBorderInsideHColor($pValue = null) - { - $this->borderInsideHColor = $pValue; - } - - /** - * Get border color inside horizontal - * - * @return - */ - public function getBorderInsideHColor() - { - return (isset($this->borderInsideHColor)) ? $this->borderInsideHColor : null; - } - - /** - * Set border color inside vertical - * - * @param $pValue - */ - public function setBorderInsideVColor($pValue = null) - { - $this->borderInsideVColor = $pValue; - } - - /** - * Get border color inside vertical - * - * @return - */ - public function getBorderInsideVColor() - { - return (isset($this->borderInsideVColor)) ? $this->borderInsideVColor : null; - } - - /** - * Set border size inside horizontal - * - * @param $pValue - */ - public function setBorderInsideHSize($pValue = null) - { - $this->borderInsideHSize = $pValue; + return $this; } /** * Get border size inside horizontal * - * @return + * @return int */ public function getBorderInsideHSize() { - return (isset($this->borderInsideHSize)) ? $this->borderInsideHSize : null; + return $this->getTableOnlyProperty('borderInsideHSize'); } /** - * Set border size inside vertical + * Set border size inside horizontal * - * @param $pValue + * @param int $value + * @return self */ - public function setBorderInsideVSize($pValue = null) + public function setBorderInsideHSize($value = null) { - $this->borderInsideVSize = $pValue; + return $this->setTableOnlyProperty('borderInsideHSize', $value); + } + + /** + * Get border color inside horizontal + * + * @return string + */ + public function getBorderInsideHColor() + { + return $this->getTableOnlyProperty('borderInsideHColor'); + } + + /** + * Set border color inside horizontal + * + * @param string $value + * @return self + */ + public function setBorderInsideHColor($value = null) + { + return $this->setTableOnlyProperty('borderInsideHColor', $value, false); } /** * Get border size inside vertical * - * @return + * @return int */ public function getBorderInsideVSize() { - return (isset($this->borderInsideVSize)) ? $this->borderInsideVSize : null; + return $this->getTableOnlyProperty('borderInsideVSize'); } /** - * Set cell margin top + * Set border size inside vertical * - * @param int $pValue + * @param int $value + * @return self */ - public function setCellMarginTop($pValue = null) + public function setBorderInsideVSize($value = null) { - $this->cellMarginTop = $pValue; + return $this->setTableOnlyProperty('borderInsideVSize', $value); + } + + /** + * Get border color inside vertical + * + * @return string + */ + public function getBorderInsideVColor() + { + return $this->getTableOnlyProperty('borderInsideVColor'); + } + + /** + * Set border color inside vertical + * + * @param string $value + * @return self + */ + public function setBorderInsideVColor($value = null) + { + return $this->setTableOnlyProperty('borderInsideVColor', $value, false); } /** @@ -545,17 +350,18 @@ class Table extends AbstractStyle */ public function getCellMarginTop() { - return $this->cellMarginTop; + return $this->getTableOnlyProperty('cellMarginTop'); } /** - * Set cell margin left + * Set cell margin top * - * @param int $pValue + * @param int $value + * @return self */ - public function setCellMarginLeft($pValue = null) + public function setCellMarginTop($value = null) { - $this->cellMarginLeft = $pValue; + return $this->setTableOnlyProperty('cellMarginTop', $value); } /** @@ -565,17 +371,18 @@ class Table extends AbstractStyle */ public function getCellMarginLeft() { - return $this->cellMarginLeft; + return $this->getTableOnlyProperty('cellMarginLeft'); } /** - * Set cell margin right + * Set cell margin left * - * @param int $pValue + * @param int $value + * @return self */ - public function setCellMarginRight($pValue = null) + public function setCellMarginLeft($value = null) { - $this->cellMarginRight = $pValue; + return $this->setTableOnlyProperty('cellMarginLeft', $value); } /** @@ -585,17 +392,18 @@ class Table extends AbstractStyle */ public function getCellMarginRight() { - return $this->cellMarginRight; + return $this->getTableOnlyProperty('cellMarginRight'); } /** - * Set cell margin bottom + * Set cell margin right * - * @param int $pValue + * @param int $value + * @return self */ - public function setCellMarginBottom($pValue = null) + public function setCellMarginRight($value = null) { - $this->cellMarginBottom = $pValue; + return $this->setTableOnlyProperty('cellMarginRight', $value); } /** @@ -605,29 +413,195 @@ class Table extends AbstractStyle */ public function getCellMarginBottom() { - return $this->cellMarginBottom; + return $this->getTableOnlyProperty('cellMarginBottom'); } /** - * Set TLRB cell margin + * Set cell margin bottom * - * @param int $pValue Margin in twips + * @param int $value + * @return self */ - public function setCellMargin($pValue = null) + public function setCellMarginBottom($value = null) { - $this->cellMarginTop = $pValue; - $this->cellMarginLeft = $pValue; - $this->cellMarginRight = $pValue; - $this->cellMarginBottom = $pValue; + return $this->setTableOnlyProperty('cellMarginBottom', $value); } /** * Get cell margin * - * @return array + * @return integer[] */ public function getCellMargin() { - return array($this->cellMarginTop, $this->cellMarginLeft, $this->cellMarginRight, $this->cellMarginBottom); + return array( + $this->cellMarginTop, + $this->cellMarginLeft, + $this->cellMarginRight, + $this->cellMarginBottom + ); + } + + /** + * Set TLRB cell margin + * + * @param int $value Margin in twips + * @return self + */ + public function setCellMargin($value = null) + { + $this->setCellMarginTop($value); + $this->setCellMarginLeft($value); + $this->setCellMarginRight($value); + $this->setCellMarginBottom($value); + + return $this; + } + + /** + * Check if any of the margin is not null + * + * @return bool + */ + public function hasMargin() + { + $margins = $this->getCellMargin(); + + return $margins !== array_filter($margins, 'is_null'); + } + + /** + * Get shading + * + * @return \PhpOffice\PhpWord\Style\Shading + */ + public function getShading() + { + return $this->shading; + } + + /** + * Set shading + * + * @param mixed $value + * @return self + */ + public function setShading($value = null) + { + $this->setObjectVal($value, 'Shading', $this->shading); + + return $this; + } + + /** + * Get alignment + * + * @return string + */ + public function getAlign() + { + return $this->alignment->getValue(); + } + + /** + * Set alignment + * + * @param string $value + * @return self + */ + public function setAlign($value = null) + { + $this->alignment->setValue($value); + + return $this; + } + + /** + * Get width + * + * @return int|float + */ + public function getWidth() + { + return $this->width; + } + + /** + * Set width + * + * @param int|float $value + * @return self + */ + public function setWidth($value = null) + { + $this->width = $this->setNumericVal($value, $this->width); + + return $this; + } + + /** + * Get width unit + * + * @return string + */ + public function getUnit() + { + return $this->unit; + } + + /** + * Set width unit + * + * @param string $value + * @return self + */ + public function setUnit($value = null) + { + $enum = array(self::WIDTH_AUTO, self::WIDTH_PERCENT, self::WIDTH_TWIP); + $this->unit = $this->setEnumVal($value, $enum, $this->unit); + + return $this; + } + + /** + * Get table style only property by checking if it's a firstRow + * + * This is necessary since firstRow style is cloned from table style but + * without certain properties activated, e.g. margins + * + * @param string $property + * @return int|string|null + */ + private function getTableOnlyProperty($property) + { + if ($this->isFirstRow === false) { + return $this->$property; + } + + return null; + } + + /** + * Set table style only property by checking if it's a firstRow + * + * This is necessary since firstRow style is cloned from table style but + * without certain properties activated, e.g. margins + * + * @param string $property + * @param int|string $value + * @param bool $isNumeric + * @return self + */ + private function setTableOnlyProperty($property, $value, $isNumeric = true) + { + if ($this->isFirstRow === false) { + if ($isNumeric === true) { + $this->$property = $this->setNumericVal($value, $this->$property); + } else { + $this->$property = $value; + } + } + + return $this; } } diff --git a/src/PhpWord/Style/Tabs.php b/src/PhpWord/Style/Tabs.php deleted file mode 100755 index 66137c0e..00000000 --- a/src/PhpWord/Style/Tabs.php +++ /dev/null @@ -1,51 +0,0 @@ -tabs = $tabs; - } - - /** - * Return XML - * - * @param \PhpOffice\PhpWord\Shared\XMLWriter &$xmlWriter - */ - public function toXml(XMLWriter &$xmlWriter = null) - { - if (isset($xmlWriter)) { - $xmlWriter->startElement("w:tabs"); - foreach ($this->tabs as &$tab) { - $tab->toXml($xmlWriter); - } - $xmlWriter->endElement(); - } - } -} diff --git a/src/PhpWord/Style/TextBox.php b/src/PhpWord/Style/TextBox.php new file mode 100644 index 00000000..6220b740 --- /dev/null +++ b/src/PhpWord/Style/TextBox.php @@ -0,0 +1,236 @@ +innerMarginTop = $value; + } + + /** + * Get margin top + * + * @return int + */ + public function getInnerMarginTop() + { + return $this->innerMarginTop; + } + + /** + * Set margin left. + * + * @param int $value + * @return void + */ + public function setInnerMarginLeft($value = null) + { + $this->innerMarginLeft = $value; + } + + /** + * Get margin left + * + * @return int + */ + public function getInnerMarginLeft() + { + return $this->innerMarginLeft; + } + + /** + * Set margin right. + * + * @param int $value + * @return void + */ + public function setInnerMarginRight($value = null) + { + $this->innerMarginRight = $value; + } + + /** + * Get margin right + * + * @return int + */ + public function getInnerMarginRight() + { + return $this->innerMarginRight; + } + + /** + * Set margin bottom. + * + * @param int $value + * @return void + */ + public function setInnerMarginBottom($value = null) + { + $this->innerMarginBottom = $value; + } + + /** + * Get margin bottom + * + * @return int + */ + public function getInnerMarginBottom() + { + return $this->innerMarginBottom; + } + + /** + * Set TLRB cell margin. + * + * @param int $value Margin in twips + * @return void + */ + public function setInnerMargin($value = null) + { + $this->setInnerMarginTop($value); + $this->setInnerMarginLeft($value); + $this->setInnerMarginRight($value); + $this->setInnerMarginBottom($value); + } + + /** + * Get cell margin + * + * @return integer[] + */ + public function getInnerMargin() + { + return array($this->innerMarginLeft, $this->innerMarginTop, $this->innerMarginRight, $this->innerMarginBottom); + } + + /** + * Has inner margin? + * + * @return bool + */ + public function hasInnerMargins() + { + $hasInnerMargins = false; + $margins = $this->getInnerMargin(); + for ($i = 0; $i < count($margins); $i++) { + if ($margins[$i] !== null) { + $hasInnerMargins = true; + } + } + + return $hasInnerMargins; + } + + /** + * Set border size. + * + * @param int $value Size in points + * @return void + */ + public function setBorderSize($value = null) + { + $this->borderSize = $value; + } + + /** + * Get border size + * + * @return int + */ + public function getBorderSize() + { + return $this->borderSize; + } + + /** + * Set border color. + * + * @param string $value + * @return void + */ + public function setBorderColor($value = null) + { + $this->borderColor = $value; + } + + /** + * Get border color + * + * @return string + */ + public function getBorderColor() + { + return $this->borderColor; + } +} diff --git a/src/PhpWord/TOC.php b/src/PhpWord/TOC.php deleted file mode 100644 index 22c79634..00000000 --- a/src/PhpWord/TOC.php +++ /dev/null @@ -1,215 +0,0 @@ - $value) { - self::$TOCStyle->setStyleValue($key, $value); - } - } - - if (!is_null($styleFont)) { - if (is_array($styleFont)) { - self::$fontStyle = new Font(); - foreach ($styleFont as $key => $value) { - self::$fontStyle->setStyleValue($key, $value); - } - } else { - self::$fontStyle = $styleFont; - } - } - - $this->minDepth = $minDepth; - $this->maxDepth = $maxDepth; - } - - /** - * Add a Title - * - * @param string $text - * @param int $depth - * @return array - */ - public static function addTitle($text, $depth = 0) - { - $anchor = '_Toc' . ++self::$anchor; - $bookmarkId = self::$bookmarkId++; - - $title = array(); - $title['text'] = $text; - $title['depth'] = $depth; - $title['anchor'] = $anchor; - $title['bookmarkId'] = $bookmarkId; - - self::$titles[] = $title; - - return array($anchor, $bookmarkId); - } - - /** - * Get all titles - * - * @return array - */ - public function getTitles() - { - $titles = self::$titles; - foreach ($titles as $i => $title) { - if ($this->minDepth > $title['depth']) { - unset($titles[$i]); - } - if (($this->maxDepth != 0) && ($this->maxDepth < $title['depth'])) { - unset($titles[$i]); - } - } - $titles = array_merge(array(), $titles); - - return $titles; - } - - /** - * Reset titles - */ - public static function resetTitles() - { - self::$titles = array(); - } - - /** - * Get TOC Style - * - * @return TOCStyle - */ - public static function getStyleTOC() - { - return self::$TOCStyle; - } - - /** - * Get Font Style - * - * @return Font - */ - public static function getStyleFont() - { - return self::$fontStyle; - } - - /** - * Set max depth - * - * @param int $value - */ - public function setMaxDepth($value) - { - $this->maxDepth = $value; - } - - /** - * Get Max Depth - * - * @return int Max depth of titles - */ - public function getMaxDepth() - { - return $this->maxDepth; - } - - /** - * Set min depth - * - * @param int $value - */ - public function setMinDepth($value) - { - $this->minDepth = $value; - } - - /** - * Get Min Depth - * - * @return int Min depth of titles - */ - public function getMinDepth() - { - return $this->minDepth; - } -} diff --git a/src/PhpWord/Template.php b/src/PhpWord/Template.php index 65ffd75f..c8f88026 100644 --- a/src/PhpWord/Template.php +++ b/src/PhpWord/Template.php @@ -1,17 +1,27 @@ tempFileName = tempnam(sys_get_temp_dir(), ''); - if ($this->tempFileName === false) { - throw new Exception('Could not create temporary file with unique name in the default temporary directory.'); + $this->tempFileName = tempnam(Settings::getTempDir(), 'PhpWord'); + if (false === $this->tempFileName) { + throw new CreateTemporaryFileException(); } // Copy the source File to the temp File - if (!copy($strFilename, $this->tempFileName)) { - throw new Exception("Could not copy the template from {$strFilename} to {$this->tempFileName}."); + if (false === copy($fileName, $this->tempFileName)) { + throw new CopyFileException($fileName, $this->tempFileName); } - $zipClass = Settings::getZipClass(); - $this->zipClass = new $zipClass(); + $this->zipClass = new ZipArchive(); $this->zipClass->open($this->tempFileName); // Find and load headers and footers - $i = 1; - while ($this->zipClass->locateName($this->getHeaderName($i)) !== false) { - $this->headerXMLs[$i] = $this->zipClass->getFromName($this->getHeaderName($i)); - $i++; + $index = 1; + while ($this->zipClass->locateName($this->getHeaderName($index)) !== false) { + $this->headerXMLs[$index] = $this->zipClass->getFromName($this->getHeaderName($index)); + $index++; } - $i = 1; - while ($this->zipClass->locateName($this->getFooterName($i)) !== false) { - $this->footerXMLs[$i] = $this->zipClass->getFromName($this->getFooterName($i)); - $i++; + $index = 1; + while ($this->zipClass->locateName($this->getFooterName($index)) !== false) { + $this->footerXMLs[$index] = $this->zipClass->getFromName($this->getFooterName($index)); + $index++; } $this->documentXML = $this->zipClass->getFromName('word/document.xml'); } /** - * Applies XSL style sheet to template's parts + * Document footer XML. + * + * @var string[] + */ + private $footerXMLs = array(); + + /** + * Applies XSL style sheet to template's parts. * * @param \DOMDocument $xslDOMDocument * @param array $xslOptions * @param string $xslOptionsURI - * @throws Exception + * @return void + * @throws \PhpOffice\PhpWord\Exception\Exception */ - public function applyXslStyleSheet(&$xslDOMDocument, $xslOptions = array(), $xslOptionsURI = '') + public function applyXslStyleSheet($xslDOMDocument, $xslOptions = array(), $xslOptionsURI = '') { $processor = new \XSLTProcessor(); $processor->importStylesheet($xslDOMDocument); - if ($processor->setParameter($xslOptionsURI, $xslOptions) === false) { + if (false === $processor->setParameter($xslOptionsURI, $xslOptions)) { throw new Exception('Could not set values for the given XSL style sheet parameters.'); } $xmlDOMDocument = new \DOMDocument(); - if ($xmlDOMDocument->loadXML($this->documentXML) === false) { + if (false === $xmlDOMDocument->loadXML($this->documentXML)) { throw new Exception('Could not load XML from the given template.'); } $xmlTransformed = $processor->transformToXml($xmlDOMDocument); - if ($xmlTransformed === false) { + if (false === $xmlTransformed) { throw new Exception('Could not transform the given XML document.'); } @@ -123,11 +136,12 @@ class Template } /** - * Set a Template value + * Set a Template value. * * @param mixed $search * @param mixed $replace * @param integer $limit + * @return void */ public function setValue($search, $replace, $limit = -1) { @@ -143,7 +157,8 @@ class Template } /** - * Returns array of all variables in template + * Returns array of all variables in template. + * * @return string[] */ public function getVariables() @@ -162,11 +177,12 @@ class Template } /** - * Clone a table row in a template document + * Clone a table row in a template document. * * @param string $search * @param integer $numberOfClones - * @throws Exception + * @return void + * @throws \PhpOffice\PhpWord\Exception\Exception */ public function cloneRow($search, $numberOfClones) { @@ -185,7 +201,7 @@ class Template // Check if there's a cell spanning multiple rows. if (preg_match('##', $xmlRow)) { - $extraRowStart = $rowEnd; + // $extraRowStart = $rowEnd; $extraRowEnd = $rowEnd; while (true) { $extraRowStart = $this->findRowStart($extraRowEnd + 1); @@ -198,7 +214,8 @@ class Template // If tmpXmlRow doesn't contain continue, this row is no longer part of the spanned row. $tmpXmlRow = $this->getSlice($extraRowStart, $extraRowEnd); - if (!preg_match('##', $tmpXmlRow) && !preg_match('##', $tmpXmlRow)) { + if (!preg_match('##', $tmpXmlRow) && + !preg_match('##', $tmpXmlRow)) { break; } // This row was a spanned row, update $rowEnd and search for the next row. @@ -217,7 +234,7 @@ class Template } /** - * Clone a block + * Clone a block. * * @param string $blockname * @param integer $clones @@ -227,7 +244,11 @@ class Template public function cloneBlock($blockname, $clones = 1, $replace = true) { $xmlBlock = null; - preg_match('/(<\?xml.*)(\${' . $blockname . '}<\/w:.*?p>)(.*)()/is', $this->documentXML, $matches); + preg_match( + '/(<\?xml.*)(\${' . $blockname . '}<\/w:.*?p>)(.*)()/is', + $this->documentXML, + $matches + ); if (isset($matches[3])) { $xmlBlock = $matches[3]; @@ -237,7 +258,11 @@ class Template } if ($replace) { - $this->documentXML = str_replace($matches[2] . $matches[3] . $matches[4], implode('', $cloned), $this->documentXML); + $this->documentXML = str_replace( + $matches[2] . $matches[3] . $matches[4], + implode('', $cloned), + $this->documentXML + ); } } @@ -245,24 +270,34 @@ class Template } /** - * Replace a block + * Replace a block. * * @param string $blockname * @param string $replacement + * @return void */ public function replaceBlock($blockname, $replacement) { - preg_match('/(<\?xml.*)(\${' . $blockname . '}<\/w:.*?p>)(.*)()/is', $this->documentXML, $matches); + preg_match( + '/(<\?xml.*)(\${' . $blockname . '}<\/w:.*?p>)(.*)()/is', + $this->documentXML, + $matches + ); if (isset($matches[3])) { - $this->documentXML = str_replace($matches[2] . $matches[3] . $matches[4], $replacement, $this->documentXML); + $this->documentXML = str_replace( + $matches[2] . $matches[3] . $matches[4], + $replacement, + $this->documentXML + ); } } /** - * Delete a block of text + * Delete a block of text. * * @param string $blockname + * @return void */ public function deleteBlock($blockname) { @@ -270,10 +305,10 @@ class Template } /** - * Save XML to temporary file + * Save XML to temporary file. * * @return string - * @throws Exception + * @throws \PhpOffice\PhpWord\Exception\Exception */ public function save() { @@ -288,7 +323,7 @@ class Template } // Close zip file - if ($this->zipClass->close() === false) { + if (false === $this->zipClass->close()) { throw new Exception('Could not close zip file.'); } @@ -296,19 +331,22 @@ class Template } /** - * Save XML to defined name + * Save XML to defined name. * - * @param string $strFilename + * @since 0.8.0 + * + * @param string $fileName + * @return void */ - public function saveAs($strFilename) + public function saveAs($fileName) { - $tempFilename = $this->save(); + $tempFileName = $this->save(); - if (file_exists($strFilename)) { - unlink($strFilename); + if (file_exists($fileName)) { + unlink($fileName); } - rename($tempFilename, $strFilename); + rename($tempFileName, $fileName); } /** @@ -345,7 +383,8 @@ class Template } /** - * Find all variables in $documentPartXML + * Find all variables in $documentPartXML. + * * @param string $documentPartXML * @return string[] */ @@ -357,7 +396,8 @@ class Template } /** - * Get the name of the footer file for $index + * Get the name of the footer file for $index. + * * @param integer $index * @return string */ @@ -367,7 +407,8 @@ class Template } /** - * Get the name of the header file for $index + * Get the name of the header file for $index. + * * @param integer $index * @return string */ @@ -377,11 +418,11 @@ class Template } /** - * Find the start position of the nearest table row before $offset + * Find the start position of the nearest table row before $offset. * * @param integer $offset * @return integer - * @throws Exception + * @throws \PhpOffice\PhpWord\Exception\Exception */ private function findRowStart($offset) { @@ -396,7 +437,7 @@ class Template } /** - * Find the end position of the nearest table row after $offset + * Find the end position of the nearest table row after $offset. * * @param integer $offset * @return integer @@ -408,7 +449,7 @@ class Template } /** - * Get a slice of a string + * Get a slice of a string. * * @param integer $startPosition * @param integer $endPosition diff --git a/src/PhpWord/Writer/AbstractWriter.php b/src/PhpWord/Writer/AbstractWriter.php index 684a5d32..31097b89 100644 --- a/src/PhpWord/Writer/AbstractWriter.php +++ b/src/PhpWord/Writer/AbstractWriter.php @@ -1,17 +1,27 @@ '', 'object' => ''); + /** * Use disk caching * - * @var boolean + * @var bool */ private $useDiskCaching = false; @@ -48,6 +72,13 @@ abstract class AbstractWriter implements WriterInterface */ private $diskCachingDirectory = './'; + /** + * Temporary directory + * + * @var string + */ + private $tempDir = ''; + /** * Original file name * @@ -65,8 +96,8 @@ abstract class AbstractWriter implements WriterInterface /** * Get PhpWord object * - * @return PhpWord - * @throws Exception + * @return \PhpOffice\PhpWord\PhpWord + * @throws \PhpOffice\PhpWord\Exception\Exception */ public function getPhpWord() { @@ -80,8 +111,8 @@ abstract class AbstractWriter implements WriterInterface /** * Set PhpWord object * - * @param PhpWord - * @return $this + * @param \PhpOffice\PhpWord\PhpWord + * @return self */ public function setPhpWord(PhpWord $phpWord = null) { @@ -92,13 +123,13 @@ abstract class AbstractWriter implements WriterInterface /** * Get writer part * - * @param string $pPartName Writer part name + * @param string $partName Writer part name * @return mixed */ - public function getWriterPart($pPartName = '') + public function getWriterPart($partName = '') { - if ($pPartName != '' && isset($this->writerParts[strtolower($pPartName)])) { - return $this->writerParts[strtolower($pPartName)]; + if ($partName != '' && isset($this->writerParts[strtolower($partName)])) { + return $this->writerParts[strtolower($partName)]; } else { return null; } @@ -107,9 +138,9 @@ abstract class AbstractWriter implements WriterInterface /** * Get use disk caching status * - * @return boolean + * @return bool */ - public function getUseDiskCaching() + public function isUseDiskCaching() { return $this->useDiskCaching; } @@ -117,19 +148,20 @@ abstract class AbstractWriter implements WriterInterface /** * Set use disk caching status * - * @param boolean $pValue - * @param string $pDirectory - * @return $this + * @param bool $value + * @param string $directory + * @return self + * @throws \PhpOffice\PhpWord\Exception\Exception */ - public function setUseDiskCaching($pValue = false, $pDirectory = null) + public function setUseDiskCaching($value = false, $directory = null) { - $this->useDiskCaching = $pValue; + $this->useDiskCaching = $value; - if (!is_null($pDirectory)) { - if (is_dir($pDirectory)) { - $this->diskCachingDirectory = $pDirectory; + if (!is_null($directory)) { + if (is_dir($directory)) { + $this->diskCachingDirectory = $directory; } else { - throw new Exception("Directory does not exist: $pDirectory"); + throw new Exception("Directory does not exist: $directory"); } } @@ -146,6 +178,32 @@ abstract class AbstractWriter implements WriterInterface return $this->diskCachingDirectory; } + /** + * Get temporary directory + * + * @return string + */ + public function getTempDir() + { + return $this->tempDir; + } + + /** + * Set temporary directory + * + * @param string $value + * @return self + */ + public function setTempDir($value) + { + if (!is_dir($value)) { + mkdir($value); + } + $this->tempDir = $value; + + return $this; + } + /** * Get temporary file name * @@ -156,10 +214,14 @@ abstract class AbstractWriter implements WriterInterface */ protected function getTempFile($filename) { + // Temporary directory + $this->setTempDir(Settings::getTempDir() . '/PHPWordWriter/'); + + // Temporary file $this->originalFilename = $filename; if (strtolower($filename) == 'php://output' || strtolower($filename) == 'php://stdout') { - $filename = @tempnam(sys_get_temp_dir(), 'phpword_'); - if ($filename == '') { + $filename = tempnam(Settings::getTempDir(), 'PhpWord'); + if (false === $filename) { $filename = $this->originalFilename; } } @@ -169,50 +231,202 @@ abstract class AbstractWriter implements WriterInterface } /** - * Cleanup temporary file + * Cleanup temporary file. * - * If a temporary file was used, copy it to the correct file stream + * @return void + * @throws \PhpOffice\PhpWord\Exception\CopyFileException */ protected function cleanupTempFile() { if ($this->originalFilename != $this->tempFilename) { - if (copy($this->tempFilename, $this->originalFilename) === false) { - throw new Exception("Could not copy temporary zip file {$this->tempFilename} to {$this->originalFilename}."); + // @codeCoverageIgnoreStart + // Can't find any test case. Uncomment when found. + if (false === copy($this->tempFilename, $this->originalFilename)) { + throw new CopyFileException($this->tempFilename, $this->originalFilename); } + // @codeCoverageIgnoreEnd @unlink($this->tempFilename); } + + $this->clearTempDir(); + } + + /** + * Clear temporary directory. + * + * @return void + */ + protected function clearTempDir() + { + if (is_dir($this->tempDir)) { + $this->deleteDir($this->tempDir); + } } /** * Get ZipArchive object * * @param string $filename - * @return mixed ZipArchive object + * @return \PhpOffice\PhpWord\Shared\ZipArchive + * @throws \Exception */ protected function getZipArchive($filename) { - // Create new ZIP file and open it for writing - $zipClass = Settings::getZipClass(); - $objZip = new $zipClass(); - - // Retrieve OVERWRITE and CREATE constants from the instantiated zip class - // This method of accessing constant values from a dynamic class should work with all appropriate versions of PHP - $ro = new \ReflectionObject($objZip); - $zipOverWrite = $ro->getConstant('OVERWRITE'); - $zipCreate = $ro->getConstant('CREATE'); - // Remove any existing file if (file_exists($filename)) { unlink($filename); } // Try opening the ZIP file - if ($objZip->open($filename, $zipOverWrite) !== true) { - if ($objZip->open($filename, $zipCreate) !== true) { - throw new Exception("Could not open " . $filename . " for writing."); + $zip = new ZipArchive(); + + // @codeCoverageIgnoreStart + // Can't find any test case. Uncomment when found. + if ($zip->open($filename, ZipArchive::OVERWRITE) !== true) { + if ($zip->open($filename, ZipArchive::CREATE) !== true) { + throw new \Exception("Could not open '{$filename}' for writing."); + } + } + // @codeCoverageIgnoreEnd + + return $zip; + } + + /** + * Open file for writing + * + * @param string $filename + * @return resource + * @throws \Exception + * @since 0.11.0 + */ + protected function openFile($filename) + { + $filename = $this->getTempFile($filename); + $fileHandle = fopen($filename, 'w'); + // @codeCoverageIgnoreStart + // Can't find any test case. Uncomment when found. + if ($fileHandle === false) { + throw new \Exception("Could not open '{$filename}' for writing."); + } + // @codeCoverageIgnoreEnd + + return $fileHandle; + } + + /** + * Write content to file. + * + * @since 0.11.0 + * + * @param resource $fileHandle + * @param string $content + * @return void + */ + protected function writeFile($fileHandle, $content) + { + fwrite($fileHandle, $content); + fclose($fileHandle); + $this->cleanupTempFile(); + } + + /** + * Add files to package. + * + * @param \PhpOffice\PhpWord\Shared\ZipArchive $zip + * @param mixed $elements + * @return void + */ + protected function addFilesToPackage(ZipArchive $zip, $elements) + { + foreach ($elements as $element) { + $type = $element['type']; // image|object|link + + // Skip nonregistered types and set target + if (!array_key_exists($type, $this->mediaPaths)) { + continue; + } + $target = $this->mediaPaths[$type] . $element['target']; + + // Retrive GD image content or get local media + 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(); + $zip->addFromString($target, $imageContents); + imagedestroy($image); + } else { + $this->addFileToPackage($zip, $element['source'], $target); + } + } + } + + /** + * Add file to package. + * + * Get the actual source from an archive image. + * + * @param \PhpOffice\PhpWord\Shared\ZipArchive $zipPackage + * @param string $source + * @param string $target + * @return void + */ + protected function addFileToPackage($zipPackage, $source, $target) + { + $isArchive = strpos($source, 'zip://') !== false; + $actualSource = null; + if ($isArchive) { + $source = substr($source, 6); + list($zipFilename, $imageFilename) = explode('#', $source); + + $zip = new ZipArchive; + if ($zip->open($zipFilename) !== false) { + if ($zip->locateName($imageFilename)) { + $zip->extractTo($this->getTempDir(), $imageFilename); + $actualSource = $this->getTempDir() . DIRECTORY_SEPARATOR . $imageFilename; + } + } + $zip->close(); + } else { + $actualSource = $source; + } + + if (!is_null($actualSource)) { + $zipPackage->addFile($actualSource, $target); + } + } + + /** + * Delete directory. + * + * @param string $dir + * @return void + */ + private function deleteDir($dir) + { + foreach (scandir($dir) as $file) { + if ($file === '.' || $file === '..') { + continue; + } elseif (is_file($dir . "/" . $file)) { + unlink($dir . "/" . $file); + } elseif (is_dir($dir . "/" . $file)) { + $this->deleteDir($dir . "/" . $file); } } - return $objZip; + rmdir($dir); + } + + /** + * Get use disk caching status + * + * @deprecated 0.10.0 + * @codeCoverageIgnore + */ + public function getUseDiskCaching() + { + return $this->isUseDiskCaching(); } } diff --git a/src/PhpWord/Writer/HTML.php b/src/PhpWord/Writer/HTML.php new file mode 100644 index 00000000..5c58acfc --- /dev/null +++ b/src/PhpWord/Writer/HTML.php @@ -0,0 +1,138 @@ +setPhpWord($phpWord); + + $this->parts = array('Head', 'Body'); + foreach ($this->parts as $partName) { + $partClass = 'PhpOffice\\PhpWord\\Writer\\HTML\\Part\\' . $partName; + if (class_exists($partClass)) { + /** @var \PhpOffice\PhpWord\Writer\HTML\Part\AbstractPart $part Type hint */ + $part = new $partClass(); + $part->setParentWriter($this); + $this->writerParts[strtolower($partName)] = $part; + } + } + } + + /** + * Save PhpWord to file. + * + * @param string $filename + * @return void + * @throws \PhpOffice\PhpWord\Exception\Exception + */ + public function save($filename = null) + { + $this->writeFile($this->openFile($filename), $this->getContent()); + } + + /** + * Get content + * + * @return string + * @since 0.11.0 + */ + public function getContent() + { + $content = ''; + + $content .= '' . PHP_EOL; + $content .= '' . PHP_EOL; + $content .= '' . PHP_EOL; + $content .= $this->getWriterPart('Head')->write(); + $content .= $this->getWriterPart('Body')->write(); + $content .= '' . PHP_EOL; + + return $content; + } + + /** + * Get is PDF + * + * @return bool + */ + public function isPdf() + { + return $this->isPdf; + } + + /** + * Get notes + * + * @return array + */ + public function getNotes() + { + return $this->notes; + } + + /** + * Add note. + * + * @param int $noteId + * @param string $noteMark + * @return void + */ + public function addNote($noteId, $noteMark) + { + $this->notes[$noteId] = $noteMark; + } + + /** + * Write document + * + * @return string + * @deprecated 0.11.0 + * @codeCoverageIgnore + */ + public function writeDocument() + { + return $this->getContent(); + } +} diff --git a/src/PhpWord/Writer/HTML/Element/AbstractElement.php b/src/PhpWord/Writer/HTML/Element/AbstractElement.php new file mode 100644 index 00000000..73f88d3d --- /dev/null +++ b/src/PhpWord/Writer/HTML/Element/AbstractElement.php @@ -0,0 +1,80 @@ +parentWriter = $parentWriter; + $this->element = $element; + $this->withoutP = $withoutP; + } + + /** + * Set without paragraph. + * + * @param bool $value + * @return void + */ + public function setWithoutP($value) + { + $this->withoutP = $value; + } +} diff --git a/src/PhpWord/Writer/HTML/Element/Container.php b/src/PhpWord/Writer/HTML/Element/Container.php new file mode 100644 index 00000000..147329dd --- /dev/null +++ b/src/PhpWord/Writer/HTML/Element/Container.php @@ -0,0 +1,64 @@ +element; + if (!$container instanceof ContainerElement) { + return ''; + } + $containerClass = substr(get_class($container), strrpos(get_class($container), '\\') + 1); + $withoutP = in_array($containerClass, array('TextRun', 'Footnote', 'Endnote')) ? true : false; + $content = ''; + + $elements = $container->getElements(); + foreach ($elements as $element) { + $elementClass = get_class($element); + $writerClass = str_replace('PhpOffice\\PhpWord\\Element', $this->namespace, $elementClass); + if (class_exists($writerClass)) { + /** @var \PhpOffice\PhpWord\Writer\HTML\Element\AbstractElement $writer Type hint */ + $writer = new $writerClass($this->parentWriter, $element, $withoutP); + $content .= $writer->write(); + } + } + + return $content; + } +} diff --git a/src/PhpWord/Writer/HTML/Element/Endnote.php b/src/PhpWord/Writer/HTML/Element/Endnote.php new file mode 100644 index 00000000..3da8a8fb --- /dev/null +++ b/src/PhpWord/Writer/HTML/Element/Endnote.php @@ -0,0 +1,33 @@ +element instanceof \PhpOffice\PhpWord\Element\Footnote) { + return ''; + } + /** @var \PhpOffice\PhpWord\Writer\HTML $parentWriter Type hint */ + $parentWriter = $this->parentWriter; + + $noteId = count($parentWriter->getNotes()) + 1; + $noteMark = $this->noteType . '-' . $this->element->getRelationId(); + $content = "{$noteId}"; + + $parentWriter->addNote($noteId, $noteMark); + + return $content; + } +} diff --git a/src/PhpWord/Writer/HTML/Element/Image.php b/src/PhpWord/Writer/HTML/Element/Image.php new file mode 100644 index 00000000..ab78990b --- /dev/null +++ b/src/PhpWord/Writer/HTML/Element/Image.php @@ -0,0 +1,59 @@ +element instanceof ImageElement) { + return ''; + } + /** @var \PhpOffice\PhpWord\Writer\HTML $parentWriter Type hint */ + $parentWriter = $this->parentWriter; + + $content = ''; + if (!$parentWriter->isPdf()) { + $imageData = $this->element->getImageStringData(true); + if ($imageData !== null) { + $styleWriter = new ImageStyleWriter($this->element->getStyle()); + $style = $styleWriter->write(); + $imageData = 'data:' . $this->element->getImageType() . ';base64,' . $imageData; + + $content .= $this->writeOpening(); + $content .= ""; + $content .= $this->writeClosing(); + } + } + + return $content; + } +} diff --git a/src/PhpWord/Writer/HTML/Element/Link.php b/src/PhpWord/Writer/HTML/Element/Link.php new file mode 100644 index 00000000..4e99810c --- /dev/null +++ b/src/PhpWord/Writer/HTML/Element/Link.php @@ -0,0 +1,45 @@ +element instanceof \PhpOffice\PhpWord\Element\Link) { + return ''; + } + + $content = ''; + $content .= $this->writeOpening(); + $content .= "element->getSource()}\">{$this->element->getText()}"; + $content .= $this->writeClosing(); + + return $content; + } +} diff --git a/src/PhpWord/Writer/HTML/Element/ListItem.php b/src/PhpWord/Writer/HTML/Element/ListItem.php new file mode 100644 index 00000000..79a3b393 --- /dev/null +++ b/src/PhpWord/Writer/HTML/Element/ListItem.php @@ -0,0 +1,43 @@ +element instanceof \PhpOffice\PhpWord\Element\ListItem) { + return ''; + } + + $text = htmlspecialchars($this->element->getTextObject()->getText()); + $content = '

' . $text . '

' . PHP_EOL; + + return $content; + } +} diff --git a/src/PhpWord/Writer/HTML/Element/PageBreak.php b/src/PhpWord/Writer/HTML/Element/PageBreak.php new file mode 100644 index 00000000..a3fb1f3b --- /dev/null +++ b/src/PhpWord/Writer/HTML/Element/PageBreak.php @@ -0,0 +1,27 @@ +element instanceof \PhpOffice\PhpWord\Element\Table) { + return ''; + } + + $content = ''; + $rows = $this->element->getRows(); + $rowCount = count($rows); + if ($rowCount > 0) { + $content .= '' . PHP_EOL; + foreach ($rows as $row) { + /** @var $row \PhpOffice\PhpWord\Element\Row Type hint */ + $rowStyle = $row->getStyle(); + // $height = $row->getHeight(); + $tblHeader = $rowStyle->isTblHeader(); + $content .= '' . PHP_EOL; + foreach ($row->getCells() as $cell) { + $writer = new Container($this->parentWriter, $cell); + $cellTag = $tblHeader ? 'th' : 'td'; + $content .= "<{$cellTag}>" . PHP_EOL; + $content .= $writer->write(); + $content .= '' . PHP_EOL; + } + $content .= '' . PHP_EOL; + } + $content .= '
' . PHP_EOL; + } + + return $content; + } +} diff --git a/src/PhpWord/Writer/HTML/Element/Text.php b/src/PhpWord/Writer/HTML/Element/Text.php new file mode 100644 index 00000000..c2d4134a --- /dev/null +++ b/src/PhpWord/Writer/HTML/Element/Text.php @@ -0,0 +1,190 @@ +element; + $this->getFontStyle(); + + $content = ''; + $content .= $this->writeOpening(); + $content .= $this->openingText; + $content .= $this->openingTags; + $content .= htmlspecialchars($element->getText()); + $content .= $this->closingTags; + $content .= $this->closingText; + $content .= $this->writeClosing(); + + return $content; + } + + /** + * Set opening text. + * + * @param string $value + * @return void + */ + public function setOpeningText($value) + { + $this->openingText = $value; + } + + /** + * Set closing text. + * + * @param string $value + * @return void + */ + public function setClosingText($value) + { + $this->closingText = $value; + } + + /** + * Write opening + * + * @return string + */ + protected function writeOpening() + { + $content = ''; + if (!$this->withoutP) { + $style = ''; + if (method_exists($this->element, 'getParagraphStyle')) { + $style = $this->getParagraphStyle(); + } + $content .= ""; + } + + return $content; + } + + /** + * Write ending + * + * @return string + */ + protected function writeClosing() + { + $content = ''; + if (!$this->withoutP) { + $content .= $this->closingText; + $content .= "

" . PHP_EOL; + } + + return $content; + } + + /** + * Write paragraph style + * + * @return string + */ + private function getParagraphStyle() + { + /** @var \PhpOffice\PhpWord\Element\Text $element Type hint */ + $element = $this->element; + $style = ''; + if (!method_exists($element, 'getParagraphStyle')) { + return $style; + } + + $paragraphStyle = $element->getParagraphStyle(); + $pStyleIsObject = ($paragraphStyle instanceof Paragraph); + if ($pStyleIsObject) { + $styleWriter = new ParagraphStyleWriter($paragraphStyle); + $style = $styleWriter->write(); + } + if ($style) { + $attribute = $pStyleIsObject ? 'style' : 'class'; + $style = " {$attribute}=\"{$style}\""; + } + + return $style; + } + + /** + * Get font style. + * + * @return void + */ + private function getFontStyle() + { + /** @var \PhpOffice\PhpWord\Element\Text $element Type hint */ + $element = $this->element; + $style = ''; + $fontStyle = $element->getFontStyle(); + $fStyleIsObject = ($fontStyle instanceof Font); + if ($fStyleIsObject) { + $styleWriter = new FontStyleWriter($fontStyle); + $style = $styleWriter->write(); + } + if ($style) { + $attribute = $fStyleIsObject ? 'style' : 'class'; + $this->openingTags = ""; + $this->closingTags = ""; + } + } +} diff --git a/src/PhpWord/Writer/HTML/Element/TextBreak.php b/src/PhpWord/Writer/HTML/Element/TextBreak.php new file mode 100644 index 00000000..30560e96 --- /dev/null +++ b/src/PhpWord/Writer/HTML/Element/TextBreak.php @@ -0,0 +1,42 @@ +withoutP) { + $content = '
' . PHP_EOL; + } else { + $content = '

 

' . PHP_EOL; + } + + return $content; + } +} diff --git a/src/PhpWord/Writer/HTML/Element/TextRun.php b/src/PhpWord/Writer/HTML/Element/TextRun.php new file mode 100644 index 00000000..b6bfacea --- /dev/null +++ b/src/PhpWord/Writer/HTML/Element/TextRun.php @@ -0,0 +1,43 @@ +writeOpening(); + $writer = new Container($this->parentWriter, $this->element); + $content .= $writer->write(); + $content .= $this->writeClosing(); + + return $content; + } +} diff --git a/src/PhpWord/Writer/HTML/Element/Title.php b/src/PhpWord/Writer/HTML/Element/Title.php new file mode 100644 index 00000000..20747bf9 --- /dev/null +++ b/src/PhpWord/Writer/HTML/Element/Title.php @@ -0,0 +1,44 @@ +element instanceof \PhpOffice\PhpWord\Element\Title) { + return ''; + } + + $tag = 'h' . $this->element->getDepth(); + $text = htmlspecialchars($this->element->getText()); + $content = "<{$tag}>{$text}" . PHP_EOL; + + return $content; + } +} diff --git a/src/PhpWord/Writer/HTML/Part/AbstractPart.php b/src/PhpWord/Writer/HTML/Part/AbstractPart.php new file mode 100644 index 00000000..124cc15a --- /dev/null +++ b/src/PhpWord/Writer/HTML/Part/AbstractPart.php @@ -0,0 +1,69 @@ +parentWriter = $writer; + } + + /** + * Get parent writer + * + * @return \PhpOffice\PhpWord\Writer\AbstractWriter + * @throws \PhpOffice\PhpWord\Exception\Exception + */ + public function getParentWriter() + { + if ($this->parentWriter !== null) { + return $this->parentWriter; + } else { + throw new Exception('No parent WriterInterface assigned.'); + } + } +} diff --git a/src/PhpWord/Writer/HTML/Part/Body.php b/src/PhpWord/Writer/HTML/Part/Body.php new file mode 100644 index 00000000..4fd61a83 --- /dev/null +++ b/src/PhpWord/Writer/HTML/Part/Body.php @@ -0,0 +1,89 @@ +getParentWriter()->getPhpWord(); + + $content = ''; + + $content .= '' . PHP_EOL; + $sections = $phpWord->getSections(); + foreach ($sections as $section) { + $writer = new Container($this->getParentWriter(), $section); + $content .= $writer->write(); + } + + $content .= $this->writeNotes(); + $content .= '' . PHP_EOL; + + return $content; + } + + /** + * Write footnote/endnote contents as textruns + * + * @return string + */ + private function writeNotes() + { + /** @var \PhpOffice\PhpWord\Writer\HTML $parentWriter Type hint */ + $parentWriter = $this->getParentWriter(); + $phpWord = $parentWriter->getPhpWord(); + $notes = $parentWriter->getNotes(); + + $content = ''; + + if (!empty($notes)) { + $content .= "
" . PHP_EOL; + foreach ($notes as $noteId => $noteMark) { + list($noteType, $noteTypeId) = explode('-', $noteMark); + $method = 'get' . ($noteType == 'endnote' ? 'Endnotes' : 'Footnotes'); + $collection = $phpWord->$method()->getItems(); + + if (array_key_exists($noteTypeId, $collection)) { + $element = $collection[$noteTypeId]; + $noteAnchor = ""; + $noteAnchor .= "{$noteId}"; + + $writer = new TextRunWriter($this->getParentWriter(), $element); + $writer->setOpeningText($noteAnchor); + $content .= $writer->write(); + } + } + } + + return $content; + } +} diff --git a/src/PhpWord/Writer/HTML/Part/Head.php b/src/PhpWord/Writer/HTML/Part/Head.php new file mode 100644 index 00000000..4bfe3046 --- /dev/null +++ b/src/PhpWord/Writer/HTML/Part/Head.php @@ -0,0 +1,129 @@ +getParentWriter()->getPhpWord()->getDocInfo(); + $propertiesMapping = array( + 'creator' => 'author', + 'title' => '', + 'description' => '', + 'subject' => '', + 'keywords' => '', + 'category' => '', + 'company' => '', + 'manager' => '' + ); + $title = $docProps->getTitle(); + $title = ($title != '') ? $title : 'PHPWord'; + + $content = ''; + + $content .= '' . PHP_EOL; + $content .= '' . PHP_EOL; + $content .= '' . htmlspecialchars($title) . '' . PHP_EOL; + foreach ($propertiesMapping as $key => $value) { + $value = ($value == '') ? $key : $value; + $method = "get" . $key; + if ($docProps->$method() != '') { + $content .= '' . PHP_EOL; + } + } + $content .= $this->writeStyles(); + $content .= '' . PHP_EOL; + + return $content; + } + + /** + * Get styles + * + * @return string + */ + private function writeStyles() + { + $css = '' . PHP_EOL; + + return $css; + } +} diff --git a/src/PhpWord/Writer/HTML/Style/AbstractStyle.php b/src/PhpWord/Writer/HTML/Style/AbstractStyle.php new file mode 100644 index 00000000..07ef1618 --- /dev/null +++ b/src/PhpWord/Writer/HTML/Style/AbstractStyle.php @@ -0,0 +1,126 @@ +style = $style; + } + + /** + * Set parent writer. + * + * @param \PhpOffice\PhpWord\Writer\AbstractWriter $writer + * @return void + */ + public function setParentWriter($writer) + { + $this->parentWriter = $writer; + } + + /** + * Get parent writer + * + * @return \PhpOffice\PhpWord\Writer\AbstractWriter + */ + public function getParentWriter() + { + return $this->parentWriter; + } + + /** + * Get style + * + * @return array|\PhpOffice\PhpWord\Style\AbstractStyle $style + */ + public function getStyle() + { + if (!$this->style instanceof Style && !is_array($this->style)) { + return ''; + } + + return $this->style; + } + + /** + * Takes array where of CSS properties / values and converts to CSS string + * + * @param array $css + * @return string + */ + protected function assembleCss($css) + { + $pairs = array(); + $string = ''; + foreach ($css as $key => $value) { + if ($value != '') { + $pairs[] = $key . ': ' . $value; + } + } + if (!empty($pairs)) { + $string = implode('; ', $pairs) . ';'; + } + + return $string; + } + + /** + * Get value if ... + * + * @param bool|null $condition + * @param string $value + * @return string + */ + protected function getValueIf($condition, $value) + { + return $condition == true ? $value : ''; + } +} diff --git a/src/PhpWord/Writer/HTML/Style/Font.php b/src/PhpWord/Writer/HTML/Style/Font.php new file mode 100644 index 00000000..8645a1f4 --- /dev/null +++ b/src/PhpWord/Writer/HTML/Style/Font.php @@ -0,0 +1,64 @@ +getStyle(); + if (!$style instanceof FontStyle) { + return ''; + } + $css = array(); + + $font = $style->getName(); + $size = $style->getSize(); + $color = $style->getColor(); + $fgColor = $style->getFgColor(); + $underline = $style->getUnderline() != FontStyle::UNDERLINE_NONE; + $lineThrough = $style->isStrikethrough() || $style->isDoubleStrikethrough(); + + $css['font-family'] = $this->getValueIf($font !== null, "'{$font}'"); + $css['font-size'] = $this->getValueIf($size !== null, "{$size}pt"); + $css['color'] = $this->getValueIf($color !== null, "#{$color}"); + $css['background'] = $this->getValueIf($fgColor != '', $fgColor); + $css['font-weight'] = $this->getValueIf($style->isBold(), 'bold'); + $css['font-style'] = $this->getValueIf($style->isItalic(), 'italic'); + $css['vertical-align'] = $this->getValueIf($style->isSuperScript(), 'italic'); + $css['vertical-align'] = $this->getValueIf($style->isSuperScript(), 'super'); + $css['vertical-align'] = $this->getValueIf($style->isSubScript(), 'sub'); + $css['text-decoration'] = ''; + $css['text-decoration'] .= $this->getValueIf($underline, 'underline '); + $css['text-decoration'] .= $this->getValueIf($lineThrough, 'line-through '); + + return $this->assembleCss($css); + } +} diff --git a/src/PhpWord/Writer/HTML/Style/Generic.php b/src/PhpWord/Writer/HTML/Style/Generic.php new file mode 100644 index 00000000..df94d492 --- /dev/null +++ b/src/PhpWord/Writer/HTML/Style/Generic.php @@ -0,0 +1,43 @@ +getStyle(); + $css = array(); + + if (is_array($style) && !empty($style)) { + $css = $style; + } + + return $this->assembleCss($css); + } +} diff --git a/src/PhpWord/Writer/HTML/Style/Image.php b/src/PhpWord/Writer/HTML/Style/Image.php new file mode 100644 index 00000000..13be3665 --- /dev/null +++ b/src/PhpWord/Writer/HTML/Style/Image.php @@ -0,0 +1,47 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Image) { + return ''; + } + $css = array(); + + $width = $style->getWidth(); + $height = $style->getHeight(); + $css['width'] = $this->getValueIf(is_numeric($width), $width . 'px'); + $css['height'] = $this->getValueIf(is_numeric($height), $height . 'px'); + + return $this->assembleCss($css); + } +} diff --git a/src/PhpWord/Writer/HTML/Style/Paragraph.php b/src/PhpWord/Writer/HTML/Style/Paragraph.php new file mode 100644 index 00000000..8b326a5c --- /dev/null +++ b/src/PhpWord/Writer/HTML/Style/Paragraph.php @@ -0,0 +1,55 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Paragraph) { + return ''; + } + $css = array(); + + // Alignment + $align = $style->getAlign(); + $css['text-align'] = $this->getValueIf(!is_null($align), $align); + + // Spacing + $spacing = $style->getSpace(); + if (!is_null($spacing)) { + $before = $spacing->getBefore(); + $after = $spacing->getAfter(); + $css['margin-top'] = $this->getValueIf(!is_null($before), ($before / 20) . 'pt'); + $css['margin-bottom'] = $this->getValueIf(!is_null($after), ($after / 20) . 'pt'); + } + + return $this->assembleCss($css); + } +} diff --git a/src/PhpWord/Writer/ODText.php b/src/PhpWord/Writer/ODText.php old mode 100755 new mode 100644 index 50064708..8fa364be --- a/src/PhpWord/Writer/ODText.php +++ b/src/PhpWord/Writer/ODText.php @@ -1,76 +1,90 @@ setPhpWord($phpWord); - // Set writer parts - $this->writerParts['content'] = new Content(); - $this->writerParts['manifest'] = new Manifest(); - $this->writerParts['meta'] = new Meta(); - $this->writerParts['mimetype'] = new Mimetype(); - $this->writerParts['styles'] = new Styles(); - foreach ($this->writerParts as $writer) { - $writer->setParentWriter($this); + // Create parts + $this->parts = array( + 'Mimetype' => 'mimetype', + 'Content' => 'content.xml', + 'Meta' => 'meta.xml', + 'Styles' => 'styles.xml', + 'Manifest' => 'META-INF/manifest.xml', + ); + foreach (array_keys($this->parts) as $partName) { + $partClass = get_class($this) . '\\Part\\' . $partName; + if (class_exists($partClass)) { + /** @var $partObject \PhpOffice\PhpWord\Writer\ODText\Part\AbstractPart Type hint */ + $partObject = new $partClass(); + $partObject->setParentWriter($this); + $this->writerParts[strtolower($partName)] = $partObject; + } } + + // Set package paths + $this->mediaPaths = array('image' => 'Pictures/'); } /** - * Save PhpWord to file + * Save PhpWord to file. * - * @param string $filename - * @throws Exception - * @todo Not in \ZipArchive::CM_STORE mode + * @param string $filename + * @return void */ public function save($filename = null) { - if (!is_null($this->phpWord)) { - $filename = $this->getTempFile($filename); - $objZip = $this->getZipArchive($filename); + $filename = $this->getTempFile($filename); + $zip = $this->getZipArchive($filename); - // Add mimetype to ZIP file - $objZip->addFromString('mimetype', $this->getWriterPart('mimetype')->writeMimetype()); - $objZip->addFromString('content.xml', $this->getWriterPart('content')->writeContent($this->phpWord)); - $objZip->addFromString('meta.xml', $this->getWriterPart('meta')->writeMeta($this->phpWord)); - $objZip->addFromString('styles.xml', $this->getWriterPart('styles')->writeStyles($this->phpWord)); - $objZip->addFromString('META-INF/manifest.xml', $this->getWriterPart('manifest')->writeManifest()); - - // Close file - if ($objZip->close() === false) { - throw new Exception("Could not close zip file $filename."); - } - - $this->cleanupTempFile(); - } else { - throw new Exception("PhpWord object unassigned."); + // Add section media files + $sectionMedia = Media::getElements('section'); + if (!empty($sectionMedia)) { + $this->addFilesToPackage($zip, $sectionMedia); } + + // Write parts + foreach ($this->parts as $partName => $fileName) { + if ($fileName != '') { + $zip->addFromString($fileName, $this->getWriterPart($partName)->write()); + } + } + + // Close zip archive and cleanup temp file + $zip->close(); + $this->cleanupTempFile(); } } diff --git a/src/PhpWord/Writer/ODText/AbstractWriterPart.php b/src/PhpWord/Writer/ODText/AbstractWriterPart.php deleted file mode 100644 index 1a5831e0..00000000 --- a/src/PhpWord/Writer/ODText/AbstractWriterPart.php +++ /dev/null @@ -1,17 +0,0 @@ -getXmlWriter(); - - // XML header - $xmlWriter->startDocument('1.0', 'UTF-8'); - - // office:document-content - $xmlWriter->startElement('office:document-content'); - $this->writeCommonRootAttributes($xmlWriter); - $xmlWriter->writeAttribute('xmlns:xforms', 'http://www.w3.org/2002/xforms'); - $xmlWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema'); - $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); - $xmlWriter->writeAttribute('xmlns:field', 'urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0'); - $xmlWriter->writeAttribute('xmlns:formx', 'urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0'); - - // We firstly search all fonts used - $sections = $phpWord->getSections(); - $countSections = count($sections); - if ($countSections > 0) { - $pSection = 0; - $numPStyles = 0; - $numFStyles = 0; - - foreach ($sections as $section) { - $pSection++; - $elements = $section->getElements(); - - foreach ($elements as $element) { - if ($element instanceof Text) { - $fStyle = $element->getFontStyle(); - $pStyle = $element->getParagraphStyle(); - - if ($fStyle instanceof Font) { - $numFStyles++; - - $arrStyle = array( - 'color' => $fStyle->getColor(), - 'name' => $fStyle->getName() - ); - $phpWord->addFontStyle('T' . $numFStyles, $arrStyle); - $element->setFontStyle('T' . $numFStyles); - } elseif ($pStyle instanceof Paragraph) { - $numPStyles++; - - $phpWord->addParagraphStyle('P' . $numPStyles, array()); - $element->setParagraphStyle('P' . $numPStyles); - } - } - } - } - } - - - $this->writeFontFaces($xmlWriter); // office:font-face-decls - - $this->writeAutomaticStyles($xmlWriter); // office:automatic-styles - - // Tables - $sections = $phpWord->getSections(); - $countSections = count($sections); - if ($countSections > 0) { - $sectionId = 0; - foreach ($sections as $section) { - $sectionId++; - $elements = $section->getElements(); - foreach ($elements as $element) { - if ($elements instanceof Table) { - $xmlWriter->startElement('style:style'); - $xmlWriter->writeAttribute('style:name', $element->getElementId()); - $xmlWriter->writeAttribute('style:family', 'table'); - $xmlWriter->startElement('style:table-properties'); - //$xmlWriter->writeAttribute('style:width', 'table'); - $xmlWriter->writeAttribute('style:rel-width', 100); - $xmlWriter->writeAttribute('table:align', 'center'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } - } - } - } - - $xmlWriter->endElement(); - - // office:body - $xmlWriter->startElement('office:body'); - // office:text - $xmlWriter->startElement('office:text'); - // text:sequence-decls - $xmlWriter->startElement('text:sequence-decls'); - // text:sequence-decl - $xmlWriter->startElement('text:sequence-decl'); - $xmlWriter->writeAttribute('text:display-outline-level', 0); - $xmlWriter->writeAttribute('text:name', 'Illustration'); - $xmlWriter->endElement(); - // text:sequence-decl - $xmlWriter->startElement('text:sequence-decl'); - $xmlWriter->writeAttribute('text:display-outline-level', 0); - $xmlWriter->writeAttribute('text:name', 'Table'); - $xmlWriter->endElement(); - // text:sequence-decl - $xmlWriter->startElement('text:sequence-decl'); - $xmlWriter->writeAttribute('text:display-outline-level', 0); - $xmlWriter->writeAttribute('text:name', 'Text'); - $xmlWriter->endElement(); - // text:sequence-decl - $xmlWriter->startElement('text:sequence-decl'); - $xmlWriter->writeAttribute('text:display-outline-level', 0); - $xmlWriter->writeAttribute('text:name', 'Drawing'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - $sections = $phpWord->getSections(); - $countSections = count($sections); - if ($countSections > 0) { - foreach ($sections as $section) { - $elements = $section->getElements(); - - foreach ($elements as $element) { - if ($element instanceof Text) { - $this->writeText($xmlWriter, $element); - } elseif ($element instanceof TextRun) { - $this->writeTextRun($xmlWriter, $element); - } elseif ($element instanceof Link) { - $this->writeLink($xmlWriter, $element); - } elseif ($element instanceof Title) { - $this->writeTitle($xmlWriter, $element); - } elseif ($element instanceof ListItem) { - $this->writeListItem($xmlWriter, $element); - } elseif ($element instanceof TextBreak) { - $this->writeTextBreak($xmlWriter); - } elseif ($element instanceof PageBreak) { - $this->writePageBreak($xmlWriter); - } elseif ($element instanceof Table) { - $this->writeTable($xmlWriter, $element); - } elseif ($element instanceof Image) { - $this->writeImage($xmlWriter, $element); - } elseif ($element instanceof Object) { - $this->writeObject($xmlWriter, $element); - } - } - } - } - $xmlWriter->endElement(); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - // Return - return $xmlWriter->getData(); - } - - /** - * Write text - * - * @param bool $withoutP - */ - protected function writeText(XMLWriter $xmlWriter, Text $text, $withoutP = false) - { - $styleFont = $text->getFontStyle(); - $styleParagraph = $text->getParagraphStyle(); - - // @todo Commented for TextRun. Should really checkout this value - // $SfIsObject = ($styleFont instanceof Font) ? true : false; - $SfIsObject = false; - - if ($SfIsObject) { - // Don't never be the case, because I browse all sections for cleaning all styles not declared - die('PhpWord : $SfIsObject wouldn\'t be an object'); - } else { - if (!$withoutP) { - $xmlWriter->startElement('text:p'); // text:p - } - if (empty($styleFont)) { - if (empty($styleParagraph)) { - $xmlWriter->writeAttribute('text:style-name', 'P1'); - } elseif (is_string($styleParagraph)) { - $xmlWriter->writeAttribute('text:style-name', $styleParagraph); - } - $xmlWriter->writeRaw($text->getText()); - } else { - if (empty($styleParagraph)) { - $xmlWriter->writeAttribute('text:style-name', 'Standard'); - } elseif (is_string($styleParagraph)) { - $xmlWriter->writeAttribute('text:style-name', $styleParagraph); - } - // text:span - $xmlWriter->startElement('text:span'); - if (is_string($styleFont)) { - $xmlWriter->writeAttribute('text:style-name', $styleFont); - } - $xmlWriter->writeRaw($text->getText()); - $xmlWriter->endElement(); - } - if (!$withoutP) { - $xmlWriter->endElement(); // text:p - } - } - } - - /** - * Write TextRun section - * - * @todo Enable all other section types - */ - protected function writeTextRun(XMLWriter $xmlWriter, TextRun $textrun) - { - $elements = $textrun->getElements(); - $xmlWriter->startElement('text:p'); - if (count($elements) > 0) { - foreach ($elements as $element) { - if ($element instanceof Text) { - $this->writeText($xmlWriter, $element, true); - } - } - } - $xmlWriter->endElement(); - } - - /** - * Write link element - */ - protected function writeLink(XMLWriter $xmlWriter, Link $link) - { - $this->writeUnsupportedElement($xmlWriter, 'Link'); - } - - /** - * Write title element - */ - protected function writeTitle(XMLWriter $xmlWriter, Title $title) - { - $this->writeUnsupportedElement($xmlWriter, 'Title'); - } - - /** - * Write preserve text - */ - protected function writePreserveText(XMLWriter $xmlWriter, PreserveText $preservetext) - { - $this->writeUnsupportedElement($xmlWriter, 'PreserveText'); - } - - /** - * Write list item - */ - protected function writeListItem(XMLWriter $xmlWriter, ListItem $listItem) - { - $this->writeUnsupportedElement($xmlWriter, 'ListItem'); - } - - /** - * Write text break - */ - protected function writeTextBreak(XMLWriter $xmlWriter) - { - $xmlWriter->startElement('text:p'); - $xmlWriter->writeAttribute('text:style-name', 'Standard'); - $xmlWriter->endElement(); - } - - /** - * Write page break - */ - protected function writePageBreak(XMLWriter $xmlWriter) - { - $this->writeUnsupportedElement($xmlWriter, 'PageBreak'); - } - - /** - * Write table - */ - protected function writeTable(XMLWriter $xmlWriter, Table $table) - { - $rows = $table->getRows(); - $rowCount = count($rows); - $colCount = $table->countColumns(); - if ($rowCount > 0) { - $xmlWriter->startElement('table:table'); - $xmlWriter->writeAttribute('table:name', $table->getElementId()); - $xmlWriter->writeAttribute('table:style', $table->getElementId()); - - $xmlWriter->startElement('table:table-column'); - $xmlWriter->writeAttribute('table:number-columns-repeated', $colCount); - $xmlWriter->endElement(); // table:table-column - - foreach ($rows as $row) { - $xmlWriter->startElement('table:table-row'); - foreach ($row->getCells() as $cell) { - $xmlWriter->startElement('table:table-cell'); - $xmlWriter->writeAttribute('office:value-type', 'string'); - $elements = $cell->getElements(); - if (count($elements) > 0) { - foreach ($elements as $element) { - if ($element instanceof Text) { - $this->writeText($xmlWriter, $element); - } elseif ($element instanceof TextRun) { - $this->writeTextRun($xmlWriter, $element); - } elseif ($element instanceof ListItem) { - $this->writeListItem($xmlWriter, $element); - } elseif ($element instanceof TextBreak) { - $this->writeTextBreak($xmlWriter); - } elseif ($element instanceof Image) { - $this->writeImage($xmlWriter, $element); - } elseif ($element instanceof Object) { - $this->writeObject($xmlWriter, $element); - } - } - } else { - $this->writeTextBreak($xmlWriter); - } - $xmlWriter->endElement(); // table:table-cell - } - $xmlWriter->endElement(); // table:table-row - } - $xmlWriter->endElement(); // table:table - } - } - - /** - * Write image - */ - protected function writeImage(XMLWriter $xmlWriter, Image $element) - { - $this->writeUnsupportedElement($xmlWriter, 'Image'); - } - - /** - * Write object - */ - protected function writeObject(XMLWriter $xmlWriter, Object $element) - { - $this->writeUnsupportedElement($xmlWriter, 'Object'); - } - - /** - * Write unsupported element - * - * @param string $element - */ - private function writeUnsupportedElement(XMLWriter $xmlWriter, $element) - { - $xmlWriter->startElement('text:p'); - $xmlWriter->writeRaw($element); - $xmlWriter->endElement(); - } - - /** - * Write automatic styles - */ - private function writeAutomaticStyles(XMLWriter $xmlWriter) - { - $xmlWriter->startElement('office:automatic-styles'); - $styles = Style::getStyles(); - $numPStyles = 0; - if (count($styles) > 0) { - foreach ($styles as $styleName => $style) { - if (preg_match('#^T[0-9]+$#', $styleName) != 0 - || preg_match('#^P[0-9]+$#', $styleName) != 0 - ) { - // Font - if ($style instanceof Font) { - $xmlWriter->startElement('style:style'); - $xmlWriter->writeAttribute('style:name', $styleName); - $xmlWriter->writeAttribute('style:family', 'text'); - // style:text-properties - $xmlWriter->startElement('style:text-properties'); - $xmlWriter->writeAttribute('fo:color', '#' . $style->getColor()); - $xmlWriter->writeAttribute('style:font-name', $style->getName()); - $xmlWriter->writeAttribute('style:font-name-complex', $style->getName()); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } - if ($style instanceof Paragraph) { - $numPStyles++; - // style:style - $xmlWriter->startElement('style:style'); - $xmlWriter->writeAttribute('style:name', $styleName); - $xmlWriter->writeAttribute('style:family', 'paragraph'); - $xmlWriter->writeAttribute('style:parent-style-name', 'Standard'); - $xmlWriter->writeAttribute('style:master-page-name', 'Standard'); - // style:paragraph-properties - $xmlWriter->startElement('style:paragraph-properties'); - $xmlWriter->writeAttribute('style:page-number', 'auto'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } - } - } - - if ($numPStyles == 0) { - // style:style - $xmlWriter->startElement('style:style'); - $xmlWriter->writeAttribute('style:name', 'P1'); - $xmlWriter->writeAttribute('style:family', 'paragraph'); - $xmlWriter->writeAttribute('style:parent-style-name', 'Standard'); - $xmlWriter->writeAttribute('style:master-page-name', 'Standard'); - // style:paragraph-properties - $xmlWriter->startElement('style:paragraph-properties'); - $xmlWriter->writeAttribute('style:page-number', 'auto'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } - } - } -} diff --git a/src/PhpWord/Writer/ODText/Element/AbstractElement.php b/src/PhpWord/Writer/ODText/Element/AbstractElement.php new file mode 100644 index 00000000..9fb24364 --- /dev/null +++ b/src/PhpWord/Writer/ODText/Element/AbstractElement.php @@ -0,0 +1,29 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Image) { + return; + } + + $mediaIndex = $element->getMediaIndex(); + $target = 'Pictures/' . $element->getTarget(); + $style = $element->getStyle(); + $width = Converter::pixelToCm($style->getWidth()); + $height = Converter::pixelToCm($style->getHeight()); + + $xmlWriter->startElement('text:p'); + $xmlWriter->writeAttribute('text:style-name', 'Standard'); + + $xmlWriter->startElement('draw:frame'); + $xmlWriter->writeAttribute('draw:style-name', 'fr' . $mediaIndex); + $xmlWriter->writeAttribute('draw:name', $element->getElementId()); + $xmlWriter->writeAttribute('text:anchor-type', 'as-char'); + $xmlWriter->writeAttribute('svg:width', $width . 'cm'); + $xmlWriter->writeAttribute('svg:height', $height . 'cm'); + $xmlWriter->writeAttribute('draw:z-index', $mediaIndex); + + $xmlWriter->startElement('draw:image'); + $xmlWriter->writeAttribute('xlink:href', $target); + $xmlWriter->writeAttribute('xlink:type', 'simple'); + $xmlWriter->writeAttribute('xlink:show', 'embed'); + $xmlWriter->writeAttribute('xlink:actuate', 'onLoad'); + $xmlWriter->endElement(); // draw:image + + $xmlWriter->endElement(); // draw:frame + + $xmlWriter->endElement(); // text:p + } +} diff --git a/src/PhpWord/Writer/ODText/Element/Link.php b/src/PhpWord/Writer/ODText/Element/Link.php new file mode 100644 index 00000000..adb64f85 --- /dev/null +++ b/src/PhpWord/Writer/ODText/Element/Link.php @@ -0,0 +1,52 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Link) { + return; + } + + if (!$this->withoutP) { + $xmlWriter->startElement('text:p'); // text:p + } + + $xmlWriter->startElement('text:a'); + $xmlWriter->writeAttribute('xlink:type', 'simple'); + $xmlWriter->writeAttribute('xlink:href', $element->getSource()); + $xmlWriter->writeRaw($element->getText()); + $xmlWriter->endElement(); // text:a + + if (!$this->withoutP) { + $xmlWriter->endElement(); // text:p + } + } +} diff --git a/src/PhpWord/Writer/ODText/Element/Table.php b/src/PhpWord/Writer/ODText/Element/Table.php new file mode 100644 index 00000000..f26960b8 --- /dev/null +++ b/src/PhpWord/Writer/ODText/Element/Table.php @@ -0,0 +1,67 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Table) { + return; + } + $rows = $element->getRows(); + $rowCount = count($rows); + $colCount = $element->countColumns(); + + if ($rowCount > 0) { + $xmlWriter->startElement('table:table'); + $xmlWriter->writeAttribute('table:name', $element->getElementId()); + $xmlWriter->writeAttribute('table:style', $element->getElementId()); + + $xmlWriter->startElement('table:table-column'); + $xmlWriter->writeAttribute('table:number-columns-repeated', $colCount); + $xmlWriter->endElement(); // table:table-column + + foreach ($rows as $row) { + $xmlWriter->startElement('table:table-row'); + /** @var $row \PhpOffice\PhpWord\Element\Row Type hint */ + foreach ($row->getCells() as $cell) { + $xmlWriter->startElement('table:table-cell'); + $xmlWriter->writeAttribute('office:value-type', 'string'); + + $containerWriter = new Container($xmlWriter, $cell); + $containerWriter->write(); + + $xmlWriter->endElement(); // table:table-cell + } + $xmlWriter->endElement(); // table:table-row + } + $xmlWriter->endElement(); // table:table + } + } +} diff --git a/src/PhpWord/Writer/ODText/Element/Text.php b/src/PhpWord/Writer/ODText/Element/Text.php new file mode 100644 index 00000000..4fc53bfe --- /dev/null +++ b/src/PhpWord/Writer/ODText/Element/Text.php @@ -0,0 +1,79 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Text) { + return; + } + $fontStyle = $element->getFontStyle(); + $paragraphStyle = $element->getParagraphStyle(); + + // @todo Commented for TextRun. Should really checkout this value + // $fStyleIsObject = ($fontStyle instanceof Font) ? true : false; + $fStyleIsObject = false; + + if ($fStyleIsObject) { + // Don't never be the case, because I browse all sections for cleaning all styles not declared + throw new Exception('PhpWord : $fStyleIsObject wouldn\'t be an object'); + } else { + if (!$this->withoutP) { + $xmlWriter->startElement('text:p'); // text:p + } + if (empty($fontStyle)) { + if (empty($paragraphStyle)) { + $xmlWriter->writeAttribute('text:style-name', 'P1'); + } elseif (is_string($paragraphStyle)) { + $xmlWriter->writeAttribute('text:style-name', $paragraphStyle); + } + $xmlWriter->writeRaw($element->getText()); + } else { + if (empty($paragraphStyle)) { + $xmlWriter->writeAttribute('text:style-name', 'Standard'); + } elseif (is_string($paragraphStyle)) { + $xmlWriter->writeAttribute('text:style-name', $paragraphStyle); + } + // text:span + $xmlWriter->startElement('text:span'); + if (is_string($fontStyle)) { + $xmlWriter->writeAttribute('text:style-name', $fontStyle); + } + $xmlWriter->writeRaw($element->getText()); + $xmlWriter->endElement(); + } + if (!$this->withoutP) { + $xmlWriter->endElement(); // text:p + } + } + } +} diff --git a/src/PhpWord/Writer/ODText/Element/TextBreak.php b/src/PhpWord/Writer/ODText/Element/TextBreak.php new file mode 100644 index 00000000..ef3186f4 --- /dev/null +++ b/src/PhpWord/Writer/ODText/Element/TextBreak.php @@ -0,0 +1,38 @@ +getXmlWriter(); + + $xmlWriter->startElement('text:p'); + $xmlWriter->writeAttribute('text:style-name', 'Standard'); + $xmlWriter->endElement(); + } +} diff --git a/src/PhpWord/Writer/ODText/Element/TextRun.php b/src/PhpWord/Writer/ODText/Element/TextRun.php new file mode 100644 index 00000000..52240e8f --- /dev/null +++ b/src/PhpWord/Writer/ODText/Element/TextRun.php @@ -0,0 +1,42 @@ +getXmlWriter(); + $element = $this->getElement(); + + $xmlWriter->startElement('text:p'); + + $containerWriter = new Container($xmlWriter, $element); + $containerWriter->write(); + + $xmlWriter->endElement(); + } +} diff --git a/src/PhpWord/Writer/ODText/Element/Title.php b/src/PhpWord/Writer/ODText/Element/Title.php new file mode 100644 index 00000000..d45f5e12 --- /dev/null +++ b/src/PhpWord/Writer/ODText/Element/Title.php @@ -0,0 +1,43 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Title) { + return; + } + + $xmlWriter->startElement('text:h'); + $xmlWriter->writeAttribute('text:outline-level', $element->getDepth()); + $xmlWriter->writeRaw($element->getText()); + $xmlWriter->endElement(); // text:h + } +} diff --git a/src/PhpWord/Writer/ODText/Manifest.php b/src/PhpWord/Writer/ODText/Manifest.php deleted file mode 100755 index 220834c4..00000000 --- a/src/PhpWord/Writer/ODText/Manifest.php +++ /dev/null @@ -1,62 +0,0 @@ -getXmlWriter(); - - // XML header - $xmlWriter->startDocument('1.0', 'UTF-8'); - - // manifest:manifest - $xmlWriter->startElement('manifest:manifest'); - $xmlWriter->writeAttribute('manifest:version', '1.2'); - $xmlWriter->writeAttribute('xmlns:manifest', 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0'); - - // manifest:file-entry - $xmlWriter->startElement('manifest:file-entry'); - $xmlWriter->writeAttribute('manifest:media-type', 'application/vnd.oasis.opendocument.text'); - $xmlWriter->writeAttribute('manifest:version', '1.2'); - $xmlWriter->writeAttribute('manifest:full-path', '/'); - $xmlWriter->endElement(); - // manifest:file-entry - $xmlWriter->startElement('manifest:file-entry'); - $xmlWriter->writeAttribute('manifest:media-type', 'text/xml'); - $xmlWriter->writeAttribute('manifest:full-path', 'content.xml'); - $xmlWriter->endElement(); - // manifest:file-entry - $xmlWriter->startElement('manifest:file-entry'); - $xmlWriter->writeAttribute('manifest:media-type', 'text/xml'); - $xmlWriter->writeAttribute('manifest:full-path', 'meta.xml'); - $xmlWriter->endElement(); - // manifest:file-entry - $xmlWriter->startElement('manifest:file-entry'); - $xmlWriter->writeAttribute('manifest:media-type', 'text/xml'); - $xmlWriter->writeAttribute('manifest:full-path', 'styles.xml'); - $xmlWriter->endElement(); - - $xmlWriter->endElement(); // manifest:manifest - - // Return - return $xmlWriter->getData(); - } -} diff --git a/src/PhpWord/Writer/ODText/Meta.php b/src/PhpWord/Writer/ODText/Meta.php deleted file mode 100644 index 8feb0d30..00000000 --- a/src/PhpWord/Writer/ODText/Meta.php +++ /dev/null @@ -1,78 +0,0 @@ -getXmlWriter(); - - // XML header - $xmlWriter->startDocument('1.0', 'UTF-8'); - - // office:document-meta - $xmlWriter->startElement('office:document-meta'); - $xmlWriter->writeAttribute('office:version', '1.2'); - $xmlWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); - $xmlWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); - $xmlWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); - $xmlWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); - $xmlWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); - $xmlWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#'); - - // office:meta - $xmlWriter->startElement('office:meta'); - - // dc:creator - $xmlWriter->writeElement('dc:creator', $phpWord->getDocumentProperties()->getLastModifiedBy()); - // dc:date - $xmlWriter->writeElement('dc:date', gmdate('Y-m-d\TH:i:s.000', $phpWord->getDocumentProperties()->getModified())); - // dc:description - $xmlWriter->writeElement('dc:description', $phpWord->getDocumentProperties()->getDescription()); - // dc:subject - $xmlWriter->writeElement('dc:subject', $phpWord->getDocumentProperties()->getSubject()); - // dc:title - $xmlWriter->writeElement('dc:title', $phpWord->getDocumentProperties()->getTitle()); - // meta:creation-date - $xmlWriter->writeElement('meta:creation-date', gmdate('Y-m-d\TH:i:s.000', $phpWord->getDocumentProperties()->getCreated())); - // meta:initial-creator - $xmlWriter->writeElement('meta:initial-creator', $phpWord->getDocumentProperties()->getCreator()); - // meta:keyword - $xmlWriter->writeElement('meta:keyword', $phpWord->getDocumentProperties()->getKeywords()); - - // @todo : Where these properties are written ? - // $phpWord->getDocumentProperties()->getCategory() - // $phpWord->getDocumentProperties()->getCompany() - - $xmlWriter->endElement(); - - $xmlWriter->endElement(); - - // Return - return $xmlWriter->getData(); - } -} diff --git a/src/PhpWord/Writer/ODText/Mimetype.php b/src/PhpWord/Writer/ODText/Mimetype.php deleted file mode 100644 index 269c377f..00000000 --- a/src/PhpWord/Writer/ODText/Mimetype.php +++ /dev/null @@ -1,26 +0,0 @@ -startElement('office:font-face-decls'); - $arrFonts = array(); + $fontTable = array(); $styles = Style::getStyles(); $numFonts = 0; if (count($styles) > 0) { - foreach ($styles as $styleName => $style) { + foreach ($styles as $style) { // Font if ($style instanceof Font) { $numFonts++; $name = $style->getName(); - if (!in_array($name, $arrFonts)) { - $arrFonts[] = $name; + if (!in_array($name, $fontTable)) { + $fontTable[] = $name; // style:font-face $xmlWriter->startElement('style:font-face'); @@ -82,10 +100,10 @@ class Base extends AbstractWriterPart } } } - if (!in_array(PhpWord::DEFAULT_FONT_NAME, $arrFonts)) { + if (!in_array(Settings::getDefaultFontName(), $fontTable)) { $xmlWriter->startElement('style:font-face'); - $xmlWriter->writeAttribute('style:name', PhpWord::DEFAULT_FONT_NAME); - $xmlWriter->writeAttribute('svg:font-family', PhpWord::DEFAULT_FONT_NAME); + $xmlWriter->writeAttribute('style:name', Settings::getDefaultFontName()); + $xmlWriter->writeAttribute('svg:font-family', Settings::getDefaultFontName()); $xmlWriter->endElement(); } $xmlWriter->endElement(); diff --git a/src/PhpWord/Writer/ODText/Part/Content.php b/src/PhpWord/Writer/ODText/Part/Content.php new file mode 100644 index 00000000..4bde66ee --- /dev/null +++ b/src/PhpWord/Writer/ODText/Part/Content.php @@ -0,0 +1,252 @@ + array(), 'Image' => array(), 'Table' => array()); + + /** + * Write part + * + * @return string + */ + public function write() + { + $xmlWriter = $this->getXmlWriter(); + $phpWord = $this->getParentWriter()->getPhpWord(); + + $this->getAutoStyles($phpWord); + + $xmlWriter->startDocument('1.0', 'UTF-8'); + $xmlWriter->startElement('office:document-content'); + $this->writeCommonRootAttributes($xmlWriter); + $xmlWriter->writeAttribute('xmlns:xforms', 'http://www.w3.org/2002/xforms'); + $xmlWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema'); + $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); + $xmlWriter->writeAttribute('xmlns:field', 'urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0'); + $xmlWriter->writeAttribute('xmlns:formx', 'urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0'); + + // Font declarations and automatic styles + $this->writeFontFaces($xmlWriter); // office:font-face-decls + $this->writeAutoStyles($xmlWriter); // office:automatic-styles + + // Body + $xmlWriter->startElement('office:body'); + $xmlWriter->startElement('office:text'); + + // Sequence declarations + $sequences = array('Illustration', 'Table', 'Text', 'Drawing'); + $xmlWriter->startElement('text:sequence-decls'); + foreach ($sequences as $sequence) { + $xmlWriter->startElement('text:sequence-decl'); + $xmlWriter->writeAttribute('text:display-outline-level', 0); + $xmlWriter->writeAttribute('text:name', $sequence); + $xmlWriter->endElement(); + } + $xmlWriter->endElement(); // text:sequence-decl + + // Sections + $sections = $phpWord->getSections(); + foreach ($sections as $section) { + $name = 'Section' . $section->getSectionId(); + $xmlWriter->startElement('text:section'); + $xmlWriter->writeAttribute('text:name', $name); + $xmlWriter->writeAttribute('text:style-name', $name); + $containerWriter = new Container($xmlWriter, $section); + $containerWriter->write(); + $xmlWriter->endElement(); // text:section + } + + $xmlWriter->endElement(); // office:text + $xmlWriter->endElement(); // office:body + + $xmlWriter->endElement(); // office:document-content + + return $xmlWriter->getData(); + } + + /** + * Write automatic styles other than fonts and paragraphs. + * + * @since 0.11.0 + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @return void + */ + private function writeAutoStyles(XMLWriter $xmlWriter) + { + $xmlWriter->startElement('office:automatic-styles'); + + $this->writeTextStyles($xmlWriter); + foreach ($this->autoStyles as $element => $styles) { + $writerClass = 'PhpOffice\\PhpWord\\Writer\\ODText\\Style\\' . $element; + foreach ($styles as $style) { + + /** @var \PhpOffice\PhpWord\Writer\ODText\Style\AbstractStyle $styleWriter Type hint */ + $styleWriter = new $writerClass($xmlWriter, $style); + $styleWriter->write(); + } + } + + $xmlWriter->endElement(); // office:automatic-styles + } + + /** + * Write automatic styles. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @return void + */ + private function writeTextStyles(XMLWriter $xmlWriter) + { + $styles = Style::getStyles(); + $paragraphStyleCount = 0; + if (count($styles) > 0) { + foreach ($styles as $style) { + if ($style->isAuto() === true) { + $styleClass = str_replace('\\Style\\', '\\Writer\\ODText\\Style\\', get_class($style)); + if (class_exists($styleClass)) { + /** @var \PhpOffice\PhpWord\Writer\ODText\Style\AbstractStyle $styleWriter Type hint */ + $styleWriter = new $styleClass($xmlWriter, $style); + $styleWriter->write(); + } + if ($style instanceof Paragraph) { + $paragraphStyleCount++; + } + } + } + if ($paragraphStyleCount == 0) { + $style = new Paragraph(); + $style->setStyleName('P1'); + $style->setAuto(); + $styleWriter = new ParagraphStyleWriter($xmlWriter, $style); + $styleWriter->write(); + } + } + } + + /** + * Get automatic styles. + * + * @param \PhpOffice\PhpWord\PhpWord $phpWord + * @return void + */ + private function getAutoStyles(PhpWord $phpWord) + { + $sections = $phpWord->getSections(); + $paragraphStyleCount = 0; + $fontStyleCount = 0; + foreach ($sections as $section) { + $style = $section->getStyle(); + $style->setStyleName("Section{$section->getSectionId()}"); + $this->autoStyles['Section'][] = $style; + $this->getContainerStyle($section, $paragraphStyleCount, $fontStyleCount); + } + } + + /** + * Get all styles of each elements in container recursively + * + * Table style can be null or string of the style name + * + * @param \PhpOffice\PhpWord\Element\AbstractContainer $container + * @param int &$paragraphStyleCount + * @param int &$fontStyleCount + * @return void + * @todo Simplify the logic + */ + private function getContainerStyle($container, &$paragraphStyleCount, &$fontStyleCount) + { + $elements = $container->getElements(); + foreach ($elements as $element) { + if ($element instanceof TextRun) { + $this->getContainerStyle($element, $paragraphStyleCount, $fontStyleCount); + } elseif ($element instanceof Text) { + $this->getElementStyle($element, $paragraphStyleCount, $fontStyleCount); + } elseif ($element instanceof Image) { + $style = $element->getStyle(); + $style->setStyleName('fr' . $element->getMediaIndex()); + $this->autoStyles['Image'][] = $style; + } elseif ($element instanceof Table) { + $style = $element->getStyle(); + if ($style === null) { + $style = new TableStyle(); + } elseif (is_string($style)) { + $style = Style::getStyle($style); + } + $style->setStyleName($element->getElementId()); + $this->autoStyles['Table'][] = $style; + } + } + } + + /** + * Get style of individual element + * + * @param \PhpOffice\PhpWord\Element\Text &$element + * @param int &$paragraphStyleCount + * @param int &$fontStyleCount + * @return void + */ + private function getElementStyle(&$element, &$paragraphStyleCount, &$fontStyleCount) + { + $fontStyle = $element->getFontStyle(); + $paragraphStyle = $element->getParagraphStyle(); + $phpWord = $this->getParentWriter()->getPhpWord(); + + // Font + if ($fontStyle instanceof Font) { + $fontStyleCount++; + $style = $phpWord->addFontStyle("T{$fontStyleCount}", $fontStyle); + $style->setAuto(); + $element->setFontStyle("T{$fontStyleCount}"); + + // Paragraph + } elseif ($paragraphStyle instanceof Paragraph) { + $paragraphStyleCount++; + $style = $phpWord->addParagraphStyle("P{$paragraphStyleCount}", array()); + $style->setAuto(); + $element->setParagraphStyle("P{$paragraphStyleCount}"); + } + } +} diff --git a/src/PhpWord/Writer/ODText/Part/Manifest.php b/src/PhpWord/Writer/ODText/Part/Manifest.php new file mode 100644 index 00000000..7c695e9b --- /dev/null +++ b/src/PhpWord/Writer/ODText/Part/Manifest.php @@ -0,0 +1,71 @@ +getXmlWriter(); + + $xmlWriter->startDocument('1.0', 'UTF-8'); + $xmlWriter->startElement('manifest:manifest'); + $xmlWriter->writeAttribute('manifest:version', '1.2'); + $xmlWriter->writeAttribute('xmlns:manifest', 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0'); + + $xmlWriter->startElement('manifest:file-entry'); + $xmlWriter->writeAttribute('manifest:media-type', 'application/vnd.oasis.opendocument.text'); + $xmlWriter->writeAttribute('manifest:full-path', '/'); + $xmlWriter->writeAttribute('manifest:version', '1.2'); + $xmlWriter->endElement(); + + // Parts + foreach ($parts as $part) { + $xmlWriter->startElement('manifest:file-entry'); + $xmlWriter->writeAttribute('manifest:media-type', 'text/xml'); + $xmlWriter->writeAttribute('manifest:full-path', $part); + $xmlWriter->endElement(); + } + + // Media files + $media = Media::getElements('section'); + foreach ($media as $medium) { + if ($medium['type'] == 'image') { + $xmlWriter->startElement('manifest:file-entry'); + $xmlWriter->writeAttribute('manifest:media-type', $medium['imageType']); + $xmlWriter->writeAttribute('manifest:full-path', 'Pictures/' . $medium['target']); + $xmlWriter->endElement(); + } + } + + $xmlWriter->endElement(); // manifest:manifest + + return $xmlWriter->getData(); + } +} diff --git a/src/PhpWord/Writer/ODText/Part/Meta.php b/src/PhpWord/Writer/ODText/Part/Meta.php new file mode 100644 index 00000000..15c81a4e --- /dev/null +++ b/src/PhpWord/Writer/ODText/Part/Meta.php @@ -0,0 +1,106 @@ +getParentWriter()->getPhpWord(); + $docProps = $phpWord->getDocInfo(); + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startDocument('1.0', 'UTF-8'); + $xmlWriter->startElement('office:document-meta'); + $xmlWriter->writeAttribute('office:version', '1.2'); + $xmlWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); + $xmlWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); + $xmlWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); + $xmlWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); + $xmlWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); + $xmlWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#'); + $xmlWriter->startElement('office:meta'); + + // Core properties + $xmlWriter->writeElement('dc:title', $docProps->getTitle()); + $xmlWriter->writeElement('dc:subject', $docProps->getSubject()); + $xmlWriter->writeElement('dc:description', $docProps->getDescription()); + $xmlWriter->writeElement('dc:creator', $docProps->getLastModifiedBy()); + $xmlWriter->writeElement('dc:date', gmdate($this->dateFormat, $docProps->getModified())); + + // Extended properties + $xmlWriter->writeElement('meta:generator', 'PHPWord'); + $xmlWriter->writeElement('meta:initial-creator', $docProps->getCreator()); + $xmlWriter->writeElement('meta:creation-date', gmdate($this->dateFormat, $docProps->getCreated())); + $xmlWriter->writeElement('meta:keyword', $docProps->getKeywords()); + + // Category, company, and manager are put in meta namespace + $properties = array('Category', 'Company', 'Manager'); + foreach ($properties as $property) { + $method = "get{$property}"; + if ($docProps->$method() !== null) { + $this->writeCustomProperty($xmlWriter, $property, $docProps->$method()); + } + } + + // Other custom properties + // @todo Check type. Currently all assumed as string + foreach ($docProps->getCustomProperties() as $property) { + $value = $docProps->getCustomPropertyValue($property); + $this->writeCustomProperty($xmlWriter, $property, $value); + } + + $xmlWriter->endElement(); // office:meta + $xmlWriter->endElement(); // office:document-meta + + return $xmlWriter->getData(); + } + + /** + * Write individual property + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param string $property + * @param string $value + * @return void + * + * @todo Handle other `$type`: double|date|dateTime|duration|boolean (4th arguments) + */ + private function writeCustomProperty(XMLWriter $xmlWriter, $property, $value) + { + $xmlWriter->startElement('meta:user-defined'); + $xmlWriter->writeAttribute('meta:name', $property); + // if ($type !== null) { + // $xmlWriter->writeAttribute('meta:value-type', $type); + // } + $xmlWriter->writeRaw($value); + $xmlWriter->endElement(); // meta:user-defined + } +} diff --git a/src/PhpWord/Writer/ODText/Part/Mimetype.php b/src/PhpWord/Writer/ODText/Part/Mimetype.php new file mode 100644 index 00000000..1da4edb0 --- /dev/null +++ b/src/PhpWord/Writer/ODText/Part/Mimetype.php @@ -0,0 +1,34 @@ +getXmlWriter(); + + // XML header + $xmlWriter->startDocument('1.0', 'UTF-8'); + $xmlWriter->startElement('office:document-styles'); + $this->writeCommonRootAttributes($xmlWriter); + + // Font declarations + $this->writeFontFaces($xmlWriter); + + // Office styles + $xmlWriter->startElement('office:styles'); + $this->writeDefault($xmlWriter); + $this->writeNamed($xmlWriter); + $xmlWriter->endElement(); + + // Automatic styles + $xmlWriter->startElement('office:automatic-styles'); + $this->writePageLayout($xmlWriter); + $this->writeMaster($xmlWriter); + $xmlWriter->endElement(); + + $xmlWriter->endElement(); // office:document-styles + + return $xmlWriter->getData(); + } + + /** + * Write default styles. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @return void + */ + private function writeDefault(XMLWriter $xmlWriter) + { + $xmlWriter->startElement('style:default-style'); + $xmlWriter->writeAttribute('style:family', 'paragraph'); + + // Paragraph + $xmlWriter->startElement('style:paragraph-properties'); + $xmlWriter->writeAttribute('fo:hyphenation-ladder-count', 'no-limit'); + $xmlWriter->writeAttribute('style:text-autospace', 'ideograph-alpha'); + $xmlWriter->writeAttribute('style:punctuation-wrap', 'hanging'); + $xmlWriter->writeAttribute('style:line-break', 'strict'); + $xmlWriter->writeAttribute('style:tab-stop-distance', '1.249cm'); + $xmlWriter->writeAttribute('style:writing-mode', 'page'); + $xmlWriter->endElement(); // style:paragraph-properties + + // Font + $xmlWriter->startElement('style:text-properties'); + $xmlWriter->writeAttribute('style:use-window-font-color', 'true'); + $xmlWriter->writeAttribute('style:font-name', Settings::getDefaultFontName()); + $xmlWriter->writeAttribute('fo:font-size', Settings::getDefaultFontSize() . 'pt'); + $xmlWriter->writeAttribute('fo:language', 'fr'); + $xmlWriter->writeAttribute('fo:country', 'FR'); + $xmlWriter->writeAttribute('style:letter-kerning', 'true'); + $xmlWriter->writeAttribute('style:font-name-asian', Settings::getDefaultFontName() . '2'); + $xmlWriter->writeAttribute('style:font-size-asian', Settings::getDefaultFontSize() . 'pt'); + $xmlWriter->writeAttribute('style:language-asian', 'zh'); + $xmlWriter->writeAttribute('style:country-asian', 'CN'); + $xmlWriter->writeAttribute('style:font-name-complex', Settings::getDefaultFontName() . '2'); + $xmlWriter->writeAttribute('style:font-size-complex', Settings::getDefaultFontSize() . 'pt'); + $xmlWriter->writeAttribute('style:language-complex', 'hi'); + $xmlWriter->writeAttribute('style:country-complex', 'IN'); + $xmlWriter->writeAttribute('fo:hyphenate', 'false'); + $xmlWriter->writeAttribute('fo:hyphenation-remain-char-count', '2'); + $xmlWriter->writeAttribute('fo:hyphenation-push-char-count', '2'); + $xmlWriter->endElement(); // style:text-properties + + $xmlWriter->endElement(); // style:default-style + } + + /** + * Write named styles. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @return void + */ + private function writeNamed(XMLWriter $xmlWriter) + { + $styles = Style::getStyles(); + if (count($styles) > 0) { + foreach ($styles as $style) { + if ($style->isAuto() === false) { + $styleClass = str_replace('\\Style\\', '\\Writer\\ODText\\Style\\', get_class($style)); + if (class_exists($styleClass)) { + /** @var $styleWriter \PhpOffice\PhpWord\Writer\ODText\Style\AbstractStyle Type hint */ + $styleWriter = new $styleClass($xmlWriter, $style); + $styleWriter->write(); + } + } + } + } + } + /** + * Write page layout styles. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @return void + */ + private function writePageLayout(XMLWriter $xmlWriter) + { + $xmlWriter->startElement('style:page-layout'); + $xmlWriter->writeAttribute('style:name', 'Mpm1'); + + $xmlWriter->startElement('style:page-layout-properties'); + $xmlWriter->writeAttribute('fo:page-width', "21.001cm"); + $xmlWriter->writeAttribute('fo:page-height', '29.7cm'); + $xmlWriter->writeAttribute('style:num-format', '1'); + $xmlWriter->writeAttribute('style:print-orientation', 'portrait'); + $xmlWriter->writeAttribute('fo:margin-top', '2.501cm'); + $xmlWriter->writeAttribute('fo:margin-bottom', '2cm'); + $xmlWriter->writeAttribute('fo:margin-left', '2.501cm'); + $xmlWriter->writeAttribute('fo:margin-right', '2.501cm'); + $xmlWriter->writeAttribute('style:writing-mode', 'lr-tb'); + $xmlWriter->writeAttribute('style:layout-grid-color', '#c0c0c0'); + $xmlWriter->writeAttribute('style:layout-grid-lines', '25199'); + $xmlWriter->writeAttribute('style:layout-grid-base-height', '0.423cm'); + $xmlWriter->writeAttribute('style:layout-grid-ruby-height', '0cm'); + $xmlWriter->writeAttribute('style:layout-grid-mode', 'none'); + $xmlWriter->writeAttribute('style:layout-grid-ruby-below', 'false'); + $xmlWriter->writeAttribute('style:layout-grid-print', 'false'); + $xmlWriter->writeAttribute('style:layout-grid-display', 'false'); + $xmlWriter->writeAttribute('style:layout-grid-base-width', '0.37cm'); + $xmlWriter->writeAttribute('style:layout-grid-snap-to', 'true'); + $xmlWriter->writeAttribute('style:footnote-max-height', '0cm'); + + $xmlWriter->startElement('style:footnote-sep'); + $xmlWriter->writeAttribute('style:width', '0.018cm'); + $xmlWriter->writeAttribute('style:line-style', 'solid'); + $xmlWriter->writeAttribute('style:adjustment', 'left'); + $xmlWriter->writeAttribute('style:rel-width', '25%'); + $xmlWriter->writeAttribute('style:color', '#000000'); + $xmlWriter->endElement(); //style:footnote-sep + + $xmlWriter->endElement(); // style:page-layout-properties + + + $xmlWriter->startElement('style:header-style'); + $xmlWriter->endElement(); // style:header-style + + $xmlWriter->startElement('style:footer-style'); + $xmlWriter->endElement(); // style:footer-style + + $xmlWriter->endElement(); // style:page-layout + } + + /** + * Write master style. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @return void + */ + private function writeMaster(XMLWriter $xmlWriter) + { + $xmlWriter->startElement('office:master-styles'); + + $xmlWriter->startElement('style:master-page'); + $xmlWriter->writeAttribute('style:name', 'Standard'); + $xmlWriter->writeAttribute('style:page-layout-name', 'Mpm1'); + $xmlWriter->endElement(); // style:master-page + + $xmlWriter->endElement(); // office:master-styles + } +} diff --git a/src/PhpWord/Writer/ODText/Style/AbstractStyle.php b/src/PhpWord/Writer/ODText/Style/AbstractStyle.php new file mode 100644 index 00000000..18d6ce10 --- /dev/null +++ b/src/PhpWord/Writer/ODText/Style/AbstractStyle.php @@ -0,0 +1,29 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Font) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement('style:style'); + $xmlWriter->writeAttribute('style:name', $style->getStyleName()); + $xmlWriter->writeAttribute('style:family', 'text'); + $xmlWriter->startElement('style:text-properties'); + + // Name + $font = $style->getName(); + $xmlWriter->writeAttributeIf($font != '', 'style:font-name', $font); + $xmlWriter->writeAttributeIf($font != '', 'style:font-name-complex', $font); + $size = $style->getSize(); + + // Size + $xmlWriter->writeAttributeIf(is_numeric($size), 'fo:font-size', $size . 'pt'); + $xmlWriter->writeAttributeIf(is_numeric($size), 'style:font-size-asian', $size . 'pt'); + $xmlWriter->writeAttributeIf(is_numeric($size), 'style:font-size-complex', $size . 'pt'); + + // Color + $color = $style->getColor(); + $xmlWriter->writeAttributeIf($color != '', 'fo:color', '#' . $color); + + // Bold & italic + $xmlWriter->writeAttributeIf($style->isBold(), 'fo:font-weight', 'bold'); + $xmlWriter->writeAttributeIf($style->isBold(), 'style:font-weight-asian', 'bold'); + $xmlWriter->writeAttributeIf($style->isItalic(), 'fo:font-style', 'italic'); + $xmlWriter->writeAttributeIf($style->isItalic(), 'style:font-style-asian', 'italic'); + $xmlWriter->writeAttributeIf($style->isItalic(), 'style:font-style-complex', 'italic'); + + // Underline + // @todo Various mode of underline + $underline = $style->getUnderline(); + $xmlWriter->writeAttributeIf($underline != 'none', 'style:text-underline-style', 'solid'); + + // Strikethrough, double strikethrough + $xmlWriter->writeAttributeIf($style->isStrikethrough(), 'style:text-line-through-type', 'single'); + $xmlWriter->writeAttributeIf($style->isDoubleStrikethrough(), 'style:text-line-through-type', 'double'); + + // Small caps, all caps + $xmlWriter->writeAttributeIf($style->isSmallCaps(), 'fo:font-variant', 'small-caps'); + $xmlWriter->writeAttributeIf($style->isAllCaps(), 'fo:text-transform', 'uppercase'); + + // Superscript/subscript + $xmlWriter->writeAttributeIf($style->isSuperScript(), 'style:text-position', 'super'); + $xmlWriter->writeAttributeIf($style->isSubScript(), 'style:text-position', 'sub'); + + // @todo Foreground-Color + + // @todo Background color + + $xmlWriter->endElement(); // style:text-properties + $xmlWriter->endElement(); // style:style + } +} diff --git a/src/PhpWord/Writer/ODText/Style/Image.php b/src/PhpWord/Writer/ODText/Style/Image.php new file mode 100644 index 00000000..21b9c4ee --- /dev/null +++ b/src/PhpWord/Writer/ODText/Style/Image.php @@ -0,0 +1,51 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Image) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement('style:style'); + $xmlWriter->writeAttribute('style:name', $style->getStyleName()); + $xmlWriter->writeAttribute('style:family', 'graphic'); + $xmlWriter->writeAttribute('style:parent-style-name', 'Graphics'); + $xmlWriter->startElement('style:graphic-properties'); + $xmlWriter->writeAttribute('style:vertical-pos', 'top'); + $xmlWriter->writeAttribute('style:vertical-rel', 'baseline'); + $xmlWriter->endElement(); // style:graphic-properties + $xmlWriter->endElement(); // style:style + } +} diff --git a/src/PhpWord/Writer/ODText/Style/Paragraph.php b/src/PhpWord/Writer/ODText/Style/Paragraph.php new file mode 100644 index 00000000..03e605a1 --- /dev/null +++ b/src/PhpWord/Writer/ODText/Style/Paragraph.php @@ -0,0 +1,63 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Paragraph) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $marginTop = is_null($style->getSpaceBefore()) ? '0' : round(17.6 / $style->getSpaceBefore(), 2); + $marginBottom = is_null($style->getSpaceAfter()) ? '0' : round(17.6 / $style->getSpaceAfter(), 2); + + $xmlWriter->startElement('style:style'); + $xmlWriter->writeAttribute('style:name', $style->getStyleName()); + $xmlWriter->writeAttribute('style:family', 'paragraph'); + if ($style->isAuto()) { + $xmlWriter->writeAttribute('style:parent-style-name', 'Standard'); + $xmlWriter->writeAttribute('style:master-page-name', 'Standard'); + } + + $xmlWriter->startElement('style:paragraph-properties'); + if ($style->isAuto()) { + $xmlWriter->writeAttribute('style:page-number', 'auto'); + } else { + $xmlWriter->writeAttribute('fo:margin-top', $marginTop . 'cm'); + $xmlWriter->writeAttribute('fo:margin-bottom', $marginBottom . 'cm'); + $xmlWriter->writeAttribute('fo:text-align', $style->getAlign()); + } + $xmlWriter->endElement(); //style:paragraph-properties + + $xmlWriter->endElement(); //style:style + } +} diff --git a/src/PhpWord/Writer/ODText/Style/Section.php b/src/PhpWord/Writer/ODText/Style/Section.php new file mode 100644 index 00000000..fa432856 --- /dev/null +++ b/src/PhpWord/Writer/ODText/Style/Section.php @@ -0,0 +1,53 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Section) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement('style:style'); + $xmlWriter->writeAttribute('style:name', $style->getStyleName()); + $xmlWriter->writeAttribute('style:family', "section"); + $xmlWriter->startElement('style:section-properties'); + + $xmlWriter->startElement('style:columns'); + $xmlWriter->writeAttribute('fo:column-count', $style->getColsNum()); + $xmlWriter->endElement(); // style:columns + + $xmlWriter->endElement(); // style:section-properties + $xmlWriter->endElement(); // style:style + } +} diff --git a/src/PhpWord/Writer/ODText/Style/Table.php b/src/PhpWord/Writer/ODText/Style/Table.php new file mode 100644 index 00000000..dbfb94ed --- /dev/null +++ b/src/PhpWord/Writer/ODText/Style/Table.php @@ -0,0 +1,51 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Table) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement('style:style'); + $xmlWriter->writeAttribute('style:name', $style->getStyleName()); + $xmlWriter->writeAttribute('style:family', 'table'); + $xmlWriter->startElement('style:table-properties'); + //$xmlWriter->writeAttribute('style:width', 'table'); + $xmlWriter->writeAttribute('style:rel-width', 100); + $xmlWriter->writeAttribute('table:align', 'center'); + $xmlWriter->endElement(); // style:table-properties + $xmlWriter->endElement(); // style:style + } +} diff --git a/src/PhpWord/Writer/ODText/Styles.php b/src/PhpWord/Writer/ODText/Styles.php deleted file mode 100644 index 53175165..00000000 --- a/src/PhpWord/Writer/ODText/Styles.php +++ /dev/null @@ -1,200 +0,0 @@ -getXmlWriter(); - - // XML header - $xmlWriter->startDocument('1.0', 'UTF-8'); - - // Styles:Styles - $xmlWriter->startElement('office:document-styles'); - $this->writeCommonRootAttributes($xmlWriter); - - // office:font-face-decls - $this->writeFontFaces($xmlWriter); - - // office:styles - $xmlWriter->startElement('office:styles'); - - // style:default-style - $xmlWriter->startElement('style:default-style'); - $xmlWriter->writeAttribute('style:family', 'paragraph'); - - // style:paragraph-properties - $xmlWriter->startElement('style:paragraph-properties'); - $xmlWriter->writeAttribute('fo:hyphenation-ladder-count', 'no-limit'); - $xmlWriter->writeAttribute('style:text-autospace', 'ideograph-alpha'); - $xmlWriter->writeAttribute('style:punctuation-wrap', 'hanging'); - $xmlWriter->writeAttribute('style:line-break', 'strict'); - $xmlWriter->writeAttribute('style:tab-stop-distance', '1.249cm'); - $xmlWriter->writeAttribute('style:writing-mode', 'page'); - $xmlWriter->endElement(); - - // style:text-properties - $xmlWriter->startElement('style:text-properties'); - $xmlWriter->writeAttribute('style:use-window-font-color', 'true'); - $xmlWriter->writeAttribute('style:font-name', PhpWord::DEFAULT_FONT_NAME); - $xmlWriter->writeAttribute('fo:font-size', PhpWord::DEFAULT_FONT_SIZE . 'pt'); - $xmlWriter->writeAttribute('fo:language', 'fr'); - $xmlWriter->writeAttribute('fo:country', 'FR'); - $xmlWriter->writeAttribute('style:letter-kerning', 'true'); - $xmlWriter->writeAttribute('style:font-name-asian', PhpWord::DEFAULT_FONT_NAME . '2'); - $xmlWriter->writeAttribute('style:font-size-asian', PhpWord::DEFAULT_FONT_SIZE . 'pt'); - $xmlWriter->writeAttribute('style:language-asian', 'zh'); - $xmlWriter->writeAttribute('style:country-asian', 'CN'); - $xmlWriter->writeAttribute('style:font-name-complex', PhpWord::DEFAULT_FONT_NAME . '2'); - $xmlWriter->writeAttribute('style:font-size-complex', PhpWord::DEFAULT_FONT_SIZE . 'pt'); - $xmlWriter->writeAttribute('style:language-complex', 'hi'); - $xmlWriter->writeAttribute('style:country-complex', 'IN'); - $xmlWriter->writeAttribute('fo:hyphenate', 'false'); - $xmlWriter->writeAttribute('fo:hyphenation-remain-char-count', '2'); - $xmlWriter->writeAttribute('fo:hyphenation-push-char-count', '2'); - $xmlWriter->endElement(); - - $xmlWriter->endElement(); - - // Write Style Definitions - $styles = Style::getStyles(); - if (count($styles) > 0) { - foreach ($styles as $styleName => $style) { - if (preg_match('#^T[0-9]+$#', $styleName) == 0 - && preg_match('#^P[0-9]+$#', $styleName) == 0 - ) { - // Font - if ($style instanceof Font) { - // style:style - $xmlWriter->startElement('style:style'); - $xmlWriter->writeAttribute('style:name', $styleName); - $xmlWriter->writeAttribute('style:family', 'text'); - - // style:text-properties - $xmlWriter->startElement('style:text-properties'); - $xmlWriter->writeAttribute('fo:font-size', ($style->getSize()) . 'pt'); - $xmlWriter->writeAttribute('style:font-size-asian', ($style->getSize()) . 'pt'); - $xmlWriter->writeAttribute('style:font-size-complex', ($style->getSize()) . 'pt'); - if ($style->getItalic()) { - $xmlWriter->writeAttribute('fo:font-style', 'italic'); - $xmlWriter->writeAttribute('style:font-style-asian', 'italic'); - $xmlWriter->writeAttribute('style:font-style-complex', 'italic'); - } - if ($style->getBold()) { - $xmlWriter->writeAttribute('fo:font-weight', 'bold'); - $xmlWriter->writeAttribute('style:font-weight-asian', 'bold'); - } - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } elseif ($style instanceof Paragraph) { - // Paragraph - // style:style - $xmlWriter->startElement('style:style'); - $xmlWriter->writeAttribute('style:name', $styleName); - $xmlWriter->writeAttribute('style:family', 'paragraph'); - - //style:paragraph-properties - $xmlWriter->startElement('style:paragraph-properties'); - $xmlWriter->writeAttribute('fo:margin-top', ((is_null($style->getSpaceBefore())) ? '0' : round(17.6 / $style->getSpaceBefore(), 2)) . 'cm'); - $xmlWriter->writeAttribute('fo:margin-bottom', ((is_null($style->getSpaceAfter())) ? '0' : round(17.6 / $style->getSpaceAfter(), 2)) . 'cm'); - $xmlWriter->writeAttribute('fo:text-align', $style->getAlign()); - $xmlWriter->endElement(); - - $xmlWriter->endElement(); - } elseif ($style instanceof Table) { - // Table - } - } - } - } - $xmlWriter->endElement(); - - // office:automatic-styles - $xmlWriter->startElement('office:automatic-styles'); - // style:page-layout - $xmlWriter->startElement('style:page-layout'); - $xmlWriter->writeAttribute('style:name', 'Mpm1'); - // style:page-layout-properties - $xmlWriter->startElement('style:page-layout-properties'); - $xmlWriter->writeAttribute('fo:page-width', "21.001cm"); - $xmlWriter->writeAttribute('fo:page-height', '29.7cm'); - $xmlWriter->writeAttribute('style:num-format', '1'); - $xmlWriter->writeAttribute('style:print-orientation', 'portrait'); - $xmlWriter->writeAttribute('fo:margin-top', '2.501cm'); - $xmlWriter->writeAttribute('fo:margin-bottom', '2cm'); - $xmlWriter->writeAttribute('fo:margin-left', '2.501cm'); - $xmlWriter->writeAttribute('fo:margin-right', '2.501cm'); - $xmlWriter->writeAttribute('style:writing-mode', 'lr-tb'); - $xmlWriter->writeAttribute('style:layout-grid-color', '#c0c0c0'); - $xmlWriter->writeAttribute('style:layout-grid-lines', '25199'); - $xmlWriter->writeAttribute('style:layout-grid-base-height', '0.423cm'); - $xmlWriter->writeAttribute('style:layout-grid-ruby-height', '0cm'); - $xmlWriter->writeAttribute('style:layout-grid-mode', 'none'); - $xmlWriter->writeAttribute('style:layout-grid-ruby-below', 'false'); - $xmlWriter->writeAttribute('style:layout-grid-print', 'false'); - $xmlWriter->writeAttribute('style:layout-grid-display', 'false'); - $xmlWriter->writeAttribute('style:layout-grid-base-width', '0.37cm'); - $xmlWriter->writeAttribute('style:layout-grid-snap-to', 'true'); - $xmlWriter->writeAttribute('style:footnote-max-height', '0cm'); - //style:footnote-sep - $xmlWriter->startElement('style:footnote-sep'); - $xmlWriter->writeAttribute('style:width', '0.018cm'); - $xmlWriter->writeAttribute('style:line-style', 'solid'); - $xmlWriter->writeAttribute('style:adjustment', 'left'); - $xmlWriter->writeAttribute('style:rel-width', '25%'); - $xmlWriter->writeAttribute('style:color', '#000000'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - // style:header-style - $xmlWriter->startElement('style:header-style'); - $xmlWriter->endElement(); - // style:footer-style - $xmlWriter->startElement('style:footer-style'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - // office:master-styles - $xmlWriter->startElement('office:master-styles'); - // style:master-page - $xmlWriter->startElement('style:master-page'); - $xmlWriter->writeAttribute('style:name', 'Standard'); - $xmlWriter->writeAttribute('style:page-layout-name', 'Mpm1'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - $xmlWriter->endElement(); - - // Return - return $xmlWriter->getData(); - } -} diff --git a/src/PhpWord/Writer/PDF.php b/src/PhpWord/Writer/PDF.php new file mode 100644 index 00000000..17865563 --- /dev/null +++ b/src/PhpWord/Writer/PDF.php @@ -0,0 +1,78 @@ +renderer = new $rendererName($phpWord); + } + + /** + * Magic method to handle direct calls to the configured PDF renderer wrapper class. + * + * @param string $name Renderer library method name + * @param mixed[] $arguments Array of arguments to pass to the renderer method + * @return mixed Returned data from the PDF renderer wrapper method + */ + public function __call($name, $arguments) + { + // Note: Commented because all exceptions should already be catched by `__construct` + // if ($this->renderer === null) { + // throw new Exception("PDF Rendering library has not been defined."); + // } + + return call_user_func_array(array($this->renderer, $name), $arguments); + } +} diff --git a/src/PhpWord/Writer/PDF/AbstractRenderer.php b/src/PhpWord/Writer/PDF/AbstractRenderer.php new file mode 100644 index 00000000..572e4b1d --- /dev/null +++ b/src/PhpWord/Writer/PDF/AbstractRenderer.php @@ -0,0 +1,200 @@ + 'A4', // (210 mm by 297 mm) + ); + + /** + * Create new instance + * + * @param PhpWord $phpWord PhpWord object + * @throws \PhpOffice\PhpWord\Exception\Exception + */ + public function __construct(PhpWord $phpWord) + { + parent::__construct($phpWord); + $includeFile = Settings::getPdfRendererPath() . '/' . $this->includeFile; + if (file_exists($includeFile)) { + /** @noinspection PhpIncludeInspection Dynamic includes */ + require_once $includeFile; + } else { + // @codeCoverageIgnoreStart + // Can't find any test case. Uncomment when found. + throw new Exception('Unable to load PDF Rendering library'); + // @codeCoverageIgnoreEnd + } + } + + /** + * Get Font + * + * @return string + */ + public function getFont() + { + return $this->font; + } + + /** + * Set font. Examples: + * 'arialunicid0-chinese-simplified' + * 'arialunicid0-chinese-traditional' + * 'arialunicid0-korean' + * 'arialunicid0-japanese' + * + * @param string $fontName + * @return self + */ + public function setFont($fontName) + { + $this->font = $fontName; + + return $this; + } + + /** + * Get Paper Size + * + * @return int + */ + public function getPaperSize() + { + return $this->paperSize; + } + + /** + * Set Paper Size + * + * @param int $value Paper size = PAPERSIZE_A4 + * @return self + */ + public function setPaperSize($value = 9) + { + $this->paperSize = $value; + return $this; + } + + /** + * Get Orientation + * + * @return string + */ + public function getOrientation() + { + return $this->orientation; + } + + /** + * Set Orientation + * + * @param string $value Page orientation ORIENTATION_DEFAULT + * @return self + */ + public function setOrientation($value = 'default') + { + $this->orientation = $value; + return $this; + } + + /** + * Save PhpWord to PDF file, pre-save + * + * @param string $filename Name of the file to save as + * @return resource + * @throws \PhpOffice\PhpWord\Exception\Exception + */ + protected function prepareForSave($filename = null) + { + $fileHandle = fopen($filename, 'w'); + // @codeCoverageIgnoreStart + // Can't find any test case. Uncomment when found. + if ($fileHandle === false) { + throw new Exception("Could not open file $filename for writing."); + } + // @codeCoverageIgnoreEnd + $this->isPdf = true; + + return $fileHandle; + } + + /** + * Save PhpWord to PDF file, post-save + * + * @param resource $fileHandle + * @return void + * @throws Exception + */ + protected function restoreStateAfterSave($fileHandle) + { + fclose($fileHandle); + } +} diff --git a/src/PhpWord/Writer/PDF/DomPDF.php b/src/PhpWord/Writer/PDF/DomPDF.php new file mode 100644 index 00000000..47054c4a --- /dev/null +++ b/src/PhpWord/Writer/PDF/DomPDF.php @@ -0,0 +1,62 @@ +set_paper(strtolower($paperSize), $orientation); + $pdf->load_html($this->getContent()); + $pdf->render(); + + // Write to file + fwrite($fileHandle, $pdf->output()); + + parent::restoreStateAfterSave($fileHandle); + } +} diff --git a/src/PhpWord/Writer/PDF/MPDF.php b/src/PhpWord/Writer/PDF/MPDF.php new file mode 100644 index 00000000..46d456d4 --- /dev/null +++ b/src/PhpWord/Writer/PDF/MPDF.php @@ -0,0 +1,72 @@ +_setPageSize($paperSize, $orientation); + $pdf->addPage($orientation); + + // Write document properties + $phpWord = $this->getPhpWord(); + $docProps = $phpWord->getDocInfo(); + $pdf->setTitle($docProps->getTitle()); + $pdf->setAuthor($docProps->getCreator()); + $pdf->setSubject($docProps->getSubject()); + $pdf->setKeywords($docProps->getKeywords()); + $pdf->setCreator($docProps->getCreator()); + + $pdf->writeHTML($this->getContent()); + + // Write to file + fwrite($fileHandle, $pdf->output($filename, 'S')); + + parent::restoreStateAfterSave($fileHandle); + } +} diff --git a/src/PhpWord/Writer/PDF/TCPDF.php b/src/PhpWord/Writer/PDF/TCPDF.php new file mode 100644 index 00000000..36849e24 --- /dev/null +++ b/src/PhpWord/Writer/PDF/TCPDF.php @@ -0,0 +1,74 @@ +setFontSubsetting(false); + $pdf->setPrintHeader(false); + $pdf->setPrintFooter(false); + $pdf->addPage(); + $pdf->setFont($this->getFont()); + $pdf->writeHTML($this->getContent()); + + // Write document properties + $phpWord = $this->getPhpWord(); + $docProps = $phpWord->getDocInfo(); + $pdf->setTitle($docProps->getTitle()); + $pdf->setAuthor($docProps->getCreator()); + $pdf->setSubject($docProps->getSubject()); + $pdf->setKeywords($docProps->getKeywords()); + $pdf->setCreator($docProps->getCreator()); + + // Write to file + fwrite($fileHandle, $pdf->output($filename, 'S')); + + parent::restoreStateAfterSave($fileHandle); + } +} diff --git a/src/PhpWord/Writer/RTF.php b/src/PhpWord/Writer/RTF.php old mode 100755 new mode 100644 index a1ff4bc6..58210c99 --- a/src/PhpWord/Writer/RTF.php +++ b/src/PhpWord/Writer/RTF.php @@ -1,50 +1,31 @@ setPhpWord($phpWord); - } - /** - * Save PhpWord to file - * - * @param string $pFilename - * @throws Exception - */ - public function save($pFilename = null) - { - if (!is_null($this->phpWord)) { - $pFilename = $this->getTempFile($pFilename); - - $hFile = fopen($pFilename, 'w') or die("can't open file"); - fwrite($hFile, $this->getData()); - fclose($hFile); - - $this->cleanupTempFile(); - } else { - throw new Exception("PhpWord object unassigned."); + $this->parts = array('Header', 'Document'); + foreach ($this->parts as $partName) { + $partClass = get_class($this) . '\\Part\\' . $partName; + if (class_exists($partClass)) { + /** @var \PhpOffice\PhpWord\Writer\RTF\Part\AbstractPart $part Type hint */ + $part = new $partClass(); + $part->setParentWriter($this); + $this->writerParts[strtolower($partName)] = $part; + } } } /** - * Get all data + * Save content to file. + * + * @param string $filename + * @return void + * @throws \PhpOffice\PhpWord\Exception\Exception + */ + public function save($filename = null) + { + $this->writeFile($this->openFile($filename), $this->getContent()); + } + + /** + * Get content * * @return string + * @since 0.11.0 */ - private function getData() + private function getContent() { - // PhpWord object : $this->phpWord - $this->fontTable = $this->getDataFont(); - $this->colorTable = $this->getDataColor(); + $content = ''; - $sRTFContent = '{\rtf1'; - // Set the default character set - $sRTFContent .= '\ansi\ansicpg1252'; - // Set the default font (the first one) - $sRTFContent .= '\deff0'; - // Set the default tab size (720 twips) - $sRTFContent .= '\deftab720'; - $sRTFContent .= PHP_EOL; - // Set the font tbl group - $sRTFContent .= '{\fonttbl'; - foreach ($this->fontTable as $idx => $font) { - $sRTFContent .= '{\f' . $idx . '\fnil\fcharset0 ' . $font . ';}'; - } - $sRTFContent .= '}' . PHP_EOL; - // Set the color tbl group - $sRTFContent .= '{\colortbl '; - foreach ($this->colorTable as $idx => $color) { - $arrColor = Drawing::htmlToRGB($color); - $sRTFContent .= ';\red' . $arrColor[0] . '\green' . $arrColor[1] . '\blue' . $arrColor[2] . ''; - } - $sRTFContent .= ';}' . PHP_EOL; - // Set the generator - $sRTFContent .= '{\*\generator PhpWord;}' . PHP_EOL; - // Set the view mode of the document - $sRTFContent .= '\viewkind4'; - // Set the numberof bytes that follows a unicode character - $sRTFContent .= '\uc1'; - // Resets to default paragraph properties. - $sRTFContent .= '\pard'; - // No widow/orphan control - $sRTFContent .= '\nowidctlpar'; - // Applies a language to a text run (1036 : French (France)) - $sRTFContent .= '\lang1036'; - // Point size (in half-points) above which to kern character pairs - $sRTFContent .= '\kerning1'; - // Set the font size in half-points - $sRTFContent .= '\fs' . (PhpWord::DEFAULT_FONT_SIZE * 2); - $sRTFContent .= PHP_EOL; - // Body - $sRTFContent .= $this->getDataContent(); + $content .= '{'; + $content .= '\rtf1' . PHP_EOL; + $content .= $this->getWriterPart('Header')->write(); + $content .= $this->getWriterPart('Document')->write(); + $content .= '}'; - - $sRTFContent .= '}'; - - return $sRTFContent; + return $content; } /** - * Get all fonts + * Get font table. * * @return array */ - private function getDataFont() + public function getFontTable() { - $phpWord = $this->phpWord; - - $arrFonts = array(); - // Default font : PhpWord::DEFAULT_FONT_NAME - $arrFonts[] = PhpWord::DEFAULT_FONT_NAME; - // PhpWord object : $this->phpWord - - // Browse styles - $styles = Style::getStyles(); - if (count($styles) > 0) { - foreach ($styles as $styleName => $style) { - // Font - if ($style instanceof Font) { - if (in_array($style->getName(), $arrFonts) == false) { - $arrFonts[] = $style->getName(); - } - } - } - } - - // Search all fonts used - $sections = $phpWord->getSections(); - $countSections = count($sections); - if ($countSections > 0) { - $pSection = 0; - - foreach ($sections as $section) { - $pSection++; - $elements = $section->getElements(); - - foreach ($elements as $element) { - if ($element instanceof Text) { - $fStyle = $element->getFontStyle(); - - if ($fStyle instanceof Font) { - if (in_array($fStyle->getName(), $arrFonts) == false) { - $arrFonts[] = $fStyle->getName(); - } - } - } - } - } - } - - return $arrFonts; + return $this->getWriterPart('Header')->getFontTable(); } /** - * Get all colors + * Get color table. * * @return array */ - private function getDataColor() + public function getColorTable() { - $phpWord = $this->phpWord; - - $arrColors = array(); - // PhpWord object : $this->phpWord - - // Browse styles - $styles = Style::getStyles(); - if (count($styles) > 0) { - foreach ($styles as $styleName => $style) { - // Font - if ($style instanceof Font) { - $color = $style->getColor(); - $fgcolor = $style->getFgColor(); - if (in_array($color, $arrColors) == false && $color != PhpWord::DEFAULT_FONT_COLOR && !empty($color)) { - $arrColors[] = $color; - } - if (in_array($fgcolor, $arrColors) == false && $fgcolor != PhpWord::DEFAULT_FONT_COLOR && !empty($fgcolor)) { - $arrColors[] = $fgcolor; - } - } - } - } - - // Search all fonts used - $sections = $phpWord->getSections(); - $countSections = count($sections); - if ($countSections > 0) { - $pSection = 0; - - foreach ($sections as $section) { - $pSection++; - $elements = $section->getElements(); - - foreach ($elements as $element) { - if ($element instanceof Text) { - $fStyle = $element->getFontStyle(); - - if ($fStyle instanceof Font) { - if (in_array($fStyle->getColor(), $arrColors) == false) { - $arrColors[] = $fStyle->getColor(); - } - if (in_array($fStyle->getFgColor(), $arrColors) == false) { - $arrColors[] = $fStyle->getFgColor(); - } - } - } - } - } - } - - return $arrColors; + return $this->getWriterPart('Header')->getColorTable(); } /** - * Get content data + * Get last paragraph style. * - * @return string + * @return mixed */ - private function getDataContent() + public function getLastParagraphStyle() { - $phpWord = $this->phpWord; - $sRTFBody = ''; - - $sections = $phpWord->getSections(); - $countSections = count($sections); - $pSection = 0; - - if ($countSections > 0) { - foreach ($sections as $section) { - $pSection++; - $elements = $section->getElements(); - foreach ($elements as $element) { - if ($element instanceof Text) { - $sRTFBody .= $this->getDataContentText($element); - } elseif ($element instanceof TextBreak) { - $sRTFBody .= $this->getDataContentTextBreak(); - } elseif ($element instanceof TextRun) { - $sRTFBody .= $this->getDataContentTextRun($element); - } elseif ($element instanceof Link) { - $sRTFBody .= $this->getDataContentUnsupportedElement('Link'); - } elseif ($element instanceof Title) { - $sRTFBody .= $this->getDataContentUnsupportedElement('Title'); - } elseif ($element instanceof PageBreak) { - $sRTFBody .= $this->getDataContentUnsupportedElement('Page Break'); - } elseif ($element instanceof Table) { - $sRTFBody .= $this->getDataContentUnsupportedElement('Table'); - } elseif ($element instanceof ListItem) { - $sRTFBody .= $this->getDataContentUnsupportedElement('List Item'); - } elseif ($element instanceof Image) { - $sRTFBody .= $this->getDataContentUnsupportedElement('Image'); - } elseif ($element instanceof Object) { - $sRTFBody .= $this->getDataContentUnsupportedElement('Object'); - } elseif ($element instanceof TOC) { - $sRTFBody .= $this->getDataContentUnsupportedElement('TOC'); - } else { - $sRTFBody .= $this->getDataContentUnsupportedElement('Other'); - } - } - } - } - return $sRTFBody; + return $this->lastParagraphStyle; } /** - * Get text element content + * Set last paragraph style. * - * @param boolean $withoutP - * @return string + * @param mixed $value + * @return void */ - private function getDataContentText(Text $text, $withoutP = false) + public function setLastParagraphStyle($value = '') { - $sRTFText = ''; - - $styleFont = $text->getFontStyle(); - if (is_string($styleFont)) { - $styleFont = Style::getStyle($styleFont); - } - - $styleParagraph = $text->getParagraphStyle(); - if (is_string($styleParagraph)) { - $styleParagraph = Style::getStyle($styleParagraph); - } - - if ($styleParagraph && !$withoutP) { - if ($this->lastParagraphStyle != $text->getParagraphStyle()) { - $sRTFText .= '\pard\nowidctlpar'; - if ($styleParagraph->getSpaceAfter() != null) { - $sRTFText .= '\sa' . $styleParagraph->getSpaceAfter(); - } - if ($styleParagraph->getAlign() != null) { - if ($styleParagraph->getAlign() == 'center') { - $sRTFText .= '\qc'; - } - } - $this->lastParagraphStyle = $text->getParagraphStyle(); - } else { - $this->lastParagraphStyle = ''; - } - } else { - $this->lastParagraphStyle = ''; - } - - if ($styleFont instanceof Font) { - if ($styleFont->getColor() != null) { - $idxColor = array_search($styleFont->getColor(), $this->colorTable); - if ($idxColor !== false) { - $sRTFText .= '\cf' . ($idxColor + 1); - } - } else { - $sRTFText .= '\cf0'; - } - if ($styleFont->getName() != null) { - $idxFont = array_search($styleFont->getName(), $this->fontTable); - if ($idxFont !== false) { - $sRTFText .= '\f' . $idxFont; - } - } else { - $sRTFText .= '\f0'; - } - if ($styleFont->getBold()) { - $sRTFText .= '\b'; - } - if ($styleFont->getItalic()) { - $sRTFText .= '\i'; - } - if ($styleFont->getSize()) { - $sRTFText .= '\fs' . ($styleFont->getSize() * 2); - } - } - if ($this->lastParagraphStyle != '' || $styleFont) { - $sRTFText .= ' '; - } - $sRTFText .= $text->getText(); - - if ($styleFont instanceof Font) { - $sRTFText .= '\cf0'; - $sRTFText .= '\f0'; - - if ($styleFont->getBold()) { - $sRTFText .= '\b0'; - } - if ($styleFont->getItalic()) { - $sRTFText .= '\i0'; - } - if ($styleFont->getSize()) { - $sRTFText .= '\fs' . (PhpWord::DEFAULT_FONT_SIZE * 2); - } - } - - if (!$withoutP) { - $sRTFText .= '\par' . PHP_EOL; - } - return $sRTFText; - } - - /** - * Get textrun content - * - * @return string - */ - private function getDataContentTextRun(TextRun $textrun) - { - $sRTFText = ''; - $elements = $textrun->getElements(); - if (count($elements) > 0) { - $sRTFText .= '\pard\nowidctlpar' . PHP_EOL; - foreach ($elements as $element) { - if ($element instanceof Text) { - $sRTFText .= '{'; - $sRTFText .= $this->getDataContentText($element, true); - $sRTFText .= '}' . PHP_EOL; - } - } - $sRTFText .= '\par' . PHP_EOL; - } - return $sRTFText; - } - - /** - * Get text break content - * - * @return string - */ - private function getDataContentTextBreak() - { - $this->lastParagraphStyle = ''; - - return '\par' . PHP_EOL; - } - - /** - * Get unsupported element content - * - * @param string $element - */ - private function getDataContentUnsupportedElement($element) - { - $sRTFText = ''; - $sRTFText .= '\pard\nowidctlpar' . PHP_EOL; - $sRTFText .= "{$element}"; - $sRTFText .= '\par' . PHP_EOL; - - return $sRTFText; + $this->lastParagraphStyle = $value; } } diff --git a/src/PhpWord/Writer/RTF/Element/AbstractElement.php b/src/PhpWord/Writer/RTF/Element/AbstractElement.php new file mode 100644 index 00000000..73da5cbd --- /dev/null +++ b/src/PhpWord/Writer/RTF/Element/AbstractElement.php @@ -0,0 +1,166 @@ +parentWriter; + + /** @var \PhpOffice\PhpWord\Element\Text $element Type hint */ + $element = $this->element; + + // Font style + if (method_exists($element, 'getFontStyle')) { + $this->fontStyle = $element->getFontStyle(); + if (is_string($this->fontStyle)) { + $this->fontStyle = Style::getStyle($this->fontStyle); + } + } + + // Paragraph style + if (method_exists($element, 'getParagraphStyle')) { + $this->paragraphStyle = $element->getParagraphStyle(); + if (is_string($this->paragraphStyle)) { + $this->paragraphStyle = Style::getStyle($this->paragraphStyle); + } + + if ($this->paragraphStyle !== null && !$this->withoutP) { + if ($parentWriter->getLastParagraphStyle() != $element->getParagraphStyle()) { + $parentWriter->setLastParagraphStyle($element->getParagraphStyle()); + } else { + $parentWriter->setLastParagraphStyle(); + $this->paragraphStyle = null; + } + } else { + $parentWriter->setLastParagraphStyle(); + $this->paragraphStyle = null; + } + } + } + + /** + * Write opening + * + * @return string + */ + protected function writeOpening() + { + if ($this->withoutP || !$this->paragraphStyle instanceof ParagraphStyle) { + return ''; + } + + $styleWriter = new ParagraphStyleWriter($this->paragraphStyle); + $styleWriter->setNestedLevel($this->element->getNestedLevel()); + return $styleWriter->write(); + } + + /** + * Write text + * + * @param string $text + * @return string + */ + protected function writeText($text) + { + return String::toUnicode($text); + } + + /** + * Write closing + * + * @return string + */ + protected function writeClosing() + { + if ($this->withoutP) { + return ''; + } + + return '\par' . PHP_EOL; + } + + /** + * Write font style + * + * @return string + */ + protected function writeFontStyle() + { + if (!$this->fontStyle instanceof FontStyle) { + return ''; + } + + /** @var \PhpOffice\PhpWord\Writer\RTF $parentWriter Type hint */ + $parentWriter = $this->parentWriter; + + // Create style writer and set color/name index + $styleWriter = new FontStyleWriter($this->fontStyle); + if ($this->fontStyle->getColor() != null) { + $colorIndex = array_search($this->fontStyle->getColor(), $parentWriter->getColorTable()); + if ($colorIndex !== false) { + $styleWriter->setColorIndex($colorIndex + 1); + } + } + if ($this->fontStyle->getName() != null) { + $fontIndex = array_search($this->fontStyle->getName(), $parentWriter->getFontTable()); + if ($fontIndex !== false) { + $styleWriter->setNameIndex($fontIndex); + } + } + + // Write style + $content = $styleWriter->write(); + + return $content; + } +} diff --git a/src/PhpWord/Writer/RTF/Element/Container.php b/src/PhpWord/Writer/RTF/Element/Container.php new file mode 100644 index 00000000..cb95b84b --- /dev/null +++ b/src/PhpWord/Writer/RTF/Element/Container.php @@ -0,0 +1,35 @@ +element instanceof ImageElement) { + return ''; + } + + $this->getStyles(); + $style = $this->element->getStyle(); + + $content = ''; + $content .= $this->writeOpening(); + $content .= '{\*\shppict {\pict'; + $content .= '\pngblip\picscalex100\picscaley100'; + $content .= '\picwgoal' . round(Converter::pixelToTwip($style->getWidth())); + $content .= '\pichgoal' . round(Converter::pixelToTwip($style->getHeight())); + $content .= PHP_EOL; + $content .= $this->element->getImageStringData(); + $content .= '}}'; + $content .= $this->writeClosing(); + + return $content; + } +} diff --git a/src/PhpWord/Writer/RTF/Element/Link.php b/src/PhpWord/Writer/RTF/Element/Link.php new file mode 100644 index 00000000..adbc7976 --- /dev/null +++ b/src/PhpWord/Writer/RTF/Element/Link.php @@ -0,0 +1,50 @@ +element instanceof \PhpOffice\PhpWord\Element\Link) { + return ''; + } + + $this->getStyles(); + + $content = ''; + $content .= $this->writeOpening(); + $content .= '{\field {\*\fldinst {HYPERLINK "' . $this->element->getSource() . '"}}{\\fldrslt {'; + $content .= $this->writeFontStyle(); + $content .= $this->writeText($this->element->getText()); + $content .= '}}}'; + $content .= $this->writeClosing(); + + return $content; + } +} diff --git a/src/PhpWord/Writer/RTF/Element/ListItem.php b/src/PhpWord/Writer/RTF/Element/ListItem.php new file mode 100644 index 00000000..b795143c --- /dev/null +++ b/src/PhpWord/Writer/RTF/Element/ListItem.php @@ -0,0 +1,27 @@ +element instanceof TableElement) { + return ''; + } + $element = $this->element; + // No nesting table for now + if ($element->getNestedLevel() >= 1) { + return ''; + } + + $content = ''; + $rows = $element->getRows(); + $rowCount = count($rows); + + if ($rowCount > 0) { + $content .= '\pard' . PHP_EOL; + + for ($i = 0; $i < $rowCount; $i++) { + $content .= '\trowd '; + $content .= $this->writeRowDef($rows[$i]); + $content .= PHP_EOL; + $content .= $this->writeRow($rows[$i]); + $content .= '\row' . PHP_EOL; + } + } + + return $content; + } + + /** + * Write column + * + * @param \PhpOffice\PhpWord\Element\Row $row + * @return string + */ + private function writeRowDef(RowElement $row) + { + $content = ''; + + $rightMargin = 0; + foreach ($row->getCells() as $cell) { + $width = $cell->getWidth(); + $vMerge = $this->getVMerge($cell->getStyle()->getVMerge()); + if ($width === null) { + $width = 720; // Arbitrary default width + } + $rightMargin += $width; + $content .= "{$vMerge}\cellx{$rightMargin} "; + } + + return $content; + } + + /** + * Write row + * + * @param \PhpOffice\PhpWord\Element\Row $row + * @return string + */ + private function writeRow(RowElement $row) + { + $content = ''; + + // Write cells + foreach ($row->getCells() as $cell) { + $content .= $this->writeCell($cell); + } + + return $content; + } + + /** + * Write cell + * + * @param \PhpOffice\PhpWord\Element\Cell $cell + * @return string + */ + private function writeCell(CellElement $cell) + { + $content = '\intbl' . PHP_EOL; + + // Write content + $writer = new Container($this->parentWriter, $cell); + $content .= $writer->write(); + + $content .= '\cell' . PHP_EOL; + + return $content; + } + + /** + * Get vertical merge style + * + * @param string $value + * @return string + * @todo Move to style + */ + private function getVMerge($value) + { + $style = ''; + if ($value == 'restart') { + $style = '\clvmgf'; + } elseif ($value == 'continue') { + $style = '\clvmrg'; + } + + return $style; + } +} diff --git a/src/PhpWord/Writer/RTF/Element/Text.php b/src/PhpWord/Writer/RTF/Element/Text.php new file mode 100644 index 00000000..38ef4c94 --- /dev/null +++ b/src/PhpWord/Writer/RTF/Element/Text.php @@ -0,0 +1,53 @@ +element; + $elementClass = str_replace('\\Writer\\RTF', '', get_class($this)); + if (!$element instanceof $elementClass) { + return ''; + } + + $this->getStyles(); + + $content = ''; + $content .= $this->writeOpening(); + $content .= '{'; + $content .= $this->writeFontStyle(); + $content .= $this->writeText($element->getText()); + $content .= '}'; + $content .= $this->writeClosing(); + + return $content; + } +} diff --git a/src/PhpWord/Writer/RTF/Element/TextBreak.php b/src/PhpWord/Writer/RTF/Element/TextBreak.php new file mode 100644 index 00000000..57dc6349 --- /dev/null +++ b/src/PhpWord/Writer/RTF/Element/TextBreak.php @@ -0,0 +1,40 @@ +parentWriter; + $parentWriter->setLastParagraphStyle(); + + return '\pard\par' . PHP_EOL; + } +} diff --git a/src/PhpWord/Writer/RTF/Element/TextRun.php b/src/PhpWord/Writer/RTF/Element/TextRun.php new file mode 100644 index 00000000..e7563716 --- /dev/null +++ b/src/PhpWord/Writer/RTF/Element/TextRun.php @@ -0,0 +1,45 @@ +parentWriter, $this->element); + + $content = ''; + $content .= $this->writeOpening(); + $content .= '{'; + $content .= $writer->write(); + $content .= '}'; + $content .= $this->writeClosing(); + + return $content; + } +} diff --git a/src/PhpWord/Writer/RTF/Element/Title.php b/src/PhpWord/Writer/RTF/Element/Title.php new file mode 100644 index 00000000..b9645a68 --- /dev/null +++ b/src/PhpWord/Writer/RTF/Element/Title.php @@ -0,0 +1,27 @@ +writeInfo(); + $content .= $this->writeFormatting(); + $content .= $this->writeSections(); + + return $content; + } + + /** + * Write document information + * + * @return string + */ + private function writeInfo() + { + $docProps = $this->getParentWriter()->getPhpWord()->getDocInfo(); + $properties = array('title', 'subject', 'category', 'keywords', 'comment', + 'author', 'operator', 'creatim', 'revtim', 'company', 'manager'); + $mapping = array('comment' => 'description', 'author' => 'creator', 'operator' => 'lastModifiedBy', + 'creatim' => 'created', 'revtim' => 'modified'); + $dateFields = array('creatim', 'revtim'); + + $content = ''; + + $content .= '{'; + $content .= '\info'; + foreach ($properties as $property) { + $method = 'get' . (array_key_exists($property, $mapping) ? $mapping[$property] : $property); + $value = $docProps->$method(); + $value = in_array($property, $dateFields) ? $this->getDateValue($value) : $value; + $content .= "{\\{$property} {$value}}"; + } + $content .= '}'; + $content .= PHP_EOL; + + return $content; + } + + /** + * Write document formatting properties + * + * @return string + */ + private function writeFormatting() + { + $content = ''; + + $content .= '\deftab720'; // Set the default tab size (720 twips) + $content .= '\viewkind1'; // Set the view mode of the document + + $content .= '\uc1'; // Set the numberof bytes that follows a unicode character + $content .= '\pard'; // Resets to default paragraph properties. + $content .= '\nowidctlpar'; // No widow/orphan control + $content .= '\lang1036'; // Applies a language to a text run (1036 : French (France)) + $content .= '\kerning1'; // Point size (in half-points) above which to kern character pairs + $content .= '\fs' . (Settings::getDefaultFontSize() * 2); // Set the font size in half-points + $content .= PHP_EOL; + + return $content; + } + + /** + * Write sections + * + * @return string + */ + private function writeSections() + { + + $content = ''; + + $sections = $this->getParentWriter()->getPhpWord()->getSections(); + foreach ($sections as $section) { + $styleWriter = new SectionStyleWriter($section->getStyle()); + $styleWriter->setParentWriter($this->getParentWriter()); + $content .= $styleWriter->write(); + + $elementWriter = new Container($this->getParentWriter(), $section); + $content .= $elementWriter->write(); + + $content .= '\sect' . PHP_EOL; + } + + return $content; + } + + /** + * Get date value + * + * The format of date value is `\yr?\mo?\dy?\hr?\min?\sec?` + * + * @param int $value + * @return string + */ + private function getDateValue($value) + { + $dateParts = array( + 'Y' => 'yr', + 'm' => 'mo', + 'd' => 'dy', + 'H' => 'hr', + 'i' => 'min', + 's' => 'sec', + ); + $result = ''; + foreach ($dateParts as $dateFormat => $controlWord) { + $result .= '\\' . $controlWord . date($dateFormat, $value); + } + + return $result; + } +} diff --git a/src/PhpWord/Writer/RTF/Part/Header.php b/src/PhpWord/Writer/RTF/Part/Header.php new file mode 100644 index 00000000..31fbb7f4 --- /dev/null +++ b/src/PhpWord/Writer/RTF/Part/Header.php @@ -0,0 +1,260 @@ +fontTable; + } + + /** + * Get color table. + * + * @return array + */ + public function getColorTable() + { + return $this->colorTable; + } + + /** + * Write part + * + * @return string + */ + public function write() + { + $this->registerFont(); + + $content = ''; + + $content .= $this->writeCharset(); + $content .= $this->writeDefaults(); + $content .= $this->writeFontTable(); + $content .= $this->writeColorTable(); + $content .= $this->writeGenerator(); + $content .= PHP_EOL; + + return $content; + } + + /** + * Write character set + * + * @return string + */ + private function writeCharset() + { + $content = ''; + + $content .= '\ansi'; + $content .= '\ansicpg1252'; + $content .= PHP_EOL; + + return $content; + } + + /** + * Write header defaults + * + * @return string + */ + private function writeDefaults() + { + $content = ''; + + $content .= '\deff0'; + $content .= PHP_EOL; + + return $content; + } + + /** + * Write font table + * + * @return string + */ + private function writeFontTable() + { + $content = ''; + + $content .= '{'; + $content .= '\fonttbl'; + foreach ($this->fontTable as $index => $font) { + $content .= "{\\f{$index}\\fnil\\fcharset0 {$font};}"; + } + $content .= '}'; + $content .= PHP_EOL; + + return $content; + } + + /** + * Write color table + * + * @return string + */ + private function writeColorTable() + { + $content = ''; + + $content .= '{'; + $content .= '\colortbl;'; + foreach ($this->colorTable as $color) { + list($red, $green, $blue) = Converter::htmlToRgb($color); + $content .= "\\red{$red}\\green{$green}\\blue{$blue};"; + } + $content .= '}'; + $content .= PHP_EOL; + + return $content; + } + + /** + * Write + * + * @return string + */ + private function writeGenerator() + { + $content = ''; + + $content .= '{\*\generator PhpWord;}'; // Set the generator + $content .= PHP_EOL; + + return $content; + } + + /** + * Register all fonts and colors in both named and inline styles to appropriate header table. + * + * @return void + */ + private function registerFont() + { + $phpWord = $this->getParentWriter()->getPhpWord(); + $this->fontTable[] = Settings::getDefaultFontName(); + + // Search named styles + $styles = Style::getStyles(); + foreach ($styles as $style) { + $this->registerFontItems($style); + } + + // Search inline styles + $sections = $phpWord->getSections(); + foreach ($sections as $section) { + $elements = $section->getElements(); + $this->registerBorderColor($section->getStyle()); + foreach ($elements as $element) { + if (method_exists($element, 'getFontStyle')) { + $style = $element->getFontStyle(); + $this->registerFontItems($style); + } + } + } + } + + /** + * Register border colors. + * + * @param \PhpOffice\PhpWord\Style\Border $style + * @return void + */ + private function registerBorderColor($style) + { + $colors = $style->getBorderColor(); + foreach ($colors as $color) { + if ($color !== null) { + $this->registerTableItem($this->colorTable, $color); + } + } + } + + /** + * Register fonts and colors. + * + * @param \PhpOffice\PhpWord\Style\AbstractStyle $style + * @return void + */ + private function registerFontItems($style) + { + $defaultFont = Settings::getDefaultFontName(); + $defaultColor = Settings::DEFAULT_FONT_COLOR; + + if ($style instanceof Font) { + $this->registerTableItem($this->fontTable, $style->getName(), $defaultFont); + $this->registerTableItem($this->colorTable, $style->getColor(), $defaultColor); + $this->registerTableItem($this->colorTable, $style->getFgColor(), $defaultColor); + } + } + + /** + * Register individual font and color. + * + * @param array &$table + * @param string $value + * @param string $default + * @return void + */ + private function registerTableItem(&$table, $value, $default = null) + { + if (in_array($value, $table) === false && $value !== null && $value != $default) { + $table[] = $value; + } + } +} diff --git a/src/PhpWord/Writer/RTF/Style/AbstractStyle.php b/src/PhpWord/Writer/RTF/Style/AbstractStyle.php new file mode 100644 index 00000000..7b55fdc2 --- /dev/null +++ b/src/PhpWord/Writer/RTF/Style/AbstractStyle.php @@ -0,0 +1,29 @@ +sizes) - 1; + + // Page border measure + // 8 = from text, infront off; 32 = from edge, infront on; 40 = from edge, infront off + $content .= '\pgbrdropt32'; + + for ($i = 0; $i < $sizeCount; $i++) { + if ($this->sizes[$i] !== null) { + $color = null; + if (isset($this->colors[$i])) { + $color = $this->colors[$i]; + } + $content .= $this->writeSide($sides[$i], $this->sizes[$i], $color); + } + } + + return $content; + } + + /** + * Write side + * + * @param string $side + * @param int $width + * @param string $color + * @return string + */ + private function writeSide($side, $width, $color = '') + { + /** @var \PhpOffice\PhpWord\Writer\RTF $rtfWriter */ + $rtfWriter = $this->getParentWriter(); + $colorIndex = 0; + if ($rtfWriter !== null) { + $colorTable = $rtfWriter->getColorTable(); + $index = array_search($color, $colorTable); + if ($index !== false && $colorIndex !== null) { + $colorIndex = $index + 1; + } + } + + $content = ''; + + $content .= '\pgbrdr' . substr($side, 0, 1); + $content .= '\brdrs'; // Single-thickness border; @todo Get other type of border + $content .= '\brdrw' . $width; // Width + $content .= '\brdrcf' . $colorIndex; // Color + $content .= '\brsp480'; // Space in twips between borders and the paragraph (24pt, following OOXML) + $content .= ' '; + + return $content; + } + + /** + * Set sizes. + * + * @param integer[] $value + * @return void + */ + public function setSizes($value) + { + $this->sizes = $value; + } + + /** + * Set colors. + * + * @param string[] $value + * @return void + */ + public function setColors($value) + { + $this->colors = $value; + } +} diff --git a/src/PhpWord/Writer/RTF/Style/Font.php b/src/PhpWord/Writer/RTF/Style/Font.php new file mode 100644 index 00000000..20c47aee --- /dev/null +++ b/src/PhpWord/Writer/RTF/Style/Font.php @@ -0,0 +1,90 @@ +getStyle(); + if (!$style instanceof FontStyle) { + return ''; + } + + $content = ''; + $content .= '\cf' . $this->colorIndex; + $content .= '\f' . $this->nameIndex; + + $size = $style->getSize(); + $content .= $this->getValueIf(is_numeric($size), '\fs' . ($size * 2)); + + $content .= $this->getValueIf($style->isBold(), '\b'); + $content .= $this->getValueIf($style->isItalic(), '\i'); + $content .= $this->getValueIf($style->getUnderline() != FontStyle::UNDERLINE_NONE, '\ul'); + $content .= $this->getValueIf($style->isStrikethrough(), '\strike'); + $content .= $this->getValueIf($style->isSuperScript(), '\super'); + $content .= $this->getValueIf($style->isSubScript(), '\sub'); + + return $content . ' '; + } + + /** + * Set font name index. + * + * + * @param int $value + * @return void + */ + public function setNameIndex($value = 0) + { + $this->nameIndex = $value; + } + + /** + * Set font color index. + * + * @param int $value + * @return void + */ + public function setColorIndex($value = 0) + { + $this->colorIndex = $value; + } +} diff --git a/src/PhpWord/Writer/RTF/Style/Paragraph.php b/src/PhpWord/Writer/RTF/Style/Paragraph.php new file mode 100644 index 00000000..1a7de0a3 --- /dev/null +++ b/src/PhpWord/Writer/RTF/Style/Paragraph.php @@ -0,0 +1,85 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Paragraph) { + return ''; + } + + $alignments = array( + Alignment::ALIGN_LEFT => '\ql', + Alignment::ALIGN_RIGHT => '\qr', + Alignment::ALIGN_CENTER => '\qc', + Alignment::ALIGN_BOTH => '\qj', + ); + + $align = $style->getAlign(); + $spaceAfter = $style->getSpaceAfter(); + $spaceBefore = $style->getSpaceBefore(); + + $content = ''; + if ($this->nestedLevel == 0) { + $content .= '\pard\nowidctlpar '; + } + if (isset($alignments[$align])) { + $content .= $alignments[$align]; + } + $content .= $this->getValueIf($spaceBefore !== null, '\sb' . $spaceBefore); + $content .= $this->getValueIf($spaceAfter !== null, '\sa' . $spaceAfter); + + return $content; + } + + /** + * Set nested level. + * + * @param int $value + * @return void + */ + public function setNestedLevel($value) + { + $this->nestedLevel = $value; + } +} diff --git a/src/PhpWord/Writer/RTF/Style/Section.php b/src/PhpWord/Writer/RTF/Style/Section.php new file mode 100644 index 00000000..4169b630 --- /dev/null +++ b/src/PhpWord/Writer/RTF/Style/Section.php @@ -0,0 +1,69 @@ +getStyle(); + if (!$style instanceof SectionStyle) { + return ''; + } + + $content = ''; + + $content .= '\sectd '; + + // Size & margin + $content .= $this->getValueIf($style->getPageSizeW() !== null, '\pgwsxn' . $style->getPageSizeW()); + $content .= $this->getValueIf($style->getPageSizeH() !== null, '\pghsxn' . $style->getPageSizeH()); + $content .= ' '; + $content .= $this->getValueIf($style->getMarginTop() !== null, '\margtsxn' . $style->getMarginTop()); + $content .= $this->getValueIf($style->getMarginRight() !== null, '\margrsxn' . $style->getMarginRight()); + $content .= $this->getValueIf($style->getMarginBottom() !== null, '\margbsxn' . $style->getMarginBottom()); + $content .= $this->getValueIf($style->getMarginLeft() !== null, '\marglsxn' . $style->getMarginLeft()); + $content .= $this->getValueIf($style->getHeaderHeight() !== null, '\headery' . $style->getHeaderHeight()); + $content .= $this->getValueIf($style->getFooterHeight() !== null, '\footery' . $style->getFooterHeight()); + $content .= $this->getValueIf($style->getGutter() !== null, '\guttersxn' . $style->getGutter()); + $content .= ' '; + + // Borders + if ($style->hasBorder()) { + $styleWriter = new Border($style); + $styleWriter->setParentWriter($this->getParentWriter()); + $styleWriter->setSizes($style->getBorderSize()); + $styleWriter->setColors($style->getBorderColor()); + $content .= $styleWriter->write(); + } + + return $content . PHP_EOL; + } +} diff --git a/src/PhpWord/Writer/Word2007.php b/src/PhpWord/Writer/Word2007.php old mode 100755 new mode 100644 index 7b552905..baac8222 --- a/src/PhpWord/Writer/Word2007.php +++ b/src/PhpWord/Writer/Word2007.php @@ -1,27 +1,26 @@ array(), 'override' => array()); + private $contentTypes = array('default' => array(), 'override' => array()); /** * Document relationship * * @var array */ - private $docRels = array(); + private $relationships = array(); /** * Create new Word2007 writer * - * @param PhpWord + * @param \PhpOffice\PhpWord\PhpWord */ public function __construct(PhpWord $phpWord = null) { // Assign PhpWord $this->setPhpWord($phpWord); - // Set writer parts - $this->writerParts['contenttypes'] = new ContentTypes(); - $this->writerParts['rels'] = new Rels(); - $this->writerParts['docprops'] = new DocProps(); - $this->writerParts['document'] = new Document(); - $this->writerParts['styles'] = new Styles(); - $this->writerParts['numbering'] = new Numbering(); - $this->writerParts['header'] = new Header(); - $this->writerParts['footer'] = new Footer(); - $this->writerParts['footnotes'] = new Notes(); - $this->writerParts['endnotes'] = new Notes(); - foreach ($this->writerParts as $writer) { - $writer->setParentWriter($this); + // Create parts + $this->parts = array( + 'ContentTypes' => '[Content_Types].xml', + 'Rels' => '_rels/.rels', + 'DocPropsApp' => 'docProps/app.xml', + 'DocPropsCore' => 'docProps/core.xml', + 'DocPropsCustom' => 'docProps/custom.xml', + 'RelsDocument' => 'word/_rels/document.xml.rels', + 'Document' => 'word/document.xml', + 'Styles' => 'word/styles.xml', + 'Numbering' => 'word/numbering.xml', + 'Settings' => 'word/settings.xml', + 'WebSettings' => 'word/webSettings.xml', + 'FontTable' => 'word/fontTable.xml', + 'Theme' => 'word/theme/theme1.xml', + 'RelsPart' => '', + 'Header' => '', + 'Footer' => '', + 'Footnotes' => '', + 'Endnotes' => '', + 'Chart' => '', + ); + foreach (array_keys($this->parts) as $partName) { + $partClass = get_class($this) . '\\Part\\' . $partName; + if (class_exists($partClass)) { + /** @var \PhpOffice\PhpWord\Writer\Word2007\Part\AbstractPart $part Type hint */ + $part = new $partClass(); + $part->setParentWriter($this); + $this->writerParts[strtolower($partName)] = $part; + } } + + // Set package paths + $this->mediaPaths = array('image' => 'word/media/', 'object' => 'word/embeddings/'); } /** - * Save document by name + * Save document by name. * * @param string $filename + * @return void */ public function save($filename = null) { - if (!is_null($this->phpWord)) { - $filename = $this->getTempFile($filename); - $objZip = $this->getZipArchive($filename); + $filename = $this->getTempFile($filename); + $zip = $this->getZipArchive($filename); + $phpWord = $this->getPhpWord(); - // Content types - $this->cTypes['default'] = array( - 'rels' => 'application/vnd.openxmlformats-package.relationships+xml', - 'xml' => 'application/xml', - ); + // Content types + $this->contentTypes['default'] = array( + 'rels' => 'application/vnd.openxmlformats-package.relationships+xml', + 'xml' => 'application/xml', + ); - // Add section media files - $sectionMedia = Media::getElements('section'); - if (!empty($sectionMedia)) { - $this->addFilesToPackage($objZip, $sectionMedia); - foreach ($sectionMedia as $element) { - $this->docRels[] = $element; - } + // Add section media files + $sectionMedia = Media::getElements('section'); + if (!empty($sectionMedia)) { + $this->addFilesToPackage($zip, $sectionMedia); + $this->registerContentTypes($sectionMedia); + foreach ($sectionMedia as $element) { + $this->relationships[] = $element; } - - // Add header/footer media files & relations - $this->addHeaderFooterMedia($objZip, 'header'); - $this->addHeaderFooterMedia($objZip, 'footer'); - - // Add header/footer contents - $rId = Media::countElements('section') + 6; // @see Rels::writeDocRels for 6 first elements - $sections = $this->phpWord->getSections(); - foreach ($sections as $section) { - $this->addHeaderFooterContent($section, $objZip, 'header', $rId); - $this->addHeaderFooterContent($section, $objZip, 'footer', $rId); - } - - $this->addNotes($objZip, $rId, 'footnote'); - $this->addNotes($objZip, $rId, 'endnote'); - - // Write dynamic files - $objZip->addFromString('[Content_Types].xml', $this->getWriterPart('contenttypes')->writeContentTypes($this->cTypes)); - $objZip->addFromString('_rels/.rels', $this->getWriterPart('rels')->writeMainRels()); - $objZip->addFromString('docProps/app.xml', $this->getWriterPart('docprops')->writeDocPropsApp($this->phpWord)); - $objZip->addFromString('docProps/core.xml', $this->getWriterPart('docprops')->writeDocPropsCore($this->phpWord)); - $objZip->addFromString('word/_rels/document.xml.rels', $this->getWriterPart('rels')->writeDocRels($this->docRels)); - $objZip->addFromString('word/document.xml', $this->getWriterPart('document')->writeDocument($this->phpWord)); - $objZip->addFromString('word/styles.xml', $this->getWriterPart('styles')->writeStyles($this->phpWord)); - $objZip->addFromString('word/numbering.xml', $this->getWriterPart('numbering')->writeNumbering()); - - // Write static files - $objZip->addFile(__DIR__ . '/../_staticDocParts/settings.xml', 'word/settings.xml'); - $objZip->addFile(__DIR__ . '/../_staticDocParts/theme1.xml', 'word/theme/theme1.xml'); - $objZip->addFile(__DIR__ . '/../_staticDocParts/webSettings.xml', 'word/webSettings.xml'); - $objZip->addFile(__DIR__ . '/../_staticDocParts/fontTable.xml', 'word/fontTable.xml'); - - // Close file - if ($objZip->close() === false) { - throw new Exception("Could not close zip file $filename."); - } - - $this->cleanupTempFile(); - } else { - throw new Exception("PhpWord object unassigned."); } + + // Add header/footer media files & relations + $this->addHeaderFooterMedia($zip, 'header'); + $this->addHeaderFooterMedia($zip, 'footer'); + + // Add header/footer contents + $rId = Media::countElements('section') + 6; // @see Rels::writeDocRels for 6 first elements + $sections = $phpWord->getSections(); + foreach ($sections as $section) { + $this->addHeaderFooterContent($section, $zip, 'header', $rId); + $this->addHeaderFooterContent($section, $zip, 'footer', $rId); + } + + $this->addNotes($zip, $rId, 'footnote'); + $this->addNotes($zip, $rId, 'endnote'); + $this->addChart($zip, $rId); + + // Write parts + foreach ($this->parts as $partName => $fileName) { + if ($fileName != '') { + $zip->addFromString($fileName, $this->getWriterPart($partName)->write()); + } + } + + // Close zip archive and cleanup temp file + $zip->close(); + $this->cleanupTempFile(); } /** - * Add section files to package + * Get content types * - * @param mixed $objZip - * @param mixed $elements + * @return array */ - private function addFilesToPackage($objZip, $elements) + public function getContentTypes() { - foreach ($elements as $element) { - // Do not add link - if ($element['type'] == 'link') { - continue; - } - // Retrieve remote image - 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); - } else { - $objZip->addFile($element['source'], 'word/' . $element['target']); - } - // Register content types - if ($element['type'] == 'image') { - $imageExtension = $element['imageExtension']; - $imageType = $element['imageType']; - if (!array_key_exists($imageExtension, $this->cTypes['default'])) { - $this->cTypes['default'][$imageExtension] = $imageType; - } - } else { - if (!array_key_exists('bin', $this->cTypes['default'])) { - $this->cTypes['default']['bin'] = 'application/vnd.openxmlformats-officedocument.oleObject'; - } - } - } + return $this->contentTypes; } /** - * Add header/footer media files + * Get content types * - * @param mixed $objZip - * @param string $docPart + * @return array */ - private function addHeaderFooterMedia($objZip, $docPart) + public function getRelationships() + { + return $this->relationships; + } + + /** + * Add header/footer media files, e.g. footer1.xml.rels. + * + * @param \PhpOffice\PhpWord\Shared\ZipArchive $zip + * @param string $docPart + * @return void + */ + private function addHeaderFooterMedia(ZipArchive $zip, $docPart) { $elements = Media::getElements($docPart); if (!empty($elements)) { foreach ($elements as $file => $media) { if (count($media) > 0) { if (!empty($media)) { - $this->addFilesToPackage($objZip, $media); + $this->addFilesToPackage($zip, $media); + $this->registerContentTypes($media); } - $relsFile = "word/_rels/{$file}.xml.rels"; - $objZip->addFromString($relsFile, $this->getWriterPart('rels')->writeMediaRels($media)); + + /** @var \PhpOffice\PhpWord\Writer\Word2007\Part\AbstractPart $writerPart Type hint */ + $writerPart = $this->getWriterPart('relspart')->setMedia($media); + $zip->addFromString("word/_rels/{$file}.xml.rels", $writerPart->write()); } } } } /** - * Add header/footer content + * Add header/footer content. * - * @param mixed $objZip - * @param string $elmType - * @param integer $rId + * @param \PhpOffice\PhpWord\Element\Section &$section + * @param \PhpOffice\PhpWord\Shared\ZipArchive $zip + * @param string $elmType header|footer + * @param integer &$rId + * @return void */ - private function addHeaderFooterContent(Section &$section, $objZip, $elmType, &$rId) + private function addHeaderFooterContent(Section &$section, ZipArchive $zip, $elmType, &$rId) { $getFunction = $elmType == 'header' ? 'getHeaders' : 'getFooters'; - $writeFunction = $elmType == 'header' ? 'writeHeader' : 'writeFooter'; $elmCount = ($section->getSectionId() - 1) * 3; - $elmObjects = $section->$getFunction(); - foreach ($elmObjects as $index => &$elmObject) { + $elements = $section->$getFunction(); + foreach ($elements as &$element) { + /** @var \PhpOffice\PhpWord\Element\AbstractElement $element Type hint */ $elmCount++; - $elmObject->setRelationId(++$rId); - $elmFile = "{$elmType}{$elmCount}.xml"; - $objZip->addFromString("word/$elmFile", $this->getWriterPart($elmType)->$writeFunction($elmObject)); - $this->cTypes['override']["/word/$elmFile"] = $elmType; - $this->docRels[] = array('target' => $elmFile, 'type' => $elmType, 'rID' => $rId); + $element->setRelationId(++$rId); + $elmFile = "{$elmType}{$elmCount}.xml"; // e.g. footer1.xml + $this->contentTypes['override']["/word/$elmFile"] = $elmType; + $this->relationships[] = array('target' => $elmFile, 'type' => $elmType, 'rID' => $rId); + + /** @var \PhpOffice\PhpWord\Writer\Word2007\Part\AbstractPart $writerPart Type hint */ + $writerPart = $this->getWriterPart($elmType)->setElement($element); + $zip->addFromString("word/$elmFile", $writerPart->write()); } } /** * Add footnotes/endnotes * - * @param mixed $objZip - * @param integer $rId - * @param string $notesType + * @param \PhpOffice\PhpWord\Shared\ZipArchive $zip + * @param integer &$rId + * @param string $noteType + * @return void */ - private function addNotes($objZip, &$rId, $notesType = 'footnote') + private function addNotes(ZipArchive $zip, &$rId, $noteType = 'footnote') { - $notesType = ($notesType == 'endnote') ? 'endnote' : 'footnote'; - $notesTypes = "{$notesType}s"; - $collection = 'PhpOffice\\PhpWord\\' . ucfirst($notesTypes); - $xmlFile = "{$notesTypes}.xml"; - $relsFile = "word/_rels/{$xmlFile}.rels"; - $xmlPath = "word/{$xmlFile}"; + $phpWord = $this->getPhpWord(); + $noteType = ($noteType == 'endnote') ? 'endnote' : 'footnote'; + $partName = "{$noteType}s"; + $method = 'get' . $partName; + $collection = $phpWord->$method(); // Add footnotes media files, relations, and contents - if ($collection::countElements() > 0) { - $media = Media::getElements($notesType); - $elements = $collection::getElements(); - $this->addFilesToPackage($objZip, $media); + /** @var \PhpOffice\PhpWord\Collection\AbstractCollection $collection Type hint */ + if ($collection->countItems() > 0) { + $media = Media::getElements($noteType); + $this->addFilesToPackage($zip, $media); + $this->registerContentTypes($media); + $this->contentTypes['override']["/word/{$partName}.xml"] = $partName; + $this->relationships[] = array('target' => "{$partName}.xml", 'type' => $partName, 'rID' => ++$rId); + + // Write relationships file, e.g. word/_rels/footnotes.xml if (!empty($media)) { - $objZip->addFromString($relsFile, $this->getWriterPart('rels')->writeMediaRels($media)); + /** @var \PhpOffice\PhpWord\Writer\Word2007\Part\AbstractPart $writerPart Type hint */ + $writerPart = $this->getWriterPart('relspart')->setMedia($media); + $zip->addFromString("word/_rels/{$partName}.xml.rels", $writerPart->write()); + } + + // Write content file, e.g. word/footnotes.xml + $writerPart = $this->getWriterPart($partName)->setElements($collection->getItems()); + $zip->addFromString("word/{$partName}.xml", $writerPart->write()); + } + } + + /** + * Add chart. + * + * @param \PhpOffice\PhpWord\Shared\ZipArchive $zip + * @param integer &$rId + * @return void + */ + private function addChart(ZipArchive $zip, &$rId) + { + $phpWord = $this->getPhpWord(); + + $collection = $phpWord->getCharts(); + $index = 0; + if ($collection->countItems() > 0) { + foreach ($collection->getItems() as $chart) { + $index++; + $rId++; + $filename = "charts/chart{$index}.xml"; + + // ContentTypes.xml + $this->contentTypes['override']["/word/{$filename}"] = 'chart'; + + // word/_rels/document.xml.rel + $this->relationships[] = array('target' => $filename, 'type' => 'chart', 'rID' => $rId); + + // word/charts/chartN.xml + /** @var \PhpOffice\PhpWord\Element\Chart $chart */ + $chart->setRelationId($rId); + $writerPart = $this->getWriterPart('Chart'); + $writerPart->setElement($chart); + $zip->addFromString("word/{$filename}", $writerPart->write()); + } + } + } + + /** + * Register content types for each media. + * + * @param array $media + * @return void + */ + private function registerContentTypes($media) + { + foreach ($media as $medium) { + $mediumType = $medium['type']; + if ($mediumType == 'image') { + $extension = $medium['imageExtension']; + if (!array_key_exists($extension, $this->contentTypes['default'])) { + $this->contentTypes['default'][$extension] = $medium['imageType']; + } + } elseif ($mediumType == 'object') { + if (!array_key_exists('bin', $this->contentTypes['default'])) { + $this->contentTypes['default']['bin'] = 'application/vnd.openxmlformats-officedocument.oleObject'; + } } - $objZip->addFromString($xmlPath, $this->getWriterPart($notesTypes)->writeNotes($elements, $notesTypes)); - $this->cTypes['override']["/{$xmlPath}"] = $notesTypes; - $this->docRels[] = array('target' => $xmlFile, 'type' => $notesTypes, 'rID' => ++$rId); } } } diff --git a/src/PhpWord/Writer/Word2007/AbstractWriterPart.php b/src/PhpWord/Writer/Word2007/AbstractWriterPart.php deleted file mode 100755 index b58797db..00000000 --- a/src/PhpWord/Writer/Word2007/AbstractWriterPart.php +++ /dev/null @@ -1,72 +0,0 @@ -parentWriter = $pWriter; - } - - /** - * Get parent writer - * - * @return WriterInterface - * @throws Exception - */ - public function getParentWriter() - { - if (!is_null($this->parentWriter)) { - return $this->parentWriter; - } else { - throw new Exception("No parent WriterInterface assigned."); - } - } - - /** - * Get XML Writer - * - * @return XMLWriter - */ - protected function getXmlWriter() - { - $useDiskCaching = false; - if (!is_null($this->parentWriter)) { - if ($this->parentWriter->getUseDiskCaching()) { - $useDiskCaching = true; - } - } - if ($useDiskCaching) { - return new XMLWriter(XMLWriter::STORAGE_DISK, $this->parentWriter->getDiskCachingDirectory()); - } else { - return new XMLWriter(XMLWriter::STORAGE_MEMORY); - } - } -} diff --git a/src/PhpWord/Writer/Word2007/Base.php b/src/PhpWord/Writer/Word2007/Base.php deleted file mode 100644 index b74211a5..00000000 --- a/src/PhpWord/Writer/Word2007/Base.php +++ /dev/null @@ -1,1245 +0,0 @@ -getFontStyle(); - $styleParagraph = $text->getParagraphStyle(); - $strText = htmlspecialchars($text->getText()); - $strText = String::controlCharacterPHP2OOXML($strText); - - if (!$withoutP) { - $xmlWriter->startElement('w:p'); - $this->writeInlineParagraphStyle($xmlWriter, $styleParagraph); - } - $xmlWriter->startElement('w:r'); - $this->writeInlineFontStyle($xmlWriter, $styleFont); - $xmlWriter->startElement('w:t'); - $xmlWriter->writeAttribute('xml:space', 'preserve'); - $xmlWriter->writeRaw($strText); - $xmlWriter->endElement(); - $xmlWriter->endElement(); // w:r - if (!$withoutP) { - $xmlWriter->endElement(); // w:p - } - } - - /** - * Write textrun element - * - * @param XMLWriter $xmlWriter - * @param TextRun $textrun - */ - protected function writeTextRun(XMLWriter $xmlWriter, TextRun $textrun) - { - $styleParagraph = $textrun->getParagraphStyle(); - $xmlWriter->startElement('w:p'); - $this->writeInlineParagraphStyle($xmlWriter, $styleParagraph); - $this->writeContainerElements($xmlWriter, $textrun); - $xmlWriter->endElement(); // w:p - } - - /** - * Write link element - * - * @param XMLWriter $xmlWriter - * @param Link $link - * @param boolean $withoutP - */ - protected function writeLink(XMLWriter $xmlWriter, Link $link, $withoutP = false) - { - $rId = $link->getRelationId() + ($link->isInSection() ? 6 : 0); - $linkName = $link->getLinkName(); - if (is_null($linkName)) { - $linkName = $link->getLinkSrc(); - } - $styleFont = $link->getFontStyle(); - $styleParagraph = $link->getParagraphStyle(); - - if (!$withoutP) { - $xmlWriter->startElement('w:p'); - $this->writeInlineParagraphStyle($xmlWriter, $styleParagraph); - } - $xmlWriter->startElement('w:hyperlink'); - $xmlWriter->writeAttribute('r:id', 'rId' . $rId); - $xmlWriter->writeAttribute('w:history', '1'); - $xmlWriter->startElement('w:r'); - $this->writeInlineFontStyle($xmlWriter, $styleFont); - $xmlWriter->startElement('w:t'); - $xmlWriter->writeAttribute('xml:space', 'preserve'); // needed because of drawing spaces before and after text - $xmlWriter->writeRaw($linkName); - $xmlWriter->endElement(); // w:t - $xmlWriter->endElement(); // w:r - $xmlWriter->endElement(); // w:hyperlink - if (!$withoutP) { - $xmlWriter->endElement(); // w:p - } - } - - /** - * Write title element - * - * @param XMLWriter $xmlWriter - * @param Title $title - */ - protected function writeTitle(XMLWriter $xmlWriter, Title $title) - { - $text = htmlspecialchars($title->getText()); - $text = String::controlCharacterPHP2OOXML($text); - $anchor = $title->getAnchor(); - $bookmarkId = $title->getBookmarkId(); - $style = $title->getStyle(); - - $xmlWriter->startElement('w:p'); - - if (!empty($style)) { - $xmlWriter->startElement('w:pPr'); - $xmlWriter->startElement('w:pStyle'); - $xmlWriter->writeAttribute('w:val', $style); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } - - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:fldChar'); - $xmlWriter->writeAttribute('w:fldCharType', 'end'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - $xmlWriter->startElement('w:bookmarkStart'); - $xmlWriter->writeAttribute('w:id', $bookmarkId); - $xmlWriter->writeAttribute('w:name', $anchor); - $xmlWriter->endElement(); - - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:t'); - $xmlWriter->writeRaw($text); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - $xmlWriter->startElement('w:bookmarkEnd'); - $xmlWriter->writeAttribute('w:id', $bookmarkId); - $xmlWriter->endElement(); - - $xmlWriter->endElement(); - } - - /** - * Write preserve text element - * - * @param XMLWriter $xmlWriter - * @param PreserveText $textrun - */ - protected function writePreserveText(XMLWriter $xmlWriter, PreserveText $textrun) - { - $styleFont = $textrun->getFontStyle(); - $styleParagraph = $textrun->getParagraphStyle(); - - $arrText = $textrun->getText(); - if (!is_array($arrText)) { - $arrText = array($arrText); - } - - $xmlWriter->startElement('w:p'); - $this->writeInlineParagraphStyle($xmlWriter, $styleParagraph); - foreach ($arrText as $text) { - if (substr($text, 0, 1) == '{') { - $text = substr($text, 1, -1); - - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:fldChar'); - $xmlWriter->writeAttribute('w:fldCharType', 'begin'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - $xmlWriter->startElement('w:r'); - $this->writeInlineFontStyle($xmlWriter, $styleFont); - $xmlWriter->startElement('w:instrText'); - $xmlWriter->writeAttribute('xml:space', 'preserve'); - $xmlWriter->writeRaw($text); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:fldChar'); - $xmlWriter->writeAttribute('w:fldCharType', 'separate'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:fldChar'); - $xmlWriter->writeAttribute('w:fldCharType', 'end'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } else { - $text = htmlspecialchars($text); - $text = String::controlCharacterPHP2OOXML($text); - - $xmlWriter->startElement('w:r'); - $this->writeInlineFontStyle($xmlWriter, $styleFont); - $xmlWriter->startElement('w:t'); - $xmlWriter->writeAttribute('xml:space', 'preserve'); - $xmlWriter->writeRaw($text); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } - } - - $xmlWriter->endElement(); // p - } - - /** - * Write text break element - * - * @param XMLWriter $xmlWriter - * @param TextBreak $element - * @param boolean $withoutP - */ - protected function writeTextBreak(XMLWriter $xmlWriter, TextBreak $element = null, $withoutP = false) - { - if (!$withoutP) { - $hasStyle = false; - $styleFont = null; - $styleParagraph = null; - if (!is_null($element)) { - $styleFont = $element->getFontStyle(); - $styleParagraph = $element->getParagraphStyle(); - $hasStyle = !is_null($styleFont) || !is_null($styleParagraph); - } - if ($hasStyle) { - $xmlWriter->startElement('w:p'); - $this->writeInlineParagraphStyle($xmlWriter, $styleParagraph); - if (!is_null($styleFont)) { - $xmlWriter->startElement('w:pPr'); - $this->writeInlineFontStyle($xmlWriter, $styleFont); - $xmlWriter->endElement(); // w:pPr - } - $xmlWriter->endElement(); // w:p - } else { - $xmlWriter->writeElement('w:p'); - } - } else { - $xmlWriter->writeElement('w:br'); - } - } - - /** - * Write list item element - * - * @param XMLWriter $xmlWriter - * @param ListItem $listItem - */ - protected function writeListItem(XMLWriter $xmlWriter, ListItem $listItem) - { - $textObject = $listItem->getTextObject(); - $depth = $listItem->getDepth(); - $numId = $listItem->getStyle()->getNumId(); - $styleParagraph = $textObject->getParagraphStyle(); - - $xmlWriter->startElement('w:p'); - $xmlWriter->startElement('w:pPr'); - $this->writeInlineParagraphStyle($xmlWriter, $styleParagraph, true); - $xmlWriter->startElement('w:numPr'); - $xmlWriter->startElement('w:ilvl'); - $xmlWriter->writeAttribute('w:val', $depth); - $xmlWriter->endElement(); // w:ilvl - $xmlWriter->startElement('w:numId'); - $xmlWriter->writeAttribute('w:val', $numId); - $xmlWriter->endElement(); // w:numId - $xmlWriter->endElement(); // w:numPr - $xmlWriter->endElement(); // w:pPr - $this->writeText($xmlWriter, $textObject, true); - $xmlWriter->endElement(); // w:p - } - - /** - * Write footnote reference element - * - * @param XMLWriter $xmlWriter - * @param Table $table - */ - protected function writeTable(XMLWriter $xmlWriter, Table $table) - { - $rows = $table->getRows(); - $cRows = count($rows); - - if ($cRows > 0) { - $xmlWriter->startElement('w:tbl'); - - // Table grid - $cellWidths = array(); - for ($i = 0; $i < $cRows; $i++) { - $row = $rows[$i]; - $cells = $row->getCells(); - if (count($cells) <= count($cellWidths)) { - continue; - } - $cellWidths = array(); - foreach ($cells as $cell) { - $cellWidths[] = $cell->getWidth(); - } - } - $xmlWriter->startElement('w:tblGrid'); - foreach ($cellWidths as $width) { - $xmlWriter->startElement('w:gridCol'); - if (!is_null($width)) { - $xmlWriter->writeAttribute('w:w', $width); - $xmlWriter->writeAttribute('w:type', 'dxa'); - } - $xmlWriter->endElement(); - } - $xmlWriter->endElement(); // w:tblGrid - - // Table style - $tblStyle = $table->getStyle(); - $tblWidth = $table->getWidth(); - if ($tblStyle instanceof TableStyle) { - $this->writeTableStyle($xmlWriter, $tblStyle, false); - } else { - if (!empty($tblStyle)) { - $xmlWriter->startElement('w:tblPr'); - $xmlWriter->startElement('w:tblStyle'); - $xmlWriter->writeAttribute('w:val', $tblStyle); - $xmlWriter->endElement(); - if (!is_null($tblWidth)) { - $xmlWriter->startElement('w:tblW'); - $xmlWriter->writeAttribute('w:w', $tblWidth); - $xmlWriter->writeAttribute('w:type', 'pct'); - $xmlWriter->endElement(); - } - $xmlWriter->endElement(); - } - } - - // Table rows - for ($i = 0; $i < $cRows; $i++) { - $row = $rows[$i]; - $height = $row->getHeight(); - $rowStyle = $row->getStyle(); - $tblHeader = $rowStyle->getTblHeader(); - $cantSplit = $rowStyle->getCantSplit(); - $exactHeight = $rowStyle->getExactHeight(); - - $xmlWriter->startElement('w:tr'); - if (!is_null($height) || !is_null($tblHeader) || !is_null($cantSplit)) { - $xmlWriter->startElement('w:trPr'); - if (!is_null($height)) { - $xmlWriter->startElement('w:trHeight'); - $xmlWriter->writeAttribute('w:val', $height); - $xmlWriter->writeAttribute('w:hRule', ($exactHeight ? 'exact' : 'atLeast')); - $xmlWriter->endElement(); - } - if ($tblHeader) { - $xmlWriter->startElement('w:tblHeader'); - $xmlWriter->writeAttribute('w:val', '1'); - $xmlWriter->endElement(); - } - if ($cantSplit) { - $xmlWriter->startElement('w:cantSplit'); - $xmlWriter->writeAttribute('w:val', '1'); - $xmlWriter->endElement(); - } - $xmlWriter->endElement(); - } - foreach ($row->getCells() as $cell) { - $cellStyle = $cell->getStyle(); - $width = $cell->getWidth(); - $xmlWriter->startElement('w:tc'); - $xmlWriter->startElement('w:tcPr'); - $xmlWriter->startElement('w:tcW'); - $xmlWriter->writeAttribute('w:w', $width); - $xmlWriter->writeAttribute('w:type', 'dxa'); - $xmlWriter->endElement(); // w:tcW - if ($cellStyle instanceof Cell) { - $this->writeCellStyle($xmlWriter, $cellStyle); - } - $xmlWriter->endElement(); // w:tcPr - $this->writeContainerElements($xmlWriter, $cell); - $xmlWriter->endElement(); // w:tc - } - $xmlWriter->endElement(); // w:tr - } - $xmlWriter->endElement(); - } - } - - /** - * Write image element - * - * @param XMLWriter $xmlWriter - * @param Image $image - * @param boolean $withoutP - */ - protected function writeImage(XMLWriter $xmlWriter, Image $image, $withoutP = false) - { - $rId = $image->getRelationId() + ($image->isInSection() ? 6 : 0); - - $style = $image->getStyle(); - $width = $style->getWidth(); - $height = $style->getHeight(); - $align = $style->getAlign(); - $marginTop = $style->getMarginTop(); - $marginLeft = $style->getMarginLeft(); - $wrappingStyle = $style->getWrappingStyle(); - - if (!$withoutP) { - $xmlWriter->startElement('w:p'); - - if (!is_null($align)) { - $xmlWriter->startElement('w:pPr'); - $xmlWriter->startElement('w:jc'); - $xmlWriter->writeAttribute('w:val', $align); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } - } - $xmlWriter->startElement('w:r'); - - $xmlWriter->startElement('w:pict'); - - $xmlWriter->startElement('v:shape'); - $xmlWriter->writeAttribute('type', '#_x0000_t75'); - - $imgStyle = ''; - if (null !== $width) { - $imgStyle .= 'width:' . $width . 'px;'; - } - if (null !== $height) { - $imgStyle .= 'height:' . $height . 'px;'; - } - if (null !== $marginTop) { - $imgStyle .= 'margin-top:' . $marginTop . 'in;'; - } - if (null !== $marginLeft) { - $imgStyle .= 'margin-left:' . $marginLeft . 'in;'; - } - - switch ($wrappingStyle) { - case ImageStyle::WRAPPING_STYLE_BEHIND: - $imgStyle .= 'position:absolute;z-index:-251658752;'; - break; - case ImageStyle::WRAPPING_STYLE_SQUARE: - $imgStyle .= 'position:absolute;z-index:251659264;mso-position-horizontal:absolute;mso-position-vertical:absolute;'; - break; - case ImageStyle::WRAPPING_STYLE_TIGHT: - $imgStyle .= 'position:absolute;z-index:251659264;mso-wrap-edited:f;mso-position-horizontal:absolute;mso-position-vertical:absolute'; - break; - case ImageStyle::WRAPPING_STYLE_INFRONT: - $imgStyle .= 'position:absolute;zz-index:251659264;mso-position-horizontal:absolute;mso-position-vertical:absolute;'; - break; - } - - $xmlWriter->writeAttribute('style', $imgStyle); - - $xmlWriter->startElement('v:imagedata'); - $xmlWriter->writeAttribute('r:id', 'rId' . $rId); - $xmlWriter->writeAttribute('o:title', ''); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - $xmlWriter->endElement(); - - $xmlWriter->endElement(); - - if (!$withoutP) { - $xmlWriter->endElement(); // w:p - } - } - - /** - * Write watermark element - * - * @param XMLWriter $xmlWriter - * @param Image $image - */ - protected function writeWatermark(XMLWriter $xmlWriter, Image $image) - { - $rId = $image->getRelationId(); - - $style = $image->getStyle(); - $width = $style->getWidth(); - $height = $style->getHeight(); - $marginLeft = $style->getMarginLeft(); - $marginTop = $style->getMarginTop(); - - $xmlWriter->startElement('w:p'); - - $xmlWriter->startElement('w:r'); - - $xmlWriter->startElement('w:pict'); - - $xmlWriter->startElement('v:shape'); - $xmlWriter->writeAttribute('type', '#_x0000_t75'); - - $strStyle = 'position:absolute;'; - $strStyle .= ' width:' . $width . 'px;'; - $strStyle .= ' height:' . $height . 'px;'; - if (!is_null($marginTop)) { - $strStyle .= ' margin-top:' . $marginTop . 'px;'; - } - if (!is_null($marginLeft)) { - $strStyle .= ' margin-left:' . $marginLeft . 'px;'; - } - - $xmlWriter->writeAttribute('style', $strStyle); - - $xmlWriter->startElement('v:imagedata'); - $xmlWriter->writeAttribute('r:id', 'rId' . $rId); - $xmlWriter->writeAttribute('o:title', ''); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - $xmlWriter->endElement(); - - $xmlWriter->endElement(); - - $xmlWriter->endElement(); - } - - /** - * Write object element - * - * @param XMLWriter $xmlWriter - * @param Object $object - * @param boolean $withoutP - */ - protected function writeObject(XMLWriter $xmlWriter, Object $object, $withoutP = false) - { - $rIdObject = $object->getRelationId() + ($object->isInSection() ? 6 : 0); - $rIdImage = $object->getImageRelationId() + ($object->isInSection() ? 6 : 0); - $shapeId = md5($rIdObject . '_' . $rIdImage); - $objectId = $object->getRelationId() + 1325353440; - $style = $object->getStyle(); - $align = $style->getAlign(); - - if (!$withoutP) { - $xmlWriter->startElement('w:p'); - } - if (!is_null($align)) { - $xmlWriter->startElement('w:pPr'); - $xmlWriter->startElement('w:jc'); - $xmlWriter->writeAttribute('w:val', $align); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:object'); - $xmlWriter->writeAttribute('w:dxaOrig', '249'); - $xmlWriter->writeAttribute('w:dyaOrig', '160'); - $xmlWriter->startElement('v:shape'); - $xmlWriter->writeAttribute('id', $shapeId); - $xmlWriter->writeAttribute('type', '#_x0000_t75'); - $xmlWriter->writeAttribute('style', 'width:104px;height:67px'); - $xmlWriter->writeAttribute('o:ole', ''); - $xmlWriter->startElement('v:imagedata'); - $xmlWriter->writeAttribute('r:id', 'rId' . $rIdImage); - $xmlWriter->writeAttribute('o:title', ''); - $xmlWriter->endElement(); // v:imagedata - $xmlWriter->endElement(); // v:shape - $xmlWriter->startElement('o:OLEObject'); - $xmlWriter->writeAttribute('Type', 'Embed'); - $xmlWriter->writeAttribute('ProgID', 'Package'); - $xmlWriter->writeAttribute('ShapeID', $shapeId); - $xmlWriter->writeAttribute('DrawAspect', 'Icon'); - $xmlWriter->writeAttribute('ObjectID', '_' . $objectId); - $xmlWriter->writeAttribute('r:id', 'rId' . $rIdObject); - $xmlWriter->endElement(); // o:OLEObject - $xmlWriter->endElement(); // w:object - $xmlWriter->endElement(); // w:r - if (!$withoutP) { - $xmlWriter->endElement(); // w:p - } - } - - /** - * Write footnote element which links to the actual content in footnotes.xml - * - * @param XMLWriter $xmlWriter - * @param Footnote $footnote - * @param boolean $withoutP - */ - protected function writeFootnote(XMLWriter $xmlWriter, Footnote $footnote, $withoutP = false) - { - if (!$withoutP) { - $xmlWriter->startElement('w:p'); - } - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:rPr'); - $xmlWriter->startElement('w:rStyle'); - $xmlWriter->writeAttribute('w:val', 'FootnoteReference'); - $xmlWriter->endElement(); // w:rStyle - $xmlWriter->endElement(); // w:rPr - $xmlWriter->startElement('w:footnoteReference'); - $xmlWriter->writeAttribute('w:id', $footnote->getRelationId()); - $xmlWriter->endElement(); // w:footnoteReference - $xmlWriter->endElement(); // w:r - if (!$withoutP) { - $xmlWriter->endElement(); // w:p - } - } - - /** - * Write endnote element which links to the actual content in endnotes.xml - * - * @param XMLWriter $xmlWriter - * @param Endnote $endnote - * @param boolean $withoutP - */ - protected function writeEndnote(XMLWriter $xmlWriter, Endnote $endnote, $withoutP = false) - { - if (!$withoutP) { - $xmlWriter->startElement('w:p'); - } - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:rPr'); - $xmlWriter->startElement('w:rStyle'); - $xmlWriter->writeAttribute('w:val', 'EndnoteReference'); - $xmlWriter->endElement(); // w:rStyle - $xmlWriter->endElement(); // w:rPr - $xmlWriter->startElement('w:endnoteReference'); - $xmlWriter->writeAttribute('w:id', $endnote->getRelationId()); - $xmlWriter->endElement(); // w:endnoteReference - $xmlWriter->endElement(); // w:r - if (!$withoutP) { - $xmlWriter->endElement(); // w:p - } - } - - /** - * Write CheckBox - * - * @param boolean $withoutP - * @param boolean $checkState - */ - protected function writeCheckBox(XMLWriter $xmlWriter, CheckBox $checkbox, $withoutP = false, $checkState = false) - { - $name = htmlspecialchars($checkbox->getName()); - $name = String::controlCharacterPHP2OOXML($name); - $text = htmlspecialchars($checkbox->getText()); - $text = String::controlCharacterPHP2OOXML($text); - $styleFont = $checkbox->getFontStyle(); - $styleParagraph = $checkbox->getParagraphStyle(); - - if (!$withoutP) { - $xmlWriter->startElement('w:p'); - $this->writeInlineParagraphStyle($xmlWriter, $styleParagraph); - } - - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:fldChar'); - $xmlWriter->writeAttribute('w:fldCharType', 'begin'); - $xmlWriter->startElement('w:ffData'); - $xmlWriter->startElement('w:name'); - $xmlWriter->writeAttribute('w:val', $name); - $xmlWriter->endElement(); //w:name - $xmlWriter->writeAttribute('w:enabled', ''); - $xmlWriter->startElement('w:calcOnExit'); - $xmlWriter->writeAttribute('w:val', '0'); - $xmlWriter->endElement(); //w:calcOnExit - $xmlWriter->startElement('w:checkBox'); - $xmlWriter->writeAttribute('w:sizeAuto', ''); - $xmlWriter->startElement('w:default'); - $xmlWriter->writeAttribute('w:val', ($checkState ? '1' : '0')); - $xmlWriter->endElement(); //w:default - $xmlWriter->endElement(); //w:checkBox - $xmlWriter->endElement(); // w:ffData - $xmlWriter->endElement(); // w:fldChar - $xmlWriter->endElement(); // w:r - - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:instrText'); - $xmlWriter->writeAttribute('xml:space', 'preserve'); - $xmlWriter->writeRaw(' FORMCHECKBOX '); - $xmlWriter->endElement();// w:instrText - $xmlWriter->endElement(); // w:r - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:fldChar'); - $xmlWriter->writeAttribute('w:fldCharType', 'seperate'); - $xmlWriter->endElement();// w:fldChar - $xmlWriter->endElement(); // w:r - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:fldChar'); - $xmlWriter->writeAttribute('w:fldCharType', 'end'); - $xmlWriter->endElement();// w:fldChar - $xmlWriter->endElement(); // w:r - - $xmlWriter->startElement('w:r'); - $this->writeInlineFontStyle($xmlWriter, $styleFont); - $xmlWriter->startElement('w:t'); - $xmlWriter->writeAttribute('xml:space', 'preserve'); - $xmlWriter->writeRaw($text); - $xmlWriter->endElement(); // w:t - $xmlWriter->endElement(); // w:r - - if (!$withoutP) { - $xmlWriter->endElement(); // w:p - } - } - - /** - * Write paragraph style - * - * @param XMLWriter $xmlWriter - * @param Paragraph $style - * @param bool $withoutPPR - */ - protected function writeParagraphStyle(XMLWriter $xmlWriter, Paragraph $style, $withoutPPR = false) - { - - $align = $style->getAlign(); - $spacing = $style->getSpacing(); - $spaceBefore = $style->getSpaceBefore(); - $spaceAfter = $style->getSpaceAfter(); - $indent = $style->getIndent(); - $hanging = $style->getHanging(); - $tabs = $style->getTabs(); - $widowControl = $style->getWidowControl(); - $keepNext = $style->getKeepNext(); - $keepLines = $style->getKeepLines(); - $pageBreakBefore = $style->getPageBreakBefore(); - - if (!is_null($align) || !is_null($spacing) || !is_null($spaceBefore) || - !is_null($spaceAfter) || !is_null($indent) || !is_null($hanging) || - !is_null($tabs) || !is_null($widowControl) || !is_null($keepNext) || - !is_null($keepLines) || !is_null($pageBreakBefore)) { - if (!$withoutPPR) { - $xmlWriter->startElement('w:pPr'); - } - - // Alignment - if (!is_null($align)) { - $xmlWriter->startElement('w:jc'); - $xmlWriter->writeAttribute('w:val', $align); - $xmlWriter->endElement(); - } - - // Indentation - if (!is_null($indent) || !is_null($hanging)) { - $xmlWriter->startElement('w:ind'); - $xmlWriter->writeAttribute('w:firstLine', 0); - if (!is_null($indent)) { - $xmlWriter->writeAttribute('w:left', $indent); - } - if (!is_null($hanging)) { - $xmlWriter->writeAttribute('w:hanging', $hanging); - } - $xmlWriter->endElement(); - } - - // Spacing - if (!is_null($spaceBefore) || !is_null($spaceAfter) || - !is_null($spacing)) { - $xmlWriter->startElement('w:spacing'); - if (!is_null($spaceBefore)) { - $xmlWriter->writeAttribute('w:before', $spaceBefore); - } - if (!is_null($spaceAfter)) { - $xmlWriter->writeAttribute('w:after', $spaceAfter); - } - if (!is_null($spacing)) { - $xmlWriter->writeAttribute('w:line', $spacing); - $xmlWriter->writeAttribute('w:lineRule', 'auto'); - } - $xmlWriter->endElement(); - } - - // Pagination - if (!$widowControl) { - $xmlWriter->startElement('w:widowControl'); - $xmlWriter->writeAttribute('w:val', '0'); - $xmlWriter->endElement(); - } - if ($keepNext) { - $xmlWriter->startElement('w:keepNext'); - $xmlWriter->writeAttribute('w:val', '1'); - $xmlWriter->endElement(); - } - if ($keepLines) { - $xmlWriter->startElement('w:keepLines'); - $xmlWriter->writeAttribute('w:val', '1'); - $xmlWriter->endElement(); - } - if ($pageBreakBefore) { - $xmlWriter->startElement('w:pageBreakBefore'); - $xmlWriter->writeAttribute('w:val', '1'); - $xmlWriter->endElement(); - } - - // Tabs - if (!is_null($tabs)) { - $tabs->toXml($xmlWriter); - } - - if (!$withoutPPR) { - $xmlWriter->endElement(); // w:pPr - } - } - } - - /** - * Write font style - * - * @param XMLWriter $xmlWriter - * @param Font $style - */ - protected function writeFontStyle(XMLWriter $xmlWriter, Font $style) - { - $font = $style->getName(); - $bold = $style->getBold(); - $italic = $style->getItalic(); - $color = $style->getColor(); - $size = $style->getSize(); - $fgColor = $style->getFgColor(); - $bgColor = $style->getBgColor(); - $strikethrough = $style->getStrikethrough(); - $underline = $style->getUnderline(); - $superscript = $style->getSuperScript(); - $subscript = $style->getSubScript(); - $hint = $style->getHint(); - - $xmlWriter->startElement('w:rPr'); - - // Font - if ($font != PhpWord::DEFAULT_FONT_NAME) { - $xmlWriter->startElement('w:rFonts'); - $xmlWriter->writeAttribute('w:ascii', $font); - $xmlWriter->writeAttribute('w:hAnsi', $font); - $xmlWriter->writeAttribute('w:eastAsia', $font); - $xmlWriter->writeAttribute('w:cs', $font); - //Font Content Type - if ($hint != PhpWord::DEFAULT_FONT_CONTENT_TYPE) { - $xmlWriter->writeAttribute('w:hint', $hint); - } - $xmlWriter->endElement(); - } - - - // Color - if ($color != PhpWord::DEFAULT_FONT_COLOR) { - $xmlWriter->startElement('w:color'); - $xmlWriter->writeAttribute('w:val', $color); - $xmlWriter->endElement(); - } - - // Size - if ($size != PhpWord::DEFAULT_FONT_SIZE) { - $xmlWriter->startElement('w:sz'); - $xmlWriter->writeAttribute('w:val', $size * 2); - $xmlWriter->endElement(); - $xmlWriter->startElement('w:szCs'); - $xmlWriter->writeAttribute('w:val', $size * 2); - $xmlWriter->endElement(); - } - - // Bold - if ($bold) { - $xmlWriter->writeElement('w:b', null); - } - - // Italic - if ($italic) { - $xmlWriter->writeElement('w:i', null); - $xmlWriter->writeElement('w:iCs', null); - } - - // Underline - if (!is_null($underline) && $underline != 'none') { - $xmlWriter->startElement('w:u'); - $xmlWriter->writeAttribute('w:val', $underline); - $xmlWriter->endElement(); - } - - // Strikethrough - if ($strikethrough) { - $xmlWriter->writeElement('w:strike', null); - } - - // Foreground-Color - if (!is_null($fgColor)) { - $xmlWriter->startElement('w:highlight'); - $xmlWriter->writeAttribute('w:val', $fgColor); - $xmlWriter->endElement(); - } - - // Background-Color - if (!is_null($bgColor)) { - $xmlWriter->startElement('w:shd'); - $xmlWriter->writeAttribute('w:val', "clear"); - $xmlWriter->writeAttribute('w:color', "auto"); - $xmlWriter->writeAttribute('w:fill', $bgColor); - $xmlWriter->endElement(); - } - - // Superscript/subscript - if ($superscript || $subscript) { - $xmlWriter->startElement('w:vertAlign'); - $xmlWriter->writeAttribute('w:val', $superscript ? 'superscript' : 'subscript'); - $xmlWriter->endElement(); - } - - $xmlWriter->endElement(); - } - - /** - * Write table style - * - * @param XMLWriter $xmlWriter - * @param TableStyle $style - * @param boolean $isFullStyle - */ - protected function writeTableStyle(XMLWriter $xmlWriter, TableStyle $style, $isFullStyle = true) - { - $bgColor = $style->getBgColor(); - $brdCol = $style->getBorderColor(); - $brdSz = $style->getBorderSize(); - $cellMargin = $style->getCellMargin(); - - // If any of the borders/margins is set, process them - $hasBorders = false; - for ($i = 0; $i < 6; $i++) { - if (!is_null($brdSz[$i])) { - $hasBorders = true; - break; - } - } - $hasMargins = false; - for ($i = 0; $i < 4; $i++) { - if (!is_null($cellMargin[$i])) { - $hasMargins = true; - break; - } - } - if ($hasMargins || $hasBorders) { - $xmlWriter->startElement('w:tblPr'); - if ($hasMargins) { - $xmlWriter->startElement('w:tblCellMar'); - $this->writeMarginBorder($xmlWriter, $cellMargin); - $xmlWriter->endElement(); // w:tblCellMar - } - if ($hasBorders) { - $xmlWriter->startElement('w:tblBorders'); - $this->writeMarginBorder($xmlWriter, $brdSz, $brdCol); - $xmlWriter->endElement(); // w:tblBorders - } - $xmlWriter->endElement(); // w:tblPr - } - // Only write background color and first row for full style - if ($isFullStyle) { - // Background color - if (!is_null($bgColor)) { - $xmlWriter->startElement('w:tcPr'); - $xmlWriter->startElement('w:shd'); - $xmlWriter->writeAttribute('w:val', 'clear'); - $xmlWriter->writeAttribute('w:color', 'auto'); - $xmlWriter->writeAttribute('w:fill', $bgColor); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } - // First Row - $firstRow = $style->getFirstRow(); - if (!is_null($firstRow)) { - $this->writeRowStyle($xmlWriter, 'firstRow', $firstRow); - } - } - } - - /** - * Write row style - * - * @param XMLWriter $xmlWriter - * @param string $type - * @param TableStyle $style - */ - protected function writeRowStyle(XMLWriter $xmlWriter, $type, TableStyle $style) - { - $bgColor = $style->getBgColor(); - - $xmlWriter->startElement('w:tblStylePr'); - $xmlWriter->writeAttribute('w:type', $type); - $xmlWriter->startElement('w:tcPr'); - if (!is_null($bgColor)) { - $xmlWriter->startElement('w:shd'); - $xmlWriter->writeAttribute('w:val', 'clear'); - $xmlWriter->writeAttribute('w:color', 'auto'); - $xmlWriter->writeAttribute('w:fill', $bgColor); - $xmlWriter->endElement(); // w:shd - } - - // Borders - $brdSz = $style->getBorderSize(); - $brdCol = $style->getBorderColor(); - $hasBorders = false; - for ($i = 0; $i < 6; $i++) { - if (!is_null($brdSz[$i])) { - $hasBorders = true; - break; - } - } - if ($hasBorders) { - $xmlWriter->startElement('w:tcBorders'); - $this->writeMarginBorder($xmlWriter, $brdSz, $brdCol); - $xmlWriter->endElement(); // w:tcBorders - } - - $xmlWriter->endElement(); // w:tcPr - $xmlWriter->endElement(); // w:tblStylePr - } - - /** - * Write footnote reference element - * - * @param XMLWriter $xmlWriter - * @param Cell $style - */ - protected function writeCellStyle(XMLWriter $xmlWriter, Cell $style) - { - $bgColor = $style->getBgColor(); - $valign = $style->getVAlign(); - $textDir = $style->getTextDirection(); - $brdSz = $style->getBorderSize(); - $brdCol = $style->getBorderColor(); - $hasBorders = false; - for ($i = 0; $i < 4; $i++) { - if (!is_null($brdSz[$i])) { - $hasBorders = true; - break; - } - } - - $styles = (!is_null($bgColor) || !is_null($valign) || !is_null($textDir) || $hasBorders) ? true : false; - - if ($styles) { - if (!is_null($textDir)) { - $xmlWriter->startElement('w:textDirection'); - $xmlWriter->writeAttribute('w:val', $textDir); - $xmlWriter->endElement(); - } - - if (!is_null($bgColor)) { - $xmlWriter->startElement('w:shd'); - $xmlWriter->writeAttribute('w:val', 'clear'); - $xmlWriter->writeAttribute('w:color', 'auto'); - $xmlWriter->writeAttribute('w:fill', $bgColor); - $xmlWriter->endElement(); - } - - if (!is_null($valign)) { - $xmlWriter->startElement('w:vAlign'); - $xmlWriter->writeAttribute('w:val', $valign); - $xmlWriter->endElement(); - } - - if ($hasBorders) { - $defaultColor = $style->getDefaultBorderColor(); - - $xmlWriter->startElement('w:tcBorders'); - $this->writeMarginBorder($xmlWriter, $brdSz, $brdCol, array('defaultColor' => $defaultColor)); - $xmlWriter->endElement(); - } - } - $gridSpan = $style->getGridSpan(); - if (!is_null($gridSpan)) { - $xmlWriter->startElement('w:gridSpan'); - $xmlWriter->writeAttribute('w:val', $gridSpan); - $xmlWriter->endElement(); - } - - $vMerge = $style->getVMerge(); - if (!is_null($vMerge)) { - $xmlWriter->startElement('w:vMerge'); - $xmlWriter->writeAttribute('w:val', $vMerge); - $xmlWriter->endElement(); - } - } - - /** - * Write inline paragraph style - * - * @param XMLWriter $xmlWriter - * @param Paragraph|string $styleParagraph - * @param boolean $withoutPPR - */ - protected function writeInlineParagraphStyle(XMLWriter $xmlWriter, $styleParagraph = null, $withoutPPR = false) - { - if ($styleParagraph instanceof Paragraph) { - $this->writeParagraphStyle($xmlWriter, $styleParagraph, $withoutPPR); - } else { - if (!is_null($styleParagraph)) { - if (!$withoutPPR) { - $xmlWriter->startElement('w:pPr'); - } - $xmlWriter->startElement('w:pStyle'); - $xmlWriter->writeAttribute('w:val', $styleParagraph); - $xmlWriter->endElement(); - if (!$withoutPPR) { - $xmlWriter->endElement(); - } - } - } - } - - /** - * Write inline font style - * - * @param XMLWriter $xmlWriter - * @param Font|string $styleFont - */ - protected function writeInlineFontStyle(XMLWriter $xmlWriter, $styleFont = null) - { - if ($styleFont instanceof Font) { - $this->writeFontStyle($xmlWriter, $styleFont); - } else { - if (!is_null($styleFont)) { - $xmlWriter->startElement('w:rPr'); - $xmlWriter->startElement('w:rStyle'); - $xmlWriter->writeAttribute('w:val', $styleFont); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } - } - } - - /** - * Write container elements - * - * @param XMLWriter $xmlWriter - * @param AbstractElement $container - */ - protected function writeContainerElements(XMLWriter $xmlWriter, AbstractElement $container) - { - // Check allowed elements - $elmCommon = array('Text', 'Link', 'TextBreak', 'Image', 'Object'); - $elmMainCell = array_merge($elmCommon, array('TextRun', 'ListItem', 'CheckBox')); - $allowedElements = array( - 'Section' => array_merge($elmMainCell, array('Table', 'Footnote', 'Title', 'PageBreak', 'TOC')), - 'Header' => array_merge($elmMainCell, array('Table', 'PreserveText')), - 'Footer' => array_merge($elmMainCell, array('Table', 'PreserveText')), - 'Cell' => array_merge($elmMainCell, array('PreserveText', 'Footnote', 'Endnote')), - 'TextRun' => array_merge($elmCommon, array('Footnote', 'Endnote')), - 'Footnote' => $elmCommon, - 'Endnote' => $elmCommon, - ); - $containerName = get_class($container); - $containerName = substr($containerName, strrpos($containerName, '\\') + 1); - if (array_key_exists($containerName, $allowedElements)) { - $containerElements = $allowedElements[$containerName]; - } else { - throw new Exception('Invalid container.'); - } - - // Loop through elements - $elements = $container->getElements(); - if (count($elements) > 0) { - foreach ($elements as $element) { - $elmName = get_class($element); - $elmName = substr($elmName, strrpos($elmName, '\\') + 1); - if (in_array($elmName, $containerElements)) { - $method = "write{$elmName}"; - // Image on Header could be watermark - if ($containerName == 'Header' && $elmName == 'Image') { - if ($element->getIsWatermark()) { - $method = "writeWatermark"; - } - } - switch ($containerName) { - case 'TextRun': - case 'Footnote': - case 'Endnote': - $this->$method($xmlWriter, $element, true); - break; - default: - $this->$method($xmlWriter, $element); - } - } - } - } else { - if ($containerName == 'Cell') { - $this->writeTextBreak($xmlWriter); - } - } - } - - /** - * Write margin or border - * - * @param XMLWriter $xmlWriter - * @param array $sizes - * @param array $colors - * @param array $attributes - */ - protected function writeMarginBorder(XMLWriter $xmlWriter, $sizes, $colors = array(), $attributes = array()) - { - $sides = array('top', 'left', 'right', 'bottom', 'insideH', 'insideV'); - $sizeCount = count($sizes) - 1; - for ($i = 0; $i < $sizeCount; $i++) { - if (!is_null($sizes[$i])) { - $xmlWriter->startElement('w:' . $sides[$i]); - if (!empty($colors)) { - if (is_null($colors[$i]) && !empty($attributes)) { - if (array_key_exists('defaultColor', $attributes)) { - $colors[$i] = $attributes['defaultColor']; - } - } - $xmlWriter->writeAttribute('w:val', 'single'); - $xmlWriter->writeAttribute('w:sz', $sizes[$i]); - $xmlWriter->writeAttribute('w:color', $colors[$i]); - if (!empty($attributes)) { - if (array_key_exists('space', $attributes)) { - $xmlWriter->writeAttribute('w:space', '24'); - } - } - } else { - $xmlWriter->writeAttribute('w:w', $sizes[$i]); - $xmlWriter->writeAttribute('w:type', 'dxa'); - } - $xmlWriter->endElement(); - } - } - } -} diff --git a/src/PhpWord/Writer/Word2007/ContentTypes.php b/src/PhpWord/Writer/Word2007/ContentTypes.php deleted file mode 100755 index a27ef43c..00000000 --- a/src/PhpWord/Writer/Word2007/ContentTypes.php +++ /dev/null @@ -1,82 +0,0 @@ - $OpenXMLPrefix . 'package.core-properties+xml', - '/docProps/app.xml' => $OpenXMLPrefix . 'officedocument.extended-properties+xml', - '/word/document.xml' => $WordMLPrefix . 'document.main+xml', - '/word/styles.xml' => $WordMLPrefix . 'styles+xml', - '/word/numbering.xml' => $WordMLPrefix . 'numbering+xml', - '/word/settings.xml' => $WordMLPrefix . 'settings+xml', - '/word/theme/theme1.xml' => $OpenXMLPrefix . 'officedocument.theme+xml', - '/word/webSettings.xml' => $WordMLPrefix . 'webSettings+xml', - '/word/fontTable.xml' => $WordMLPrefix . 'fontTable+xml', - ); - - $defaults = $contentTypes['default']; - if (!empty($contentTypes['override'])) { - foreach ($contentTypes['override'] as $key => $val) { - $overrides[$key] = $WordMLPrefix . $val . '+xml'; - } - } - - $xmlWriter = $this->getXmlWriter(); - $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); - $xmlWriter->startElement('Types'); - $xmlWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/content-types'); - $this->writeContentType($xmlWriter, $defaults, true); - $this->writeContentType($xmlWriter, $overrides, false); - $xmlWriter->endElement(); - - return $xmlWriter->getData(); - } - - /** - * Write content types element - * - * @param XMLWriter $xmlWriter XML Writer - * @param array $parts - * @param boolean $isDefault - * @throws Exception - */ - private function writeContentType(XMLWriter $xmlWriter, $parts, $isDefault) - { - foreach ($parts as $partName => $contentType) { - if ($partName != '' && $contentType != '') { - $partType = $isDefault ? 'Default' : 'Override'; - $partAttribute = $isDefault ? 'Extension' : 'PartName'; - $xmlWriter->startElement($partType); - $xmlWriter->writeAttribute($partAttribute, $partName); - $xmlWriter->writeAttribute('ContentType', $contentType); - $xmlWriter->endElement(); - } else { - throw new Exception("Invalid parameters passed."); - } - } - } -} diff --git a/src/PhpWord/Writer/Word2007/DocProps.php b/src/PhpWord/Writer/Word2007/DocProps.php deleted file mode 100644 index 5818d511..00000000 --- a/src/PhpWord/Writer/Word2007/DocProps.php +++ /dev/null @@ -1,172 +0,0 @@ -getXmlWriter(); - - // XML header - $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); - - // Properties - $xmlWriter->startElement('Properties'); - $xmlWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties'); - $xmlWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'); - - // Application - $xmlWriter->writeElement('Application', 'Microsoft Office Word'); - - // ScaleCrop - $xmlWriter->writeElement('ScaleCrop', 'false'); - - // HeadingPairs - $xmlWriter->startElement('HeadingPairs'); - - // Vector - $xmlWriter->startElement('vt:vector'); - $xmlWriter->writeAttribute('size', '4'); - $xmlWriter->writeAttribute('baseType', 'variant'); - - // Variant - $xmlWriter->startElement('vt:variant'); - $xmlWriter->writeElement('vt:lpstr', 'Theme'); - $xmlWriter->endElement(); - - // Variant - $xmlWriter->startElement('vt:variant'); - $xmlWriter->writeElement('vt:i4', '1'); - $xmlWriter->endElement(); - - // Variant - $xmlWriter->startElement('vt:variant'); - $xmlWriter->writeElement('vt:lpstr', 'Slide Titles'); - $xmlWriter->endElement(); - - // Variant - $xmlWriter->startElement('vt:variant'); - $xmlWriter->writeElement('vt:i4', '1'); - $xmlWriter->endElement(); - - $xmlWriter->endElement(); - - $xmlWriter->endElement(); - - // TitlesOfParts - $xmlWriter->startElement('TitlesOfParts'); - - // Vector - $xmlWriter->startElement('vt:vector'); - $xmlWriter->writeAttribute('size', '1'); - $xmlWriter->writeAttribute('baseType', 'lpstr'); - - $xmlWriter->writeElement('vt:lpstr', 'Office Theme'); - - $xmlWriter->endElement(); - - $xmlWriter->endElement(); - - // Company - $xmlWriter->writeElement('Company', $phpWord->getDocumentProperties()->getCompany()); - - // LinksUpToDate - $xmlWriter->writeElement('LinksUpToDate', 'false'); - - // SharedDoc - $xmlWriter->writeElement('SharedDoc', 'false'); - - // HyperlinksChanged - $xmlWriter->writeElement('HyperlinksChanged', 'false'); - - // AppVersion - $xmlWriter->writeElement('AppVersion', '12.0000'); - - $xmlWriter->endElement(); - - // Return - return $xmlWriter->getData(); - } - - - /** - * Write docProps/core.xml - * - * @param PhpWord $phpWord - */ - public function writeDocPropsCore(PhpWord $phpWord) - { - // Create XML writer - $xmlWriter = $this->getXmlWriter(); - - // XML header - $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); - - // cp:coreProperties - $xmlWriter->startElement('cp:coreProperties'); - $xmlWriter->writeAttribute('xmlns:cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties'); - $xmlWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); - $xmlWriter->writeAttribute('xmlns:dcterms', 'http://purl.org/dc/terms/'); - $xmlWriter->writeAttribute('xmlns:dcmitype', 'http://purl.org/dc/dcmitype/'); - $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); - - // dc:creator - $xmlWriter->writeElement('dc:creator', $phpWord->getDocumentProperties()->getCreator()); - - // cp:lastModifiedBy - $xmlWriter->writeElement('cp:lastModifiedBy', $phpWord->getDocumentProperties()->getLastModifiedBy()); - - // dcterms:created - $xmlWriter->startElement('dcterms:created'); - $xmlWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); - $xmlWriter->writeRaw(date(DATE_W3C, $phpWord->getDocumentProperties()->getCreated())); - $xmlWriter->endElement(); - - // dcterms:modified - $xmlWriter->startElement('dcterms:modified'); - $xmlWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); - $xmlWriter->writeRaw(date(DATE_W3C, $phpWord->getDocumentProperties()->getModified())); - $xmlWriter->endElement(); - - // dc:title - $xmlWriter->writeElement('dc:title', $phpWord->getDocumentProperties()->getTitle()); - - // dc:description - $xmlWriter->writeElement('dc:description', $phpWord->getDocumentProperties()->getDescription()); - - // dc:subject - $xmlWriter->writeElement('dc:subject', $phpWord->getDocumentProperties()->getSubject()); - - // cp:keywords - $xmlWriter->writeElement('cp:keywords', $phpWord->getDocumentProperties()->getKeywords()); - - // cp:category - $xmlWriter->writeElement('cp:category', $phpWord->getDocumentProperties()->getCategory()); - - $xmlWriter->endElement(); - - // Return - return $xmlWriter->getData(); - } -} diff --git a/src/PhpWord/Writer/Word2007/Document.php b/src/PhpWord/Writer/Word2007/Document.php deleted file mode 100644 index 0637c689..00000000 --- a/src/PhpWord/Writer/Word2007/Document.php +++ /dev/null @@ -1,360 +0,0 @@ -getXmlWriter(); - - // XML header - $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); - - // w:document - $xmlWriter->startElement('w:document'); - - $xmlWriter->writeAttribute('xmlns:ve', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); - $xmlWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); - $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - $xmlWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math'); - $xmlWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); - $xmlWriter->writeAttribute('xmlns:wp', 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'); - $xmlWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word'); - $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); - $xmlWriter->writeAttribute('xmlns:wne', 'http://schemas.microsoft.com/office/word/2006/wordml'); - - $xmlWriter->startElement('w:body'); - - $sections = $phpWord->getSections(); - $countSections = count($sections); - $pSection = 0; - - if ($countSections > 0) { - foreach ($sections as $section) { - $pSection++; - - $this->writeContainerElements($xmlWriter, $section); - - if ($pSection == $countSections) { - $this->writeEndSection($xmlWriter, $section); - } else { - $this->writeSection($xmlWriter, $section); - } - } - } - - $xmlWriter->endElement(); // End w:body - $xmlWriter->endElement(); // End w:document - - // Return - return $xmlWriter->getData(); - } - - /** - * Write begin section - * - * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter - * @param \PhpOffice\PhpWord\Element\Section $section - */ - private function writeSection(XMLWriter $xmlWriter, Section $section) - { - $xmlWriter->startElement('w:p'); - $xmlWriter->startElement('w:pPr'); - $this->writeEndSection($xmlWriter, $section); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } - - /** - * Write end section - * - * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter - * @param \PhpOffice\PhpWord\Element\Section $section - */ - private function writeEndSection(XMLWriter $xmlWriter, Section $section) - { - $settings = $section->getSettings(); - $headers = $section->getHeaders(); - $footers = $section->getFooters(); - $pgSzW = $settings->getPageSizeW(); - $pgSzH = $settings->getPageSizeH(); - $orientation = $settings->getOrientation(); - - $marginTop = $settings->getMarginTop(); - $marginLeft = $settings->getMarginLeft(); - $marginRight = $settings->getMarginRight(); - $marginBottom = $settings->getMarginBottom(); - - $headerHeight = $settings->getHeaderHeight(); - $footerHeight = $settings->getFooterHeight(); - - $borders = $settings->getBorderSize(); - - $colsNum = $settings->getColsNum(); - $colsSpace = $settings->getColsSpace(); - $breakType = $settings->getBreakType(); - - $xmlWriter->startElement('w:sectPr'); - - // Section break - if (!is_null($breakType)) { - $xmlWriter->startElement('w:type'); - $xmlWriter->writeAttribute('w:val', $breakType); - $xmlWriter->endElement(); - } - - // Header reference - foreach ($headers as &$header) { - $rId = $header->getRelationId(); - $xmlWriter->startElement('w:headerReference'); - $xmlWriter->writeAttribute('w:type', $header->getType()); - $xmlWriter->writeAttribute('r:id', 'rId' . $rId); - $xmlWriter->endElement(); - } - // Footer reference - foreach ($footers as &$footer) { - $rId = $footer->getRelationId(); - $xmlWriter->startElement('w:footerReference'); - $xmlWriter->writeAttribute('w:type', $footer->getType()); - $xmlWriter->writeAttribute('r:id', 'rId' . $rId); - $xmlWriter->endElement(); - } - // Different first page - if ($section->hasDifferentFirstPage()) { - $xmlWriter->startElement('w:titlePg'); - $xmlWriter->endElement(); - } - - // Page size & orientation - $xmlWriter->startElement('w:pgSz'); - $xmlWriter->writeAttribute('w:w', $pgSzW); - $xmlWriter->writeAttribute('w:h', $pgSzH); - if (!is_null($orientation) && strtolower($orientation) != 'portrait') { - $xmlWriter->writeAttribute('w:orient', $orientation); - } - $xmlWriter->endElement(); // w:pgSz - - // Margins - $xmlWriter->startElement('w:pgMar'); - $xmlWriter->writeAttribute('w:top', $marginTop); - $xmlWriter->writeAttribute('w:right', $marginRight); - $xmlWriter->writeAttribute('w:bottom', $marginBottom); - $xmlWriter->writeAttribute('w:left', $marginLeft); - $xmlWriter->writeAttribute('w:header', $headerHeight); - $xmlWriter->writeAttribute('w:footer', $footerHeight); - $xmlWriter->writeAttribute('w:gutter', '0'); - $xmlWriter->endElement(); - - // Borders - $hasBorders = false; - for ($i = 0; $i < 4; $i++) { - if (!is_null($borders[$i])) { - $hasBorders = true; - break; - } - } - if ($hasBorders) { - $borderColor = $settings->getBorderColor(); - $xmlWriter->startElement('w:pgBorders'); - $xmlWriter->writeAttribute('w:offsetFrom', 'page'); - $this->writeMarginBorder($xmlWriter, $borders, $borderColor, array('space' => '24')); - $xmlWriter->endElement(); - } - - // Page numbering - if (null !== $settings->getPageNumberingStart()) { - $xmlWriter->startElement('w:pgNumType'); - $xmlWriter->writeAttribute('w:start', $section->getSettings()->getPageNumberingStart()); - $xmlWriter->endElement(); - } - - // Columns - $xmlWriter->startElement('w:cols'); - $xmlWriter->writeAttribute('w:num', $colsNum); - $xmlWriter->writeAttribute('w:space', $colsSpace); - $xmlWriter->endElement(); - - $xmlWriter->endElement(); - } - - /** - * Write page break element - * - * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter - * @param \PhpOffice\PhpWord\Element\PageBreak $pagebreak - */ - protected function writePageBreak(XMLWriter $xmlWriter, PageBreak $pagebreak) - { - $xmlWriter->startElement('w:p'); - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:br'); - $xmlWriter->writeAttribute('w:type', 'page'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } - - /** - * Write TOC element - * - * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter - * @param \PhpOffice\PhpWord\TOC $toc - */ - protected function writeTOC(XMLWriter $xmlWriter, TOC $toc) - { - $titles = $toc->getTitles(); - $styleFont = $toc->getStyleFont(); - - $styleTOC = $toc->getStyleTOC(); - $fIndent = $styleTOC->getIndent(); - $tabLeader = $styleTOC->getTabLeader(); - $tabPos = $styleTOC->getTabPos(); - - $maxDepth = $toc->getMaxDepth(); - $minDepth = $toc->getMinDepth(); - - $isObject = ($styleFont instanceof Font) ? true : false; - - for ($i = 0; $i < count($titles); $i++) { - $title = $titles[$i]; - $indent = ($title['depth'] - 1) * $fIndent; - - $xmlWriter->startElement('w:p'); - - $xmlWriter->startElement('w:pPr'); - - if ($isObject && !is_null($styleFont->getParagraphStyle())) { - $this->writeParagraphStyle($xmlWriter, $styleFont->getParagraphStyle()); - } - - if ($indent > 0) { - $xmlWriter->startElement('w:ind'); - $xmlWriter->writeAttribute('w:left', $indent); - $xmlWriter->endElement(); - } - - if (!empty($styleFont) && !$isObject) { - $xmlWriter->startElement('w:pPr'); - $xmlWriter->startElement('w:pStyle'); - $xmlWriter->writeAttribute('w:val', $styleFont); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } - - $xmlWriter->startElement('w:tabs'); - $xmlWriter->startElement('w:tab'); - $xmlWriter->writeAttribute('w:val', 'right'); - if (!empty($tabLeader)) { - $xmlWriter->writeAttribute('w:leader', $tabLeader); - } - $xmlWriter->writeAttribute('w:pos', $tabPos); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - $xmlWriter->endElement(); // w:pPr - - - if ($i == 0) { - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:fldChar'); - $xmlWriter->writeAttribute('w:fldCharType', 'begin'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:instrText'); - $xmlWriter->writeAttribute('xml:space', 'preserve'); - $xmlWriter->writeRaw('TOC \o "' . $minDepth . '-' . $maxDepth . '" \h \z \u'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:fldChar'); - $xmlWriter->writeAttribute('w:fldCharType', 'separate'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } - - $xmlWriter->startElement('w:hyperlink'); - $xmlWriter->writeAttribute('w:anchor', $title['anchor']); - $xmlWriter->writeAttribute('w:history', '1'); - - $xmlWriter->startElement('w:r'); - - if ($isObject) { - $this->writeFontStyle($xmlWriter, $styleFont); - } - - $xmlWriter->startElement('w:t'); - $xmlWriter->writeRaw($title['text']); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - $xmlWriter->startElement('w:r'); - $xmlWriter->writeElement('w:tab', null); - $xmlWriter->endElement(); - - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:fldChar'); - $xmlWriter->writeAttribute('w:fldCharType', 'begin'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:instrText'); - $xmlWriter->writeAttribute('xml:space', 'preserve'); - $xmlWriter->writeRaw('PAGEREF ' . $title['anchor'] . ' \h'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:fldChar'); - $xmlWriter->writeAttribute('w:fldCharType', 'end'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - - $xmlWriter->endElement(); // w:hyperlink - - $xmlWriter->endElement(); // w:p - } - - $xmlWriter->startElement('w:p'); - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:fldChar'); - $xmlWriter->writeAttribute('w:fldCharType', 'end'); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - $xmlWriter->endElement(); - } -} diff --git a/src/PhpWord/Writer/Word2007/Element/AbstractElement.php b/src/PhpWord/Writer/Word2007/Element/AbstractElement.php new file mode 100644 index 00000000..2c200f81 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/AbstractElement.php @@ -0,0 +1,172 @@ +xmlWriter = $xmlWriter; + $this->element = $element; + $this->withoutP = $withoutP; + } + + /** + * Get XML Writer + * + * @return \PhpOffice\PhpWord\Shared\XMLWriter + */ + protected function getXmlWriter() + { + return $this->xmlWriter; + } + + /** + * Get element + * + * @return \PhpOffice\PhpWord\Element\AbstractElement + */ + protected function getElement() + { + return $this->element; + } + + /** + * Start w:p DOM element. + * + * @uses \PhpOffice\PhpWord\Writer\Word2007\Element\PageBreak::write() + * @return void + */ + protected function startElementP() + { + if (!$this->withoutP) { + $this->xmlWriter->startElement('w:p'); + // Paragraph style + if (method_exists($this->element, 'getParagraphStyle')) { + $this->writeParagraphStyle(); + } + } + } + + /** + * End w:p DOM element. + * + * @return void + */ + protected function endElementP() + { + if (!$this->withoutP) { + $this->xmlWriter->endElement(); // w:p + } + } + + /** + * Write ending. + * + * @return void + */ + protected function writeParagraphStyle() + { + $this->writeTextStyle('Paragraph'); + } + + /** + * Write ending. + * + * @return void + */ + protected function writeFontStyle() + { + $this->writeTextStyle('Font'); + } + + + /** + * Write text style. + * + * @param string $styleType Font|Paragraph + * @return void + */ + private function writeTextStyle($styleType) + { + $method = "get{$styleType}Style"; + $class = "PhpOffice\\PhpWord\\Writer\\Word2007\\Style\\{$styleType}"; + $styleObject = $this->element->$method(); + + $styleWriter = new $class($this->xmlWriter, $styleObject); + if (method_exists($styleWriter, 'setIsInline')) { + $styleWriter->setIsInline(true); + } + + /** @var \PhpOffice\PhpWord\Writer\Word2007\Style\AbstractStyle $styleWriter */ + $styleWriter->write(); + } + + /** + * Convert text to valid format + * + * @param string $text + * @return string + */ + protected function getText($text) + { + return String::controlCharacterPHP2OOXML(htmlspecialchars($text)); + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/Bookmark.php b/src/PhpWord/Writer/Word2007/Element/Bookmark.php new file mode 100644 index 00000000..df5a104a --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/Bookmark.php @@ -0,0 +1,49 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Bookmark) { + return; + } + + $rId = $element->getRelationId(); + + $xmlWriter->startElement('w:bookmarkStart'); + $xmlWriter->writeAttribute('w:id', $rId); + $xmlWriter->writeAttribute('w:name', $element->getName()); + $xmlWriter->endElement(); + + $xmlWriter->startElement('w:bookmarkEnd'); + $xmlWriter->writeAttribute('w:id', $rId); + $xmlWriter->endElement(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/Chart.php b/src/PhpWord/Writer/Word2007/Element/Chart.php new file mode 100644 index 00000000..ccd8cd77 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/Chart.php @@ -0,0 +1,77 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof ChartElement) { + return; + } + + $rId = $element->getRelationId(); + $style = $element->getStyle(); + + if (!$this->withoutP) { + $xmlWriter->startElement('w:p'); + } + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:drawing'); + $xmlWriter->startElement('wp:inline'); + + // EMU + $xmlWriter->writeElementBlock('wp:extent', array('cx' => $style->getWidth(), 'cy' => $style->getHeight())); + $xmlWriter->writeElementBlock('wp:docPr', array('id' => $rId, 'name' => "Chart{$rId}")); + + $xmlWriter->startElement('a:graphic'); + $xmlWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main'); + $xmlWriter->startElement('a:graphicData'); + $xmlWriter->writeAttribute('uri', 'http://schemas.openxmlformats.org/drawingml/2006/chart'); + + $xmlWriter->startElement('c:chart'); + $xmlWriter->writeAttribute('r:id', "rId{$rId}"); + $xmlWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart'); + $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $xmlWriter->endElement(); // c:chart + + $xmlWriter->endElement(); // a:graphicData + $xmlWriter->endElement(); // a:graphic + + $xmlWriter->endElement(); // wp:inline + $xmlWriter->endElement(); // w:drawing + $xmlWriter->endElement(); // w:r + + $this->endElementP(); // w:p + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/CheckBox.php b/src/PhpWord/Writer/Word2007/Element/CheckBox.php new file mode 100644 index 00000000..9d060726 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/CheckBox.php @@ -0,0 +1,92 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\CheckBox) { + return; + } + + $this->startElementP(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'begin'); + $xmlWriter->startElement('w:ffData'); + $xmlWriter->startElement('w:name'); + $xmlWriter->writeAttribute('w:val', $this->getText($element->getName())); + $xmlWriter->endElement(); //w:name + $xmlWriter->writeAttribute('w:enabled', ''); + $xmlWriter->startElement('w:calcOnExit'); + $xmlWriter->writeAttribute('w:val', '0'); + $xmlWriter->endElement(); //w:calcOnExit + $xmlWriter->startElement('w:checkBox'); + $xmlWriter->writeAttribute('w:sizeAuto', ''); + $xmlWriter->startElement('w:default'); + $xmlWriter->writeAttribute('w:val', 0); + $xmlWriter->endElement(); //w:default + $xmlWriter->endElement(); //w:checkBox + $xmlWriter->endElement(); // w:ffData + $xmlWriter->endElement(); // w:fldChar + $xmlWriter->endElement(); // w:r + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:instrText'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw(' FORMCHECKBOX '); + $xmlWriter->endElement();// w:instrText + $xmlWriter->endElement(); // w:r + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'seperate'); + $xmlWriter->endElement();// w:fldChar + $xmlWriter->endElement(); // w:r + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'end'); + $xmlWriter->endElement();// w:fldChar + $xmlWriter->endElement(); // w:r + + $xmlWriter->startElement('w:r'); + + $this->writeFontStyle(); + + $xmlWriter->startElement('w:t'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw($this->getText($element->getText())); + $xmlWriter->endElement(); // w:t + $xmlWriter->endElement(); // w:r + + $this->endElementP(); // w:p + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/Container.php b/src/PhpWord/Writer/Word2007/Element/Container.php new file mode 100644 index 00000000..771fe5c3 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/Container.php @@ -0,0 +1,94 @@ +getElement(); + if (!$container instanceof ContainerElement) { + return; + } + $containerClass = substr(get_class($container), strrpos(get_class($container), '\\') + 1); + $withoutP = in_array($containerClass, array('TextRun', 'Footnote', 'Endnote', 'ListItemRun')) ? true : false; + $xmlWriter = $this->getXmlWriter(); + + // Loop through elements + $elements = $container->getElements(); + $elementClass = ''; + foreach ($elements as $element) { + $elementClass = $this->writeElement($xmlWriter, $element, $withoutP); + } + + // Special case for Cell: They have to contain a w:p element at the end. + // The $elementClass contains the last element name. If it's empty string + // or Table, the last element is not w:p + $writeLastTextBreak = ($containerClass == 'Cell') && ($elementClass == '' || $elementClass == 'Table'); + if ($writeLastTextBreak) { + $writerClass = $this->namespace . '\\TextBreak'; + /** @var \PhpOffice\PhpWord\Writer\Word2007\Element\AbstractElement $writer Type hint */ + $writer = new $writerClass($xmlWriter, new TextBreakElement(), $withoutP); + $writer->write(); + } + } + + /** + * Write individual element + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\AbstractElement $element + * @param bool $withoutP + * @return string + */ + private function writeElement(XMLWriter $xmlWriter, Element $element, $withoutP) + { + $elementClass = substr(get_class($element), strrpos(get_class($element), '\\') + 1); + $writerClass = $this->namespace . '\\' . $elementClass; + + if (class_exists($writerClass)) { + /** @var \PhpOffice\PhpWord\Writer\Word2007\Element\AbstractElement $writer Type hint */ + $writer = new $writerClass($xmlWriter, $element, $withoutP); + $writer->write(); + } + + return $elementClass; + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/Endnote.php b/src/PhpWord/Writer/Word2007/Element/Endnote.php new file mode 100644 index 00000000..f627c13c --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/Endnote.php @@ -0,0 +1,33 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Field) { + return; + } + + $instruction = ' ' . $element->getType() . ' '; + $properties = $element->getProperties(); + foreach ($properties as $propkey => $propval) { + switch ($propkey) { + case 'format': + case 'numformat': + $instruction .= '\* ' . $propval . ' '; + break; + case 'dateformat': + $instruction .= '\@ "' . $propval . '" '; + break; + } + } + + $options = $element->getOptions(); + foreach ($options as $option) { + switch ($option) { + case 'PreserveFormat': + $instruction .= '\* MERGEFORMAT '; + break; + case 'LunarCalendar': + $instruction .= '\h '; + break; + case 'SakaEraCalendar': + $instruction .= '\s '; + break; + case 'LastUsedFormat': + $instruction .= '\l '; + break; + } + } + + $this->startElementP(); + + $xmlWriter->startElement('w:fldSimple'); + $xmlWriter->writeAttribute('w:instr', $instruction); + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:rPr'); + $xmlWriter->startElement('w:noProof'); + $xmlWriter->endElement(); // w:noProof + $xmlWriter->endElement(); // w:rPr + + $xmlWriter->startElement('w:t'); + $xmlWriter->writeRaw('1'); + $xmlWriter->endElement(); // w:t + $xmlWriter->endElement(); // w:r + $xmlWriter->endElement(); // w:fldSimple + + $this->endElementP(); // w:p + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/Footnote.php b/src/PhpWord/Writer/Word2007/Element/Footnote.php new file mode 100644 index 00000000..5640a90d --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/Footnote.php @@ -0,0 +1,62 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Footnote) { + return; + } + + $this->startElementP(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:rPr'); + $xmlWriter->startElement('w:rStyle'); + $xmlWriter->writeAttribute('w:val', ucfirst($this->referenceType)); + $xmlWriter->endElement(); // w:rStyle + $xmlWriter->endElement(); // w:rPr + $xmlWriter->startElement("w:{$this->referenceType}"); + $xmlWriter->writeAttribute('w:id', $element->getRelationId()); + $xmlWriter->endElement(); // w:$referenceType + $xmlWriter->endElement(); // w:r + + $this->endElementP(); // w:p + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/FormField.php b/src/PhpWord/Writer/Word2007/Element/FormField.php new file mode 100644 index 00000000..432dc9c2 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/FormField.php @@ -0,0 +1,172 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof FormFieldElement) { + return; + } + + $type = $element->getType(); + $instructions = array('textinput' => 'FORMTEXT', 'checkbox' => 'FORMCHECKBOX', 'dropdown' => 'FORMDROPDOWN'); + $instruction = $instructions[$type]; + $writeFormField = "write{$type}"; + $name = $element->getName(); + if ($name === null) { + $name = $type . $element->getElementId(); + } + $value = $element->getValue(); + if ($value === null) { + $value = str_repeat(' ', self::FILLER_LENGTH); + } + + $this->startElementP(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'begin'); + $xmlWriter->startElement('w:ffData'); + $xmlWriter->writeElementBlock('w:enabled', 'w:val', 1); + $xmlWriter->writeElementBlock('w:name', 'w:val', $name); + $xmlWriter->writeElementBlock('w:calcOnExit', 'w:val', 0); + $this->$writeFormField($xmlWriter, $element); + $xmlWriter->endElement(); // w:ffData + $xmlWriter->endElement(); // w:fldChar + $xmlWriter->endElement(); // w:r + + $xmlWriter->startElement('w:r'); + $this->writeFontStyle(); + $xmlWriter->startElement('w:instrText'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw("{$instruction}"); + $xmlWriter->endElement();// w:instrText + $xmlWriter->endElement(); // w:r + + $xmlWriter->startElement('w:r'); + $this->writeFontStyle(); + $xmlWriter->writeElementBlock('w:fldChar', 'w:fldCharType', 'separate'); + $xmlWriter->endElement(); // w:r + + $xmlWriter->startElement('w:r'); + $this->writeFontStyle(); + $xmlWriter->startElement('w:t'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw($value); + $xmlWriter->endElement(); // w:t + $xmlWriter->endElement(); // w:r + + $xmlWriter->startElement('w:r'); + $this->writeFontStyle(); + $xmlWriter->writeElementBlock('w:fldChar', 'w:fldCharType', 'end'); + $xmlWriter->endElement(); // w:r + + $this->endElementP(); // w:p + } + + /** + * Write textinput. + * + * @link http://www.datypic.com/sc/ooxml/t-w_CT_FFTextInput.html + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\FormField $element + * @return void + */ + private function writeTextInput(XMLWriter $xmlWriter, FormFieldElement $element) + { + $default = $element->getDefault(); + + $xmlWriter->startElement('w:textInput'); + $xmlWriter->writeElementBlock('w:default', 'w:val', $default); + $xmlWriter->endElement(); + } + + /** + * Write checkbox. + * + * @link http://www.datypic.com/sc/ooxml/t-w_CT_FFCheckBox.html + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\FormField $element + * @return void + */ + private function writeCheckBox(XMLWriter $xmlWriter, FormFieldElement $element) + { + $default = $element->getDefault() ? 1 : 0; + $value = $element->getValue(); + if ($value == null) { + $value = $default; + } + $value = $value ? 1 : 0; + + $xmlWriter->startElement('w:checkBox'); + $xmlWriter->writeElementBlock('w:sizeAuto', 'w:val', ''); + $xmlWriter->writeElementBlock('w:default', 'w:val', $default); + $xmlWriter->writeElementBlock('w:checked', 'w:val', $value); + $xmlWriter->endElement(); + } + + /** + * Write dropdown. + * + * @link http://www.datypic.com/sc/ooxml/t-w_CT_FFDDList.html + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\FormField $element + * @return void + */ + private function writeDropDown(XMLWriter $xmlWriter, FormFieldElement $element) + { + $default = $element->getDefault(); + $value = $element->getValue(); + if ($value == null) { + $value = $default; + } + $entries = $element->getEntries(); + + $xmlWriter->startElement('w:ddList'); + $xmlWriter->writeElementBlock('w:result', 'w:val', $value); + $xmlWriter->writeElementBlock('w:default', 'w:val', $default); + foreach ($entries as $entry) { + $xmlWriter->writeElementBlock('w:listEntry', 'w:val', $entry); + } + $xmlWriter->endElement(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/Image.php b/src/PhpWord/Writer/Word2007/Element/Image.php new file mode 100644 index 00000000..73988423 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/Image.php @@ -0,0 +1,115 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof ImageElement) { + return; + } + + if ($element->isWatermark()) { + $this->writeWatermark($xmlWriter, $element); + } else { + $this->writeImage($xmlWriter, $element); + } + } + + /** + * Write image element. + * + * @return void + */ + private function writeImage(XMLWriter $xmlWriter, ImageElement $element) + { + $rId = $element->getRelationId() + ($element->isInSection() ? 6 : 0); + $style = $element->getStyle(); + $styleWriter = new ImageStyleWriter($xmlWriter, $style); + + if (!$this->withoutP) { + $xmlWriter->startElement('w:p'); + $styleWriter->writeAlignment(); + } + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:pict'); + $xmlWriter->startElement('v:shape'); + $xmlWriter->writeAttribute('type', '#_x0000_t75'); + + $styleWriter->write(); + + $xmlWriter->startElement('v:imagedata'); + $xmlWriter->writeAttribute('r:id', 'rId' . $rId); + $xmlWriter->writeAttribute('o:title', ''); + $xmlWriter->endElement(); // v:imagedata + + $xmlWriter->endElement(); // v:shape + $xmlWriter->endElement(); // w:pict + $xmlWriter->endElement(); // w:r + + $this->endElementP(); + } + + /** + * Write watermark element. + * + * @return void + */ + private function writeWatermark(XMLWriter $xmlWriter, ImageElement $element) + { + $rId = $element->getRelationId(); + $style = $element->getStyle(); + $style->setPositioning('absolute'); + $styleWriter = new ImageStyleWriter($xmlWriter, $style); + + $xmlWriter->startElement('w:p'); + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:pict'); + $xmlWriter->startElement('v:shape'); + $xmlWriter->writeAttribute('type', '#_x0000_t75'); + + $styleWriter->write(); + + $xmlWriter->startElement('v:imagedata'); + $xmlWriter->writeAttribute('r:id', 'rId' . $rId); + $xmlWriter->writeAttribute('o:title', ''); + $xmlWriter->endElement(); // v:imagedata + $xmlWriter->endElement(); // v:shape + $xmlWriter->endElement(); // w:pict + $xmlWriter->endElement(); // w:r + $xmlWriter->endElement(); // w:p + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/Line.php b/src/PhpWord/Writer/Word2007/Element/Line.php new file mode 100644 index 00000000..a6c7c240 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/Line.php @@ -0,0 +1,90 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof LineElement) { + return; + } + + $style = $element->getStyle(); + $styleWriter = new LineStyleWriter($xmlWriter, $style); + + $elementId = $element->getElementIndex(); + + if (!$this->withoutP) { + $xmlWriter->startElement('w:p'); + $styleWriter->writeAlignment(); + } + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:pict'); + + // Shapetype could be defined for each line separately, but then a unique id would be necessary + if ($elementId == 1) { + $xmlWriter->startElement('v:shapetype'); + $xmlWriter->writeAttribute('id', '_x0000_t32'); + $xmlWriter->writeAttribute('coordsize', '21600,21600'); + $xmlWriter->writeAttribute('o:spt', '32'); + $xmlWriter->writeAttribute('o:oned', 't'); + $xmlWriter->writeAttribute('path', 'm,l21600,21600e'); + $xmlWriter->writeAttribute('filled', 'f'); + $xmlWriter->startElement('v:path'); + $xmlWriter->writeAttribute('arrowok', 't'); + $xmlWriter->writeAttribute('fillok', 'f'); + $xmlWriter->writeAttribute('o:connecttype', 'none'); + $xmlWriter->endElement(); // v:path + $xmlWriter->startElement('o:lock'); + $xmlWriter->writeAttribute('v:ext', 'edit'); + $xmlWriter->writeAttribute('shapetype', 't'); + $xmlWriter->endElement(); // o:lock + $xmlWriter->endElement(); // v:shapetype + } + + $xmlWriter->startElement('v:shape'); + $xmlWriter->writeAttribute('id', sprintf('_x0000_s1%1$03d', $elementId)); + $xmlWriter->writeAttribute('type', '#_x0000_t32'); //type should correspond to shapetype id + + $styleWriter->write(); + $styleWriter->writeStroke(); + + $xmlWriter->endElement(); // v:shape + + $xmlWriter->endElement(); // w:pict + $xmlWriter->endElement(); // w:r + + $this->endElementP(); // w:p + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/Link.php b/src/PhpWord/Writer/Word2007/Element/Link.php new file mode 100644 index 00000000..2cb8407f --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/Link.php @@ -0,0 +1,64 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Link) { + return; + } + + $rId = $element->getRelationId() + ($element->isInSection() ? 6 : 0); + + $this->startElementP(); + + $xmlWriter->startElement('w:hyperlink'); + if ($element->isInternal()) { + $xmlWriter->writeAttribute('w:anchor', $element->getSource()); + } else { + $xmlWriter->writeAttribute('r:id', 'rId' . $rId); + } + $xmlWriter->writeAttribute('w:history', '1'); + $xmlWriter->startElement('w:r'); + + $this->writeFontStyle(); + + $xmlWriter->startElement('w:t'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw($element->getText()); + $xmlWriter->endElement(); // w:t + $xmlWriter->endElement(); // w:r + $xmlWriter->endElement(); // w:hyperlink + + $this->endElementP(); // w:p + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/ListItem.php b/src/PhpWord/Writer/Word2007/Element/ListItem.php new file mode 100644 index 00000000..0f559a4e --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/ListItem.php @@ -0,0 +1,69 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\ListItem) { + return; + } + + $textObject = $element->getTextObject(); + + $styleWriter = new ParagraphStyleWriter($xmlWriter, $textObject->getParagraphStyle()); + $styleWriter->setWithoutPPR(true); + $styleWriter->setIsInline(true); + + $xmlWriter->startElement('w:p'); + + $xmlWriter->startElement('w:pPr'); + $styleWriter->write(); + + $xmlWriter->startElement('w:numPr'); + $xmlWriter->startElement('w:ilvl'); + $xmlWriter->writeAttribute('w:val', $element->getDepth()); + $xmlWriter->endElement(); // w:ilvl + $xmlWriter->startElement('w:numId'); + $xmlWriter->writeAttribute('w:val', $element->getStyle()->getNumId()); + $xmlWriter->endElement(); // w:numId + $xmlWriter->endElement(); // w:numPr + + $xmlWriter->endElement(); // w:pPr + + $elementWriter = new Text($xmlWriter, $textObject, true); + $elementWriter->write(); + + $xmlWriter->endElement(); // w:p + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/ListItemRun.php b/src/PhpWord/Writer/Word2007/Element/ListItemRun.php new file mode 100644 index 00000000..289cb054 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/ListItemRun.php @@ -0,0 +1,66 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\ListItemRun) { + return; + } + + $xmlWriter->startElement('w:p'); + + $xmlWriter->startElement('w:pPr'); + $paragraphStyle = $element->getParagraphStyle(); + $styleWriter = new ParagraphStyleWriter($xmlWriter, $paragraphStyle); + $styleWriter->setIsInline(true); + $styleWriter->write(); + + $xmlWriter->startElement('w:numPr'); + $xmlWriter->startElement('w:ilvl'); + $xmlWriter->writeAttribute('w:val', $element->getDepth()); + $xmlWriter->endElement(); // w:ilvl + $xmlWriter->startElement('w:numId'); + $xmlWriter->writeAttribute('w:val', $element->getStyle()->getNumId()); + $xmlWriter->endElement(); // w:numId + $xmlWriter->endElement(); // w:numPr + + $xmlWriter->endElement(); // w:pPr + + $containerWriter = new Container($xmlWriter, $element); + $containerWriter->write(); + + $xmlWriter->endElement(); // w:p + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/Object.php b/src/PhpWord/Writer/Word2007/Element/Object.php new file mode 100644 index 00000000..a9cc449a --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/Object.php @@ -0,0 +1,89 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Object) { + return; + } + + $rIdObject = $element->getRelationId() + ($element->isInSection() ? 6 : 0); + $rIdImage = $element->getImageRelationId() + ($element->isInSection() ? 6 : 0); + $shapeId = md5($rIdObject . '_' . $rIdImage); + $objectId = $element->getRelationId() + 1325353440; + + $style = $element->getStyle(); + $styleWriter = new ImageStyleWriter($xmlWriter, $style); + + if (!$this->withoutP) { + $xmlWriter->startElement('w:p'); + $styleWriter->writeAlignment(); + } + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:object'); + $xmlWriter->writeAttribute('w:dxaOrig', '249'); + $xmlWriter->writeAttribute('w:dyaOrig', '160'); + + // Icon + $xmlWriter->startElement('v:shape'); + $xmlWriter->writeAttribute('id', $shapeId); + $xmlWriter->writeAttribute('type', '#_x0000_t75'); + $xmlWriter->writeAttribute('style', 'width:104px;height:67px'); + $xmlWriter->writeAttribute('o:ole', ''); + + $xmlWriter->startElement('v:imagedata'); + $xmlWriter->writeAttribute('r:id', 'rId' . $rIdImage); + $xmlWriter->writeAttribute('o:title', ''); + $xmlWriter->endElement(); // v:imagedata + + $xmlWriter->endElement(); // v:shape + + // Object + $xmlWriter->startElement('o:OLEObject'); + $xmlWriter->writeAttribute('Type', 'Embed'); + $xmlWriter->writeAttribute('ProgID', 'Package'); + $xmlWriter->writeAttribute('ShapeID', $shapeId); + $xmlWriter->writeAttribute('DrawAspect', 'Icon'); + $xmlWriter->writeAttribute('ObjectID', '_' . $objectId); + $xmlWriter->writeAttribute('r:id', 'rId' . $rIdObject); + $xmlWriter->endElement(); // o:OLEObject + + $xmlWriter->endElement(); // w:object + $xmlWriter->endElement(); // w:r + + $this->endElementP(); // w:p + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/PageBreak.php b/src/PhpWord/Writer/Word2007/Element/PageBreak.php new file mode 100644 index 00000000..fb831ca7 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/PageBreak.php @@ -0,0 +1,45 @@ +getXmlWriter(); + + $xmlWriter->startElement('w:p'); + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:br'); + $xmlWriter->writeAttribute('w:type', 'page'); + $xmlWriter->endElement(); // w:br + $xmlWriter->endElement(); // w:r + $xmlWriter->endElement(); // w:p + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/PreserveText.php b/src/PhpWord/Writer/Word2007/Element/PreserveText.php new file mode 100644 index 00000000..894b3050 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/PreserveText.php @@ -0,0 +1,93 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\PreserveText) { + return; + } + + $texts = $element->getText(); + if (!is_array($texts)) { + $texts = array($texts); + } + + $this->startElementP(); + + foreach ($texts as $text) { + if (substr($text, 0, 1) == '{') { + $text = substr($text, 1, -1); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'begin'); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + + $xmlWriter->startElement('w:r'); + + $this->writeFontStyle(); + + $xmlWriter->startElement('w:instrText'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw($text); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'separate'); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'end'); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + } else { + $xmlWriter->startElement('w:r'); + + $this->writeFontStyle(); + + $xmlWriter->startElement('w:t'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw($this->getText($text)); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + } + } + + $this->endElementP(); // w:p + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/SDT.php b/src/PhpWord/Writer/Word2007/Element/SDT.php new file mode 100644 index 00000000..79d7004d --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/SDT.php @@ -0,0 +1,124 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof SDTElement) { + return; + } + $type = $element->getType(); + $writeFormField = "write{$type}"; + + $this->startElementP(); + + $xmlWriter->startElement('w:sdt'); + + // Properties + $xmlWriter->startElement('w:sdtPr'); + $xmlWriter->writeElementBlock('w:id', 'w:val', rand(100000000, 999999999)); + $xmlWriter->writeElementBlock('w:lock', 'w:val', 'sdtLocked'); + $this->$writeFormField($xmlWriter, $element); + $xmlWriter->endElement(); // w:sdtPr + + // Content + $xmlWriter->startElement('w:sdtContent'); + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:t'); + $xmlWriter->writeRaw('Pick value'); + $xmlWriter->endElement(); // w:t + $xmlWriter->endElement(); // w:r + $xmlWriter->endElement(); // w:sdtContent + + $xmlWriter->endElement(); // w:sdt + + $this->endElementP(); // w:p + } + + /** + * Write combo box. + * + * @link http://www.datypic.com/sc/ooxml/t-w_CT_SdtComboBox.html + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\SDT $element + * @return void + */ + private function writeComboBox(XMLWriter $xmlWriter, SDTElement $element) + { + $type = $element->getType(); + $listItems = $element->getListItems(); + + $xmlWriter->startElement("w:{$type}"); + foreach ($listItems as $key => $val) { + $xmlWriter->writeElementBlock('w:listItem', array('w:value' => $key, 'w:displayText' => $val)); + } + $xmlWriter->endElement(); // w:{$type} + } + + /** + * Write drop down list. + * + * @link http://www.datypic.com/sc/ooxml/t-w_CT_SdtDropDownList.html + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\SDT $element + * @return void + */ + private function writeDropDownList(XMLWriter $xmlWriter, SDTElement $element) + { + $this->writecomboBox($xmlWriter, $element); + } + + /** + * Write date. + * + * @link http://www.datypic.com/sc/ooxml/t-w_CT_SdtDate.html + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\SDT $element + * @return void + */ + private function writeDate(XMLWriter $xmlWriter, SDTElement $element) + { + $type = $element->getType(); + + $xmlWriter->startElement("w:{$type}"); + $xmlWriter->writeElementBlock('w:dateFormat', 'w:val', 'd/M/yyyy'); + $xmlWriter->writeElementBlock('w:lid', 'w:val', 'en-US'); + $xmlWriter->writeElementBlock('w:storeMappedDataAs', 'w:val', 'dateTime'); + $xmlWriter->writeElementBlock('w:calendar', 'w:val', 'gregorian'); + $xmlWriter->endElement(); // w:date + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/Shape.php b/src/PhpWord/Writer/Word2007/Element/Shape.php new file mode 100644 index 00000000..bd9320a2 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/Shape.php @@ -0,0 +1,175 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof ShapeElement) { + return; + } + + $style = $element->getStyle(); + $styleWriter = new ShapeStyleWriter($xmlWriter, $style); + + $type = $element->getType(); + if ($type == 'rect' && $style->getRoundness() !== null) { + $type = 'roundrect'; + } + $method = "write{$type}"; + + if (!$this->withoutP) { + $xmlWriter->startElement('w:p'); + } + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:pict'); + $xmlWriter->startElement("v:{$type}"); + + // Element style + if (method_exists($this, $method)) { + $this->$method($xmlWriter, $style); + } + + // Child style + $styleWriter->write(); + + $xmlWriter->endElement(); // v:$type + $xmlWriter->endElement(); // w:pict + $xmlWriter->endElement(); // w:r + + $this->endElementP(); // w:p + } + + /** + * Write arc. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Style\Shape $style + * @return void + */ + private function writeArc(XMLWriter $xmlWriter, ShapeStyle $style) + { + $points = $this->getPoints('arc', $style->getPoints()); + + $xmlWriter->writeAttributeIf($points['start'] !== null, 'startAngle', $points['start']); + $xmlWriter->writeAttributeIf($points['end'] !== null, 'endAngle', $points['end']); + } + + /** + * Write curve. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Style\Shape $style + * @return void + */ + private function writeCurve(XMLWriter $xmlWriter, ShapeStyle $style) + { + $points = $this->getPoints('curve', $style->getPoints()); + + $this->writeLine($xmlWriter, $style); + $xmlWriter->writeAttributeIf($points['point1'] !== null, 'control1', $points['point1']); + $xmlWriter->writeAttributeIf($points['point2'] !== null, 'control2', $points['point2']); + } + + /** + * Write line. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Style\Shape $style + * @return void + */ + private function writeLine(XMLWriter $xmlWriter, ShapeStyle $style) + { + $points = $this->getPoints('line', $style->getPoints()); + + $xmlWriter->writeAttributeIf($points['start'] !== null, 'from', $points['start']); + $xmlWriter->writeAttributeIf($points['end'] !== null, 'to', $points['end']); + } + + /** + * Write polyline. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Style\Shape $style + * @return void + */ + private function writePolyline(XMLWriter $xmlWriter, ShapeStyle $style) + { + $xmlWriter->writeAttributeIf($style->getPoints() !== null, 'points', $style->getPoints()); + } + + /** + * Write rectangle. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Style\Shape $style + * @return void + */ + private function writeRoundRect(XMLWriter $xmlWriter, ShapeStyle $style) + { + $xmlWriter->writeAttribute('arcsize', $style->getRoundness()); + } + + /** + * Set points + * + * @param string $type + * @param string $value + * @return array + */ + private function getPoints($type, $value) + { + $points = array(); + + switch ($type) { + case 'arc': + case 'line': + $points = explode(' ', $value); + @list($start, $end) = $points; + $points = array('start' => $start, 'end' => $end); + break; + case 'curve': + $points = explode(' ', $value); + @list($start, $end, $point1, $point2) = $points; + $points = array('start' => $start, 'end' => $end, 'point1' => $point1, 'point2' => $point2); + break; + } + + return $points; + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/TOC.php b/src/PhpWord/Writer/Word2007/Element/TOC.php new file mode 100644 index 00000000..db2a65d0 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/TOC.php @@ -0,0 +1,213 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof TOCElement) { + return; + } + + $titles = $element->getTitles(); + $writeFieldMark = true; + + foreach ($titles as $title) { + $this->writeTitle($xmlWriter, $element, $title, $writeFieldMark); + if ($writeFieldMark) { + $writeFieldMark = false; + } + } + + $xmlWriter->startElement('w:p'); + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'end'); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + } + + /** + * Write title + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\TOC $element + * @param \PhpOffice\PhpWord\Element\Title $title + * @param bool $writeFieldMark + * @return void + */ + private function writeTitle(XMLWriter $xmlWriter, TOCElement $element, $title, $writeFieldMark) + { + $tocStyle = $element->getStyleTOC(); + $fontStyle = $element->getStyleFont(); + $isObject = ($fontStyle instanceof Font) ? true : false; + $rId = $title->getRelationId(); + $indent = ($title->getDepth() - 1) * $tocStyle->getIndent(); + + $xmlWriter->startElement('w:p'); + + // Write style and field mark + $this->writeStyle($xmlWriter, $element, $indent); + if ($writeFieldMark) { + $this->writeFieldMark($xmlWriter, $element); + } + + // Hyperlink + $xmlWriter->startElement('w:hyperlink'); + $xmlWriter->writeAttribute('w:anchor', "_Toc{$rId}"); + $xmlWriter->writeAttribute('w:history', '1'); + + // Title text + $xmlWriter->startElement('w:r'); + if ($isObject) { + $styleWriter = new FontStyleWriter($xmlWriter, $fontStyle); + $styleWriter->write(); + } + $xmlWriter->startElement('w:t'); + $xmlWriter->writeRaw($title->getText()); + $xmlWriter->endElement(); + $xmlWriter->endElement(); // w:r + + $xmlWriter->startElement('w:r'); + $xmlWriter->writeElement('w:tab', null); + $xmlWriter->endElement(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'begin'); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:instrText'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw("PAGEREF _Toc{$rId} \h"); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'end'); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + + $xmlWriter->endElement(); // w:hyperlink + + $xmlWriter->endElement(); // w:p + } + + /** + * Write style + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\TOC $element + * @param int $indent + * @return void + */ + private function writeStyle(XMLWriter $xmlWriter, TOCElement $element, $indent) + { + $tocStyle = $element->getStyleTOC(); + $fontStyle = $element->getStyleFont(); + $isObject = ($fontStyle instanceof Font) ? true : false; + + $xmlWriter->startElement('w:pPr'); + + // Paragraph + if ($isObject && !is_null($fontStyle->getParagraph())) { + $styleWriter = new ParagraphStyleWriter($xmlWriter, $fontStyle->getParagraph()); + $styleWriter->write(); + } + + // Font + if (!empty($fontStyle) && !$isObject) { + $xmlWriter->startElement('w:rPr'); + $xmlWriter->startElement('w:rStyle'); + $xmlWriter->writeAttribute('w:val', $fontStyle); + $xmlWriter->endElement(); + $xmlWriter->endElement(); // w:rPr + } + + // Tab + $xmlWriter->startElement('w:tabs'); + $styleWriter = new TabStyleWriter($xmlWriter, $tocStyle); + $styleWriter->write(); + $xmlWriter->endElement(); + + // Indent + if ($indent > 0) { + $xmlWriter->startElement('w:ind'); + $xmlWriter->writeAttribute('w:left', $indent); + $xmlWriter->endElement(); + } + + $xmlWriter->endElement(); // w:pPr + } + + /** + * Write TOC Field. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\TOC $element + * @return void + */ + private function writeFieldMark(XMLWriter $xmlWriter, TOCElement $element) + { + $minDepth = $element->getMinDepth(); + $maxDepth = $element->getMaxDepth(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'begin'); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:instrText'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw("TOC \o {$minDepth}-{$maxDepth} \h \z \u"); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:fldChar'); + $xmlWriter->writeAttribute('w:fldCharType', 'separate'); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/Table.php b/src/PhpWord/Writer/Word2007/Element/Table.php new file mode 100644 index 00000000..f090d05c --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/Table.php @@ -0,0 +1,163 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof TableElement) { + return; + } + + $rows = $element->getRows(); + $rowCount = count($rows); + + if ($rowCount > 0) { + $xmlWriter->startElement('w:tbl'); + + // Write columns + $this->writeColumns($xmlWriter, $element); + + // Write style + $styleWriter = new TableStyleWriter($xmlWriter, $element->getStyle()); + $styleWriter->setWidth($element->getWidth()); + $styleWriter->write(); + + // Write rows + for ($i = 0; $i < $rowCount; $i++) { + $this->writeRow($xmlWriter, $rows[$i]); + } + + $xmlWriter->endElement(); // w:tbl + } + } + + /** + * Write column. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\Table $element + * @return void + */ + private function writeColumns(XMLWriter $xmlWriter, TableElement $element) + { + $rows = $element->getRows(); + $rowCount = count($rows); + + $cellWidths = array(); + for ($i = 0; $i < $rowCount; $i++) { + $row = $rows[$i]; + $cells = $row->getCells(); + if (count($cells) <= count($cellWidths)) { + continue; + } + $cellWidths = array(); + foreach ($cells as $cell) { + $cellWidths[] = $cell->getWidth(); + } + } + + $xmlWriter->startElement('w:tblGrid'); + foreach ($cellWidths as $width) { + $xmlWriter->startElement('w:gridCol'); + if ($width !== null) { + $xmlWriter->writeAttribute('w:w', $width); + $xmlWriter->writeAttribute('w:type', 'dxa'); + } + $xmlWriter->endElement(); + } + $xmlWriter->endElement(); // w:tblGrid + } + + /** + * Write row. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\Row $row + * @return void + */ + private function writeRow(XMLWriter $xmlWriter, RowElement $row) + { + $xmlWriter->startElement('w:tr'); + + // Write style + $rowStyle = $row->getStyle(); + if ($rowStyle instanceof RowStyle) { + $styleWriter = new RowStyleWriter($xmlWriter, $rowStyle); + $styleWriter->setHeight($row->getHeight()); + $styleWriter->write(); + } + + // Write cells + foreach ($row->getCells() as $cell) { + $this->writeCell($xmlWriter, $cell); + } + + $xmlWriter->endElement(); // w:tr + } + + /** + * Write cell. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\Cell $cell + * @return void + */ + private function writeCell(XMLWriter $xmlWriter, CellElement $cell) + { + + $xmlWriter->startElement('w:tc'); + + // Write style + $cellStyle = $cell->getStyle(); + if ($cellStyle instanceof CellStyle) { + $styleWriter = new CellStyleWriter($xmlWriter, $cellStyle); + $styleWriter->setWidth($cell->getWidth()); + $styleWriter->write(); + } + + // Write content + $containerWriter = new Container($xmlWriter, $cell); + $containerWriter->write(); + + $xmlWriter->endElement(); // w:tc + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/Text.php b/src/PhpWord/Writer/Word2007/Element/Text.php new file mode 100644 index 00000000..cfb991c2 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/Text.php @@ -0,0 +1,54 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Text) { + return; + } + + $this->startElementP(); + + $xmlWriter->startElement('w:r'); + + $this->writeFontStyle(); + + $xmlWriter->startElement('w:t'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw($this->getText($element->getText())); + $xmlWriter->endElement(); + $xmlWriter->endElement(); // w:r + + $this->endElementP(); // w:p + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/TextBox.php b/src/PhpWord/Writer/Word2007/Element/TextBox.php new file mode 100644 index 00000000..fe62c644 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/TextBox.php @@ -0,0 +1,74 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\TextBox) { + return; + } + $style = $element->getStyle(); + $styleWriter = new TextBoxStyleWriter($xmlWriter, $style); + + if (!$this->withoutP) { + $xmlWriter->startElement('w:p'); + $styleWriter->writeAlignment(); + } + + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:pict'); + $xmlWriter->startElement('v:shape'); + $xmlWriter->writeAttribute('type', '#_x0000_t0202'); + + $styleWriter->write(); + $styleWriter->writeBorder(); + + $xmlWriter->startElement('v:textbox'); + $styleWriter->writeInnerMargin(); + + // TextBox content, serving as a container + $xmlWriter->startElement('w:txbxContent'); + $containerWriter = new Container($xmlWriter, $element); + $containerWriter->write(); + $xmlWriter->endElement(); // w:txbxContent + + $xmlWriter->endElement(); // v: textbox + + $xmlWriter->endElement(); // v:shape + $xmlWriter->endElement(); // w:pict + $xmlWriter->endElement(); // w:r + + $this->endElementP(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/TextBreak.php b/src/PhpWord/Writer/Word2007/Element/TextBreak.php new file mode 100644 index 00000000..fb52b86e --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/TextBreak.php @@ -0,0 +1,55 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\TextBreak) { + return; + } + + if (!$this->withoutP) { + $hasStyle = $element->hasStyle(); + $this->startElementP(); + + if ($hasStyle) { + $xmlWriter->startElement('w:pPr'); + $this->writeFontStyle(); + $xmlWriter->endElement(); // w:pPr + } + + $this->endElementP(); // w:p + } else { + $xmlWriter->writeElement('w:br'); + } + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/TextRun.php b/src/PhpWord/Writer/Word2007/Element/TextRun.php new file mode 100644 index 00000000..844e0b6b --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/TextRun.php @@ -0,0 +1,44 @@ +getXmlWriter(); + $element = $this->getElement(); + + $this->startElementP(); + + $containerWriter = new Container($xmlWriter, $element); + $containerWriter->write(); + + $this->endElementP(); // w:p + } +} diff --git a/src/PhpWord/Writer/Word2007/Element/Title.php b/src/PhpWord/Writer/Word2007/Element/Title.php new file mode 100644 index 00000000..ce9aeea5 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Element/Title.php @@ -0,0 +1,75 @@ +getXmlWriter(); + $element = $this->getElement(); + if (!$element instanceof \PhpOffice\PhpWord\Element\Title) { + return; + } + + $style = $element->getStyle(); + + $xmlWriter->startElement('w:p'); + + if (!empty($style)) { + $xmlWriter->startElement('w:pPr'); + $xmlWriter->startElement('w:pStyle'); + $xmlWriter->writeAttribute('w:val', $style); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + } + + $rId = $element->getRelationId(); + $bookmarkRId = $element->getPhpWord()->addBookmark(); + + // Bookmark start for TOC + $xmlWriter->startElement('w:bookmarkStart'); + $xmlWriter->writeAttribute('w:id', $bookmarkRId); + $xmlWriter->writeAttribute('w:name', "_Toc{$rId}"); + $xmlWriter->endElement(); + + // Actual text + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:t'); + $xmlWriter->writeRaw($this->getText($element->getText())); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + + // Bookmark end + $xmlWriter->startElement('w:bookmarkEnd'); + $xmlWriter->writeAttribute('w:id', $bookmarkRId); + $xmlWriter->endElement(); + + $xmlWriter->endElement(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Footer.php b/src/PhpWord/Writer/Word2007/Footer.php deleted file mode 100644 index dc726114..00000000 --- a/src/PhpWord/Writer/Word2007/Footer.php +++ /dev/null @@ -1,50 +0,0 @@ -getXmlWriter(); - - // XML header - $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); - - $xmlWriter->startElement('w:ftr'); - $xmlWriter->writeAttribute('xmlns:ve', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); - $xmlWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); - $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - $xmlWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math'); - $xmlWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); - $xmlWriter->writeAttribute('xmlns:wp', 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'); - $xmlWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word'); - $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); - $xmlWriter->writeAttribute('xmlns:wne', 'http://schemas.microsoft.com/office/word/2006/wordml'); - - $this->writeContainerElements($xmlWriter, $footer); - - $xmlWriter->endElement(); - - // Return - return $xmlWriter->getData(); - } -} diff --git a/src/PhpWord/Writer/Word2007/Header.php b/src/PhpWord/Writer/Word2007/Header.php deleted file mode 100644 index 95e57340..00000000 --- a/src/PhpWord/Writer/Word2007/Header.php +++ /dev/null @@ -1,50 +0,0 @@ -getXmlWriter(); - - // XML header - $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); - - $xmlWriter->startElement('w:hdr'); - $xmlWriter->writeAttribute('xmlns:ve', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); - $xmlWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); - $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - $xmlWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math'); - $xmlWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); - $xmlWriter->writeAttribute('xmlns:wp', 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'); - $xmlWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word'); - $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); - $xmlWriter->writeAttribute('xmlns:wne', 'http://schemas.microsoft.com/office/word/2006/wordml'); - - $this->writeContainerElements($xmlWriter, $header); - - $xmlWriter->endElement(); - - // Return - return $xmlWriter->getData(); - } -} diff --git a/src/PhpWord/Writer/Word2007/Notes.php b/src/PhpWord/Writer/Word2007/Notes.php deleted file mode 100644 index 3b70ee74..00000000 --- a/src/PhpWord/Writer/Word2007/Notes.php +++ /dev/null @@ -1,126 +0,0 @@ -getXmlWriter(); - - // XML header - $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); - $xmlWriter->startElement($rootNode); - $xmlWriter->writeAttribute('xmlns:ve', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); - $xmlWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); - $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - $xmlWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math'); - $xmlWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); - $xmlWriter->writeAttribute('xmlns:wp', 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'); - $xmlWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word'); - $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); - $xmlWriter->writeAttribute('xmlns:wne', 'http://schemas.microsoft.com/office/word/2006/wordml'); - - // Separator and continuation separator - $xmlWriter->startElement($elementNode); - $xmlWriter->writeAttribute('w:id', -1); - $xmlWriter->writeAttribute('w:type', 'separator'); - $xmlWriter->startElement('w:p'); - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:separator'); - $xmlWriter->endElement(); // w:separator - $xmlWriter->endElement(); // w:r - $xmlWriter->endElement(); // w:p - $xmlWriter->endElement(); // $elementNode - $xmlWriter->startElement($elementNode); - $xmlWriter->writeAttribute('w:id', 0); - $xmlWriter->writeAttribute('w:type', 'continuationSeparator'); - $xmlWriter->startElement('w:p'); - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:continuationSeparator'); - $xmlWriter->endElement(); // w:continuationSeparator - $xmlWriter->endElement(); // w:r - $xmlWriter->endElement(); // w:p - $xmlWriter->endElement(); // $elementNode - - // Content - foreach ($elements as $element) { - if ($element instanceof Footnote || $element instanceof Endnote) { - $this->writeNote($xmlWriter, $element, $notesTypes); - } - } - - $xmlWriter->endElement(); - - return $xmlWriter->getData(); - } - - /** - * Write note item - * - * @param XMLWriter $xmlWriter - * @param Footnote|Endnote $element - * @param string $notesTypes - */ - protected function writeNote(XMLWriter $xmlWriter, $element, $notesTypes = 'footnotes') - { - $isFootnote = ($notesTypes == 'footnotes'); - $elementNode = $isFootnote ? 'w:footnote' : 'w:endnote'; - $refNode = $isFootnote ? 'w:footnoteRef' : 'w:endnoteRef'; - $styleName = $isFootnote ? 'FootnoteReference' : 'EndnoteReference'; - - $xmlWriter->startElement($elementNode); - $xmlWriter->writeAttribute('w:id', $element->getRelationId()); - $xmlWriter->startElement('w:p'); - - // Paragraph style - $styleParagraph = $element->getParagraphStyle(); - $this->writeInlineParagraphStyle($xmlWriter, $styleParagraph); - - // Reference symbol - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:rPr'); - $xmlWriter->startElement('w:rStyle'); - $xmlWriter->writeAttribute('w:val', $styleName); - $xmlWriter->endElement(); // w:rStyle - $xmlWriter->endElement(); // w:rPr - $xmlWriter->writeElement($refNode); - $xmlWriter->endElement(); // w:r - - // Empty space after refence symbol - $xmlWriter->startElement('w:r'); - $xmlWriter->startElement('w:t'); - $xmlWriter->writeAttribute('xml:space', 'preserve'); - $xmlWriter->writeRaw(' '); - $xmlWriter->endElement(); // w:t - $xmlWriter->endElement(); // w:r - - $this->writeContainerElements($xmlWriter, $element); - - $xmlWriter->endElement(); // w:p - $xmlWriter->endElement(); // $elementNode - } -} diff --git a/src/PhpWord/Writer/Word2007/Numbering.php b/src/PhpWord/Writer/Word2007/Numbering.php deleted file mode 100644 index da127891..00000000 --- a/src/PhpWord/Writer/Word2007/Numbering.php +++ /dev/null @@ -1,177 +0,0 @@ -getXmlWriter(); - - $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); - $xmlWriter->startElement('w:numbering'); - $xmlWriter->writeAttribute('xmlns:ve', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); - $xmlWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); - $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - $xmlWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math'); - $xmlWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); - $xmlWriter->writeAttribute('xmlns:wp', 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'); - $xmlWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word'); - $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); - $xmlWriter->writeAttribute('xmlns:wne', 'http://schemas.microsoft.com/office/word/2006/wordml'); - - // Abstract numbering definitions - foreach ($styles as $style) { - if ($style instanceof NumberingStyle) { - $levels = $style->getLevels(); - - $xmlWriter->startElement('w:abstractNum'); - $xmlWriter->writeAttribute('w:abstractNumId', $style->getNumId()); - - $xmlWriter->startElement('w:nsid'); - $xmlWriter->writeAttribute('w:val', $this->getRandomHexNumber()); - $xmlWriter->endElement(); // w:nsid - - $xmlWriter->startElement('w:multiLevelType'); - $xmlWriter->writeAttribute('w:val', $style->getType()); - $xmlWriter->endElement(); // w:multiLevelType - - if (is_array($levels)) { - foreach ($levels as $levelNum => $levelObject) { - if ($levelObject instanceof NumberingLevel) { - $start = $levelObject->getStart(); - $format = $levelObject->getFormat(); - $restart = $levelObject->getRestart(); - $suffix = $levelObject->getSuffix(); - $text = $levelObject->getText(); - $align = $levelObject->getAlign(); - $tabPos = $levelObject->getTabPos(); - $left = $levelObject->getLeft(); - $hanging = $levelObject->getHanging(); - $font = $levelObject->getFont(); - $hint = $levelObject->getHint(); - - $xmlWriter->startElement('w:lvl'); - $xmlWriter->writeAttribute('w:ilvl', $levelNum); - - if (!is_null($start)) { - $xmlWriter->startElement('w:start'); - $xmlWriter->writeAttribute('w:val', $start); - $xmlWriter->endElement(); // w:start - } - if (!is_null($format)) { - $xmlWriter->startElement('w:numFmt'); - $xmlWriter->writeAttribute('w:val', $format); - $xmlWriter->endElement(); // w:numFmt - } - if (!is_null($restart)) { - $xmlWriter->startElement('w:lvlRestart'); - $xmlWriter->writeAttribute('w:val', $restart); - $xmlWriter->endElement(); // w:lvlRestart - } - if (!is_null($suffix)) { - $xmlWriter->startElement('w:suff'); - $xmlWriter->writeAttribute('w:val', $suffix); - $xmlWriter->endElement(); // w:suff - } - if (!is_null($text)) { - $xmlWriter->startElement('w:lvlText'); - $xmlWriter->writeAttribute('w:val', $text); - $xmlWriter->endElement(); // w:start - } - if (!is_null($align)) { - $xmlWriter->startElement('w:lvlJc'); - $xmlWriter->writeAttribute('w:val', $align); - $xmlWriter->endElement(); // w:lvlJc - } - if (!is_null($tabPos) || !is_null($left) || !is_null($hanging)) { - $xmlWriter->startElement('w:pPr'); - if (!is_null($tabPos)) { - $xmlWriter->startElement('w:tabs'); - $xmlWriter->startElement('w:tab'); - $xmlWriter->writeAttribute('w:val', 'num'); - $xmlWriter->writeAttribute('w:pos', $tabPos); - $xmlWriter->endElement(); // w:tab - $xmlWriter->endElement(); // w:tabs - } - if (!is_null($left) || !is_null($hanging)) { - $xmlWriter->startElement('w:ind'); - if (!is_null($left)) { - $xmlWriter->writeAttribute('w:left', $left); - } - if (!is_null($hanging)) { - $xmlWriter->writeAttribute('w:hanging', $hanging); - } - $xmlWriter->endElement(); // w:ind - } - $xmlWriter->endElement(); // w:pPr - } - if (!is_null($font) || !is_null($hint)) { - $xmlWriter->startElement('w:rPr'); - $xmlWriter->startElement('w:rFonts'); - if (!is_null($font)) { - $xmlWriter->writeAttribute('w:ascii', $font); - $xmlWriter->writeAttribute('w:hAnsi', $font); - $xmlWriter->writeAttribute('w:cs', $font); - } - if (!is_null($hint)) { - $xmlWriter->writeAttribute('w:hint', $hint); - } - $xmlWriter->endElement(); // w:rFonts - $xmlWriter->endElement(); // w:rPr - } - $xmlWriter->endElement(); // w:lvl - } - } - } - $xmlWriter->endElement(); // w:abstractNum - } - } - - // Numbering definition instances - foreach ($styles as $style) { - if ($style instanceof NumberingStyle) { - $xmlWriter->startElement('w:num'); - $xmlWriter->writeAttribute('w:numId', $style->getNumId()); - $xmlWriter->startElement('w:abstractNumId'); - $xmlWriter->writeAttribute('w:val', $style->getNumId()); - $xmlWriter->endElement(); // w:abstractNumId - $xmlWriter->endElement(); // w:num - } - } - - $xmlWriter->endElement(); - - return $xmlWriter->getData(); - } - - /** - * Get random hexadecimal number value - * - * @param int $length - * @return string - */ - private function getRandomHexNumber($length = 8) - { - return strtoupper(substr(md5(rand()), 0, $length)); - } -} diff --git a/src/PhpWord/Writer/Word2007/Part/AbstractPart.php b/src/PhpWord/Writer/Word2007/Part/AbstractPart.php new file mode 100644 index 00000000..e26853d7 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/AbstractPart.php @@ -0,0 +1,93 @@ +parentWriter = $writer; + } + + /** + * Get parent writer + * + * @return \PhpOffice\PhpWord\Writer\AbstractWriter + * @throws \PhpOffice\PhpWord\Exception\Exception + */ + public function getParentWriter() + { + if (!is_null($this->parentWriter)) { + return $this->parentWriter; + } else { + throw new Exception('No parent WriterInterface assigned.'); + } + } + + /** + * Get XML Writer + * + * @return \PhpOffice\PhpWord\Shared\XMLWriter + */ + protected function getXmlWriter() + { + $useDiskCaching = false; + if (!is_null($this->parentWriter)) { + if ($this->parentWriter->isUseDiskCaching()) { + $useDiskCaching = true; + } + } + if ($useDiskCaching) { + return new XMLWriter(XMLWriter::STORAGE_DISK, $this->parentWriter->getDiskCachingDirectory()); + } else { + return new XMLWriter(XMLWriter::STORAGE_MEMORY); + } + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/Chart.php b/src/PhpWord/Writer/Word2007/Part/Chart.php new file mode 100644 index 00000000..8423762c --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/Chart.php @@ -0,0 +1,320 @@ + array('type' => 'pie', 'colors' => 1), + 'doughnut' => array('type' => 'doughnut', 'colors' => 1, 'hole' => 75, 'no3d' => true), + 'bar' => array('type' => 'bar', 'colors' => 0, 'axes' => true, 'bar' => 'bar'), + 'column' => array('type' => 'bar', 'colors' => 0, 'axes' => true, 'bar' => 'col'), + 'line' => array('type' => 'line', 'colors' => 0, 'axes' => true), + 'area' => array('type' => 'area', 'colors' => 0, 'axes' => true), + 'radar' => array('type' => 'radar', 'colors' => 0, 'axes' => true, 'radar' => 'standard', 'no3d' => true), + 'scatter' => array('type' => 'scatter', 'colors' => 0, 'axes' => true, 'scatter' => 'marker', 'no3d' => true), + ); + + /** + * Chart options + * + * @var array + */ + private $options = array(); + + /** + * Set chart element. + * + * @param \PhpOffice\PhpWord\Element\Chart $element + * @return void + */ + public function setElement(ChartElement $element) + { + $this->element = $element; + } + + /** + * Write part + * + * @return string + */ + public function write() + { + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); + $xmlWriter->startElement('c:chartSpace'); + $xmlWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart'); + $xmlWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main'); + $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + + $this->writeChart($xmlWriter); + $this->writeShape($xmlWriter); + + $xmlWriter->endElement(); // c:chartSpace + + return $xmlWriter->getData(); + } + + /** + * Write chart + * + * @link http://www.datypic.com/sc/ooxml/t-draw-chart_CT_Chart.html + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @return void + */ + private function writeChart(XMLWriter $xmlWriter) + { + $xmlWriter->startElement('c:chart'); + + $xmlWriter->writeElementBlock('c:autoTitleDeleted', 'val', 1); + + $this->writePlotArea($xmlWriter); + + $xmlWriter->endElement(); // c:chart + } + + /** + * Write plot area. + * + * @link http://www.datypic.com/sc/ooxml/t-draw-chart_CT_PlotArea.html + * @link http://www.datypic.com/sc/ooxml/t-draw-chart_CT_PieChart.html + * @link http://www.datypic.com/sc/ooxml/t-draw-chart_CT_DoughnutChart.html + * @link http://www.datypic.com/sc/ooxml/t-draw-chart_CT_BarChart.html + * @link http://www.datypic.com/sc/ooxml/t-draw-chart_CT_LineChart.html + * @link http://www.datypic.com/sc/ooxml/t-draw-chart_CT_AreaChart.html + * @link http://www.datypic.com/sc/ooxml/t-draw-chart_CT_RadarChart.html + * @link http://www.datypic.com/sc/ooxml/t-draw-chart_CT_ScatterChart.html + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @return void + */ + private function writePlotArea(XMLWriter $xmlWriter) + { + $type = $this->element->getType(); + $style = $this->element->getStyle(); + $this->options = $this->types[$type]; + + $xmlWriter->startElement('c:plotArea'); + $xmlWriter->writeElement('c:layout'); + + // Chart + $chartType = $this->options['type']; + $chartType .= $style->is3d() && !isset($this->options['no3d'])? '3D' : ''; + $chartType .= 'Chart'; + $xmlWriter->startElement("c:{$chartType}"); + + $xmlWriter->writeElementBlock('c:varyColors', 'val', $this->options['colors']); + if ($type == 'area') { + $xmlWriter->writeElementBlock('c:grouping', 'val', 'standard'); + } + if (isset($this->options['hole'])) { + $xmlWriter->writeElementBlock('c:holeSize', 'val', $this->options['hole']); + } + if (isset($this->options['bar'])) { + $xmlWriter->writeElementBlock('c:barDir', 'val', $this->options['bar']); // bar|col + $xmlWriter->writeElementBlock('c:grouping', 'val', 'clustered'); // 3d; standard = percentStacked + } + if (isset($this->options['radar'])) { + $xmlWriter->writeElementBlock('c:radarStyle', 'val', $this->options['radar']); + } + if (isset($this->options['scatter'])) { + $xmlWriter->writeElementBlock('c:scatterStyle', 'val', $this->options['scatter']); + } + + // Series + $this->writeSeries($xmlWriter, isset($this->options['scatter'])); + + // Axes + if (isset($this->options['axes'])) { + $xmlWriter->writeElementBlock('c:axId', 'val', 1); + $xmlWriter->writeElementBlock('c:axId', 'val', 2); + } + + $xmlWriter->endElement(); // chart type + + // Axes + if (isset($this->options['axes'])) { + $this->writeAxis($xmlWriter, 'cat'); + $this->writeAxis($xmlWriter, 'val'); + } + + $xmlWriter->endElement(); // c:plotArea + } + + /** + * Write series. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param bool $scatter + * @return void + */ + private function writeSeries(XMLWriter $xmlWriter, $scatter = false) + { + $series = $this->element->getSeries(); + + $index = 0; + foreach ($series as $seriesItem) { + $categories = $seriesItem['categories']; + $values = $seriesItem['values']; + + $xmlWriter->startElement('c:ser'); + + $xmlWriter->writeElementBlock('c:idx', 'val', $index); + $xmlWriter->writeElementBlock('c:order', 'val', $index); + + if (isset($this->options['scatter'])) { + $this->writeShape($xmlWriter); + } + + if ($scatter === true) { + $this->writeSeriesItem($xmlWriter, 'xVal', $categories); + $this->writeSeriesItem($xmlWriter, 'yVal', $values); + } else { + $this->writeSeriesItem($xmlWriter, 'cat', $categories); + $this->writeSeriesItem($xmlWriter, 'val', $values); + } + + $xmlWriter->endElement(); // c:ser + $index++; + } + + } + + /** + * Write series items. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param string $type + * @param array $values + * @return void + */ + private function writeSeriesItem(XMLWriter $xmlWriter, $type, $values) + { + $types = array( + 'cat' => array('c:cat', 'c:strLit'), + 'val' => array('c:val', 'c:numLit'), + 'xVal' => array('c:xVal', 'c:strLit'), + 'yVal' => array('c:yVal', 'c:numLit'), + ); + list($itemType, $itemLit) = $types[$type]; + + $xmlWriter->startElement($itemType); + $xmlWriter->startElement($itemLit); + + $index = 0; + foreach ($values as $value) { + $xmlWriter->startElement('c:pt'); + $xmlWriter->writeAttribute('idx', $index); + + $xmlWriter->startElement('c:v'); + $xmlWriter->writeRaw($value); + $xmlWriter->endElement(); // c:v + + $xmlWriter->endElement(); // c:pt + $index++; + } + + $xmlWriter->endElement(); // $itemLit + $xmlWriter->endElement(); // $itemType + } + + /** + * Write axis + * + * @link http://www.datypic.com/sc/ooxml/t-draw-chart_CT_CatAx.html + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param string $type + * @return void + */ + private function writeAxis(XMLWriter $xmlWriter, $type) + { + $types = array( + 'cat' => array('c:catAx', 1, 'b', 2), + 'val' => array('c:valAx', 2, 'l', 1), + ); + list($axisType, $axisId, $axisPos, $axisCross) = $types[$type]; + + $xmlWriter->startElement($axisType); + + $xmlWriter->writeElementBlock('c:axId', 'val', $axisId); + $xmlWriter->writeElementBlock('c:axPos', 'val', $axisPos); + $xmlWriter->writeElementBlock('c:crossAx', 'val', $axisCross); + $xmlWriter->writeElementBlock('c:auto', 'val', 1); + + if (isset($this->options['axes'])) { + $xmlWriter->writeElementBlock('c:delete', 'val', 0); + $xmlWriter->writeElementBlock('c:majorTickMark', 'val', 'none'); + $xmlWriter->writeElementBlock('c:minorTickMark', 'val', 'none'); + $xmlWriter->writeElementBlock('c:tickLblPos', 'val', 'none'); // nextTo + $xmlWriter->writeElementBlock('c:crosses', 'val', 'autoZero'); + } + if (isset($this->options['radar'])) { + $xmlWriter->writeElement('c:majorGridlines'); + } + + $xmlWriter->startElement('c:scaling'); + $xmlWriter->writeElementBlock('c:orientation', 'val', 'minMax'); + $xmlWriter->endElement(); // c:scaling + + $this->writeShape($xmlWriter, true); + + $xmlWriter->endElement(); // $axisType + } + + /** + * Write shape + * + * @link http://www.datypic.com/sc/ooxml/t-a_CT_ShapeProperties.html + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param bool $line + * @return void + */ + private function writeShape(XMLWriter $xmlWriter, $line = false) + { + $xmlWriter->startElement('c:spPr'); + $xmlWriter->startElement('a:ln'); + if ($line === true) { + $xmlWriter->writeElement('a:solidFill'); + } else { + $xmlWriter->writeElement('a:noFill'); + } + $xmlWriter->endElement(); // a:ln + $xmlWriter->endElement(); // c:spPr + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/ContentTypes.php b/src/PhpWord/Writer/Word2007/Part/ContentTypes.php new file mode 100644 index 00000000..6ae4e875 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/ContentTypes.php @@ -0,0 +1,98 @@ +getParentWriter(); + $contentTypes = $parentWriter->getContentTypes(); + + $openXMLPrefix = 'application/vnd.openxmlformats-'; + $wordMLPrefix = $openXMLPrefix . 'officedocument.wordprocessingml.'; + $drawingMLPrefix = $openXMLPrefix . 'officedocument.drawingml.'; + $overrides = array( + '/docProps/core.xml' => $openXMLPrefix . 'package.core-properties+xml', + '/docProps/app.xml' => $openXMLPrefix . 'officedocument.extended-properties+xml', + '/docProps/custom.xml' => $openXMLPrefix . 'officedocument.custom-properties+xml', + '/word/document.xml' => $wordMLPrefix . 'document.main+xml', + '/word/styles.xml' => $wordMLPrefix . 'styles+xml', + '/word/numbering.xml' => $wordMLPrefix . 'numbering+xml', + '/word/settings.xml' => $wordMLPrefix . 'settings+xml', + '/word/theme/theme1.xml' => $openXMLPrefix . 'officedocument.theme+xml', + '/word/webSettings.xml' => $wordMLPrefix . 'webSettings+xml', + '/word/fontTable.xml' => $wordMLPrefix . 'fontTable+xml', + ); + + $defaults = $contentTypes['default']; + if (!empty($contentTypes['override'])) { + foreach ($contentTypes['override'] as $key => $val) { + if ($val == 'chart') { + $overrides[$key] = $drawingMLPrefix . $val . '+xml'; + } else { + $overrides[$key] = $wordMLPrefix . $val . '+xml'; + } + } + } + + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); + $xmlWriter->startElement('Types'); + $xmlWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/content-types'); + + $this->writeContentType($xmlWriter, $defaults, true); + $this->writeContentType($xmlWriter, $overrides, false); + + $xmlWriter->endElement(); // Types + + return $xmlWriter->getData(); + } + + /** + * Write content types element + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter XML Writer + * @param array $parts + * @param boolean $isDefault + * @return void + */ + private function writeContentType(XMLWriter $xmlWriter, $parts, $isDefault) + { + foreach ($parts as $partName => $contentType) { + $partType = $isDefault ? 'Default' : 'Override'; + $partAttribute = $isDefault ? 'Extension' : 'PartName'; + $xmlWriter->startElement($partType); + $xmlWriter->writeAttribute($partAttribute, $partName); + $xmlWriter->writeAttribute('ContentType', $contentType); + $xmlWriter->endElement(); + } + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/DocPropsApp.php b/src/PhpWord/Writer/Word2007/Part/DocPropsApp.php new file mode 100644 index 00000000..421ceefe --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/DocPropsApp.php @@ -0,0 +1,51 @@ +getParentWriter()->getPhpWord(); + $xmlWriter = $this->getXmlWriter(); + $schema = 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties'; + + $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); + $xmlWriter->startElement('Properties'); + $xmlWriter->writeAttribute('xmlns', $schema); + $xmlWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'); + + $xmlWriter->writeElement('Application', 'PHPWord'); + $xmlWriter->writeElement('Company', $phpWord->getDocInfo()->getCompany()); + $xmlWriter->writeElement('Manager', $phpWord->getDocInfo()->getManager()); + + $xmlWriter->endElement(); // Properties + + return $xmlWriter->getData(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/DocPropsCore.php b/src/PhpWord/Writer/Word2007/Part/DocPropsCore.php new file mode 100644 index 00000000..252be01f --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/DocPropsCore.php @@ -0,0 +1,70 @@ +getParentWriter()->getPhpWord(); + $xmlWriter = $this->getXmlWriter(); + $schema = 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties'; + + $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); + $xmlWriter->startElement('cp:coreProperties'); + $xmlWriter->writeAttribute('xmlns:cp', $schema); + $xmlWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); + $xmlWriter->writeAttribute('xmlns:dcterms', 'http://purl.org/dc/terms/'); + $xmlWriter->writeAttribute('xmlns:dcmitype', 'http://purl.org/dc/dcmitype/'); + $xmlWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); + + $xmlWriter->writeElement('dc:creator', $phpWord->getDocInfo()->getCreator()); + $xmlWriter->writeElement('dc:title', $phpWord->getDocInfo()->getTitle()); + $xmlWriter->writeElement('dc:description', $phpWord->getDocInfo()->getDescription()); + $xmlWriter->writeElement('dc:subject', $phpWord->getDocInfo()->getSubject()); + $xmlWriter->writeElement('cp:keywords', $phpWord->getDocInfo()->getKeywords()); + $xmlWriter->writeElement('cp:category', $phpWord->getDocInfo()->getCategory()); + $xmlWriter->writeElement('cp:lastModifiedBy', $phpWord->getDocInfo()->getLastModifiedBy()); + + // dcterms:created + $xmlWriter->startElement('dcterms:created'); + $xmlWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); + $xmlWriter->writeRaw(date($this->dateFormat, $phpWord->getDocInfo()->getCreated())); + $xmlWriter->endElement(); + + // dcterms:modified + $xmlWriter->startElement('dcterms:modified'); + $xmlWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); + $xmlWriter->writeRaw(date($this->dateFormat, $phpWord->getDocInfo()->getModified())); + $xmlWriter->endElement(); + + $xmlWriter->endElement(); // cp:coreProperties + + return $xmlWriter->getData(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/DocPropsCustom.php b/src/PhpWord/Writer/Word2007/Part/DocPropsCustom.php new file mode 100644 index 00000000..ba6547d9 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/DocPropsCustom.php @@ -0,0 +1,78 @@ +getParentWriter()->getPhpWord(); + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); + $xmlWriter->startElement('Properties'); + $xmlWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/custom-properties'); + $xmlWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'); + + $docProps = $phpWord->getDocInfo(); + $properties = $docProps->getCustomProperties(); + foreach ($properties as $key => $property) { + $propertyValue = $docProps->getCustomPropertyValue($property); + $propertyType = $docProps->getCustomPropertyType($property); + + $xmlWriter->startElement('property'); + $xmlWriter->writeAttribute('fmtid', '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}'); + $xmlWriter->writeAttribute('pid', $key + 2); + $xmlWriter->writeAttribute('name', $property); + switch ($propertyType) { + case 'i': + $xmlWriter->writeElement('vt:i4', $propertyValue); + break; + case 'f': + $xmlWriter->writeElement('vt:r8', $propertyValue); + break; + case 'b': + $xmlWriter->writeElement('vt:bool', ($propertyValue) ? 'true' : 'false'); + break; + case 'd': + $xmlWriter->startElement('vt:filetime'); + $xmlWriter->writeRaw(date($this->dateFormat, $propertyValue)); + $xmlWriter->endElement(); + break; + default: + $xmlWriter->writeElement('vt:lpwstr', $propertyValue); + break; + } + $xmlWriter->endElement(); // property + } + + $xmlWriter->endElement(); // Properties + + return $xmlWriter->getData(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/Document.php b/src/PhpWord/Writer/Word2007/Part/Document.php new file mode 100644 index 00000000..ea607f09 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/Document.php @@ -0,0 +1,138 @@ +getParentWriter()->getPhpWord(); + $xmlWriter = $this->getXmlWriter(); + + $sections = $phpWord->getSections(); + $sectionCount = count($sections); + $currentSection = 0; + $drawingSchema = 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'; + + $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); + $xmlWriter->startElement('w:document'); + $xmlWriter->writeAttribute('xmlns:ve', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); + $xmlWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); + $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $xmlWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math'); + $xmlWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); + $xmlWriter->writeAttribute('xmlns:wp', $drawingSchema); + $xmlWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word'); + $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); + $xmlWriter->writeAttribute('xmlns:wne', 'http://schemas.microsoft.com/office/word/2006/wordml'); + + $xmlWriter->startElement('w:body'); + + + if ($sectionCount > 0) { + foreach ($sections as $section) { + $currentSection++; + + $containerWriter = new Container($xmlWriter, $section); + $containerWriter->write(); + + if ($currentSection == $sectionCount) { + $this->writeSectionSettings($xmlWriter, $section); + } else { + $this->writeSection($xmlWriter, $section); + } + } + } + + $xmlWriter->endElement(); // w:body + $xmlWriter->endElement(); // w:document + + return $xmlWriter->getData(); + } + + /** + * Write begin section. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\Section $section + * @return void + */ + private function writeSection(XMLWriter $xmlWriter, Section $section) + { + $xmlWriter->startElement('w:p'); + $xmlWriter->startElement('w:pPr'); + $this->writeSectionSettings($xmlWriter, $section); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + } + + /** + * Write end section. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\Section $section + * @return void + */ + private function writeSectionSettings(XMLWriter $xmlWriter, Section $section) + { + $xmlWriter->startElement('w:sectPr'); + + // Header reference + foreach ($section->getHeaders() as $header) { + $rId = $header->getRelationId(); + $xmlWriter->startElement('w:headerReference'); + $xmlWriter->writeAttribute('w:type', $header->getType()); + $xmlWriter->writeAttribute('r:id', 'rId' . $rId); + $xmlWriter->endElement(); + } + + // Footer reference + foreach ($section->getFooters() as $footer) { + $rId = $footer->getRelationId(); + $xmlWriter->startElement('w:footerReference'); + $xmlWriter->writeAttribute('w:type', $footer->getType()); + $xmlWriter->writeAttribute('r:id', 'rId' . $rId); + $xmlWriter->endElement(); + } + + // Different first page + if ($section->hasDifferentFirstPage()) { + $xmlWriter->startElement('w:titlePg'); + $xmlWriter->endElement(); + } + + // Section settings + $styleWriter = new SectionStyleWriter($xmlWriter, $section->getStyle()); + $styleWriter->write(); + + $xmlWriter->endElement(); // w:sectPr + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/Endnotes.php b/src/PhpWord/Writer/Word2007/Part/Endnotes.php new file mode 100644 index 00000000..f07bac5f --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/Endnotes.php @@ -0,0 +1,52 @@ +'; + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + + return $str; + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/Footer.php b/src/PhpWord/Writer/Word2007/Part/Footer.php new file mode 100644 index 00000000..db6a2b33 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/Footer.php @@ -0,0 +1,83 @@ +getXmlWriter(); + $drawingSchema = 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'; + + $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); + $xmlWriter->startElement($this->rootElement); + $xmlWriter->writeAttribute('xmlns:ve', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); + $xmlWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); + $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $xmlWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math'); + $xmlWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); + $xmlWriter->writeAttribute('xmlns:wp', $drawingSchema); + $xmlWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word'); + $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); + $xmlWriter->writeAttribute('xmlns:wne', 'http://schemas.microsoft.com/office/word/2006/wordml'); + + $containerWriter = new Container($xmlWriter, $this->element); + $containerWriter->write(); + + $xmlWriter->endElement(); // $this->rootElement + + return $xmlWriter->getData(); + } + + /** + * Set element + * + * @param \PhpOffice\PhpWord\Element\Footer|\PhpOffice\PhpWord\Element\Header $element + * @return self + */ + public function setElement($element) + { + $this->element = $element; + + return $this; + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/Footnotes.php b/src/PhpWord/Writer/Word2007/Part/Footnotes.php new file mode 100644 index 00000000..9ceefd82 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/Footnotes.php @@ -0,0 +1,177 @@ +getXmlWriter(); + $drawingSchema = 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'; + + $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); + $xmlWriter->startElement($this->rootNode); + $xmlWriter->writeAttribute('xmlns:ve', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); + $xmlWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); + $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $xmlWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math'); + $xmlWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); + $xmlWriter->writeAttribute('xmlns:wp', $drawingSchema); + $xmlWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word'); + $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); + $xmlWriter->writeAttribute('xmlns:wne', 'http://schemas.microsoft.com/office/word/2006/wordml'); + + // Separator and continuation separator + $xmlWriter->startElement($this->elementNode); + $xmlWriter->writeAttribute('w:id', -1); + $xmlWriter->writeAttribute('w:type', 'separator'); + $xmlWriter->startElement('w:p'); + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:separator'); + $xmlWriter->endElement(); // w:separator + $xmlWriter->endElement(); // w:r + $xmlWriter->endElement(); // w:p + $xmlWriter->endElement(); // $this->elementNode + $xmlWriter->startElement($this->elementNode); + $xmlWriter->writeAttribute('w:id', 0); + $xmlWriter->writeAttribute('w:type', 'continuationSeparator'); + $xmlWriter->startElement('w:p'); + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:continuationSeparator'); + $xmlWriter->endElement(); // w:continuationSeparator + $xmlWriter->endElement(); // w:r + $xmlWriter->endElement(); // w:p + $xmlWriter->endElement(); // $this->elementNode + + /** @var array $elements Type hint */ + $elements = $this->elements; + foreach ($elements as $element) { + if ($element instanceof Footnote) { + $this->writeNote($xmlWriter, $element); + } + } + + $xmlWriter->endElement(); // $this->rootNode + + return $xmlWriter->getData(); + } + + /** + * Set element + * + * @param \PhpOffice\PhpWord\Collection\Footnotes|\PhpOffice\PhpWord\Collection\Endnotes $elements + * @return self + */ + public function setElements($elements) + { + $this->elements = $elements; + + return $this; + } + + /** + * Write note item. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Element\Footnote|\PhpOffice\PhpWord\Element\Endnote $element + * @return void + */ + protected function writeNote(XMLWriter $xmlWriter, $element) + { + $xmlWriter->startElement($this->elementNode); + $xmlWriter->writeAttribute('w:id', $element->getRelationId()); + $xmlWriter->startElement('w:p'); + + // Paragraph style + $styleWriter = new ParagraphStyleWriter($xmlWriter, $element->getParagraphStyle()); + $styleWriter->setIsInline(true); + $styleWriter->write(); + + // Reference symbol + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:rPr'); + $xmlWriter->startElement('w:rStyle'); + $xmlWriter->writeAttribute('w:val', $this->refStyle); + $xmlWriter->endElement(); // w:rStyle + $xmlWriter->endElement(); // w:rPr + $xmlWriter->writeElement($this->refNode); + $xmlWriter->endElement(); // w:r + + // Empty space after refence symbol + $xmlWriter->startElement('w:r'); + $xmlWriter->startElement('w:t'); + $xmlWriter->writeAttribute('xml:space', 'preserve'); + $xmlWriter->writeRaw(' '); + $xmlWriter->endElement(); // w:t + $xmlWriter->endElement(); // w:r + + $containerWriter = new Container($xmlWriter, $element); + $containerWriter->write(); + + $xmlWriter->endElement(); // w:p + $xmlWriter->endElement(); // $this->elementNode + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/Header.php b/src/PhpWord/Writer/Word2007/Part/Header.php new file mode 100644 index 00000000..638111d7 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/Header.php @@ -0,0 +1,31 @@ +getXmlWriter(); + $styles = Style::getStyles(); + $drawingSchema = 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing'; + + $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); + $xmlWriter->startElement('w:numbering'); + $xmlWriter->writeAttribute('xmlns:ve', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); + $xmlWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); + $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $xmlWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math'); + $xmlWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); + $xmlWriter->writeAttribute('xmlns:wp', $drawingSchema); + $xmlWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word'); + $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); + $xmlWriter->writeAttribute('xmlns:wne', 'http://schemas.microsoft.com/office/word/2006/wordml'); + + // Abstract numbering definitions + foreach ($styles as $style) { + if ($style instanceof NumberingStyle) { + $levels = $style->getLevels(); + + $xmlWriter->startElement('w:abstractNum'); + $xmlWriter->writeAttribute('w:abstractNumId', $style->getIndex()); + + $xmlWriter->startElement('w:nsid'); + $xmlWriter->writeAttribute('w:val', $this->getRandomHexNumber()); + $xmlWriter->endElement(); // w:nsid + + $xmlWriter->startElement('w:multiLevelType'); + $xmlWriter->writeAttribute('w:val', $style->getType()); + $xmlWriter->endElement(); // w:multiLevelType + + if (is_array($levels)) { + foreach ($levels as $level) { + $this->writeLevel($xmlWriter, $level); + } + } + $xmlWriter->endElement(); // w:abstractNum + } + } + + // Numbering definition instances + foreach ($styles as $style) { + if ($style instanceof NumberingStyle) { + $xmlWriter->startElement('w:num'); + $xmlWriter->writeAttribute('w:numId', $style->getIndex()); + $xmlWriter->startElement('w:abstractNumId'); + $xmlWriter->writeAttribute('w:val', $style->getIndex()); + $xmlWriter->endElement(); // w:abstractNumId + $xmlWriter->endElement(); // w:num + } + } + + $xmlWriter->endElement(); // w:numbering + + return $xmlWriter->getData(); + } + + /** + * Write level. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Style\NumberingLevel $level + * @return void + */ + private function writeLevel(XMLWriter $xmlWriter, NumberingLevel $level) + { + $xmlWriter->startElement('w:lvl'); + $xmlWriter->writeAttribute('w:ilvl', $level->getLevel()); + + // Numbering level properties + $properties = array( + 'start' => 'start', + 'format' => 'numFmt', + 'restart' => 'lvlRestart', + 'pStyle' => 'pStyle', + 'suffix' => 'suff', + 'text' => 'lvlText', + 'align' => 'lvlJc' + ); + foreach ($properties as $property => $nodeName) { + $getMethod = "get{$property}"; + if (!is_null($level->$getMethod())) { + $xmlWriter->startElement("w:{$nodeName}"); + $xmlWriter->writeAttribute('w:val', $level->$getMethod()); + $xmlWriter->endElement(); // w:start + } + } + + // Paragraph & font styles + $this->writeParagraph($xmlWriter, $level); + $this->writeFont($xmlWriter, $level); + + $xmlWriter->endElement(); // w:lvl + } + + /** + * Write level paragraph. + * + * @since 0.11.0 + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Style\NumberingLevel $level + * @return void + * @todo Use paragraph style writer + */ + private function writeParagraph(XMLWriter $xmlWriter, NumberingLevel $level) + { + $tabPos = $level->getTabPos(); + $left = $level->getLeft(); + $hanging = $level->getHanging(); + + $xmlWriter->startElement('w:pPr'); + + $xmlWriter->startElement('w:tabs'); + $xmlWriter->startElement('w:tab'); + $xmlWriter->writeAttribute('w:val', 'num'); + $xmlWriter->writeAttributeIf($tabPos !== null, 'w:pos', $tabPos); + $xmlWriter->endElement(); // w:tab + $xmlWriter->endElement(); // w:tabs + + $xmlWriter->startElement('w:ind'); + $xmlWriter->writeAttributeIf($left !== null, 'w:left', $left); + $xmlWriter->writeAttributeIf($hanging !== null, 'w:hanging', $hanging); + $xmlWriter->endElement(); // w:ind + + $xmlWriter->endElement(); // w:pPr + } + + /** + * Write level font. + * + * @since 0.11.0 + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Style\NumberingLevel $level + * @return void + * @todo Use font style writer + */ + private function writeFont(XMLWriter $xmlWriter, NumberingLevel $level) + { + $font = $level->getFont(); + $hint = $level->getHint(); + + $xmlWriter->startElement('w:rPr'); + $xmlWriter->startElement('w:rFonts'); + $xmlWriter->writeAttributeIf($font !== null, 'w:ascii', $font); + $xmlWriter->writeAttributeIf($font !== null, 'w:hAnsi', $font); + $xmlWriter->writeAttributeIf($font !== null, 'w:cs', $font); + $xmlWriter->writeAttributeIf($hint !== null, 'w:hint', $hint); + $xmlWriter->endElement(); // w:rFonts + $xmlWriter->endElement(); // w:rPr + } + + /** + * Get random hexadecimal number value + * + * @param int $length + * @return string + */ + private function getRandomHexNumber($length = 8) + { + return strtoupper(substr(md5(rand()), 0, $length)); + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/Rels.php b/src/PhpWord/Writer/Word2007/Part/Rels.php new file mode 100644 index 00000000..80ab6307 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/Rels.php @@ -0,0 +1,132 @@ + 'package/2006/relationships/metadata/core-properties', + 'docProps/app.xml' => 'officeDocument/2006/relationships/extended-properties', + 'docProps/custom.xml' => 'officeDocument/2006/relationships/custom-properties', + 'word/document.xml' => 'officeDocument/2006/relationships/officeDocument', + ); + $xmlWriter = $this->getXmlWriter(); + $this->writeRels($xmlWriter, $xmlRels); + + return $xmlWriter->getData(); + } + + /** + * Write relationships. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param array $xmlRels + * @param array $mediaRels + * @param int $relId + * @return void + */ + protected function writeRels(XMLWriter $xmlWriter, $xmlRels = array(), $mediaRels = array(), $relId = 1) + { + $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); + $xmlWriter->startElement('Relationships'); + $xmlWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + + // XML files relationships + foreach ($xmlRels as $target => $type) { + $this->writeRel($xmlWriter, $relId++, $type, $target); + } + + // Media relationships + foreach ($mediaRels as $mediaRel) { + $this->writeMediaRel($xmlWriter, $relId++, $mediaRel); + } + + $xmlWriter->endElement(); // Relationships + } + + /** + * Write media relationships. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param int $relId + * @param array $mediaRel + * @return void + */ + private function writeMediaRel(XMLWriter $xmlWriter, $relId, $mediaRel) + { + $typePrefix = 'officeDocument/2006/relationships/'; + $typeMapping = array('image' => 'image', 'object' => 'oleObject', 'link' => 'hyperlink'); + $targetMapping = array('image' => 'media/', 'object' => 'embeddings/'); + + $mediaType = $mediaRel['type']; + $type = array_key_exists($mediaType, $typeMapping) ? $typeMapping[$mediaType] : $mediaType; + $targetPrefix = array_key_exists($mediaType, $targetMapping) ? $targetMapping[$mediaType] : ''; + $target = $mediaRel['target']; + $targetMode = ($type == 'hyperlink') ? 'External' : ''; + + $this->writeRel($xmlWriter, $relId, $typePrefix . $type, $targetPrefix . $target, $targetMode); + } + + /** + * Write individual rels entry. + * + * Format: + * + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param int $relId Relationship ID + * @param string $type Relationship type + * @param string $target Relationship target + * @param string $targetMode Relationship target mode + * @return void + * @throws \PhpOffice\PhpWord\Exception\Exception + */ + private function writeRel(XMLWriter $xmlWriter, $relId, $type, $target, $targetMode = '') + { + if ($type != '' && $target != '') { + if (strpos($relId, 'rId') === false) { + $relId = 'rId' . $relId; + } + $xmlWriter->startElement('Relationship'); + $xmlWriter->writeAttribute('Id', $relId); + $xmlWriter->writeAttribute('Type', 'http://schemas.openxmlformats.org/' . $type); + $xmlWriter->writeAttribute('Target', $target); + if ($targetMode != '') { + $xmlWriter->writeAttribute('TargetMode', $targetMode); + } + $xmlWriter->endElement(); + } else { + throw new Exception("Invalid parameters passed."); + } + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/RelsDocument.php b/src/PhpWord/Writer/Word2007/Part/RelsDocument.php new file mode 100644 index 00000000..744e14f9 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/RelsDocument.php @@ -0,0 +1,50 @@ + 'officeDocument/2006/relationships/styles', + 'numbering.xml' => 'officeDocument/2006/relationships/numbering', + 'settings.xml' => 'officeDocument/2006/relationships/settings', + 'theme/theme1.xml' => 'officeDocument/2006/relationships/theme', + 'webSettings.xml' => 'officeDocument/2006/relationships/webSettings', + 'fontTable.xml' => 'officeDocument/2006/relationships/fontTable', + ); + $xmlWriter = $this->getXmlWriter(); + + /** @var \PhpOffice\PhpWord\Writer\Word2007 $parentWriter Type hint */ + $parentWriter = $this->getParentWriter(); + $this->writeRels($xmlWriter, $xmlRels, $parentWriter->getRelationships()); + + return $xmlWriter->getData(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/RelsPart.php b/src/PhpWord/Writer/Word2007/Part/RelsPart.php new file mode 100644 index 00000000..627a2bcd --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/RelsPart.php @@ -0,0 +1,59 @@ +getXmlWriter(); + $this->writeRels($xmlWriter, array(), $this->media); + + return $xmlWriter->getData(); + } + + /** + * Set media + * + * @param array $media + * @return self + */ + public function setMedia($media) + { + $this->media = $media; + + return $this; + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/Settings.php b/src/PhpWord/Writer/Word2007/Part/Settings.php new file mode 100644 index 00000000..50399c4a --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/Settings.php @@ -0,0 +1,180 @@ +getSettings(); + + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); + $xmlWriter->startElement('w:settings'); + $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); + $xmlWriter->writeAttribute('xmlns:m', 'http://schemas.openxmlformats.org/officeDocument/2006/math'); + $xmlWriter->writeAttribute('xmlns:sl', 'http://schemas.openxmlformats.org/schemaLibrary/2006/main'); + $xmlWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); + $xmlWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); + $xmlWriter->writeAttribute('xmlns:w10', 'urn:schemas-microsoft-com:office:word'); + + foreach ($this->settings as $settingKey => $settingValue) { + $this->writeSetting($xmlWriter, $settingKey, $settingValue); + } + + $xmlWriter->endElement(); // w:settings + + return $xmlWriter->getData(); + } + + /** + * Write indivual setting, recursive to any child settings. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param string $settingKey + * @param array|string $settingValue + * @return void + */ + protected function writeSetting($xmlWriter, $settingKey, $settingValue) + { + if ($settingValue == '') { + $xmlWriter->writeElement($settingKey); + } else { + $xmlWriter->startElement($settingKey); + + /** @var array $settingValue Type hint */ + foreach ($settingValue as $childKey => $childValue) { + if ($childKey == '@attributes') { + foreach ($childValue as $key => $val) { + $xmlWriter->writeAttribute($key, $val); + } + } else { + $this->writeSetting($xmlWriter, $childKey, $childValue); + } + } + $xmlWriter->endElement(); + } + } + + /** + * Get settings. + * + * @return void + */ + private function getSettings() + { + // Default settings + $this->settings = array( + 'w:zoom' => array('@attributes' => array('w:percent' => '100')), + 'w:defaultTabStop' => array('@attributes' => array('w:val' => '708')), + 'w:hyphenationZone' => array('@attributes' => array('w:val' => '425')), + 'w:characterSpacingControl' => array('@attributes' => array('w:val' => 'doNotCompress')), + 'w:themeFontLang' => array('@attributes' => array('w:val' => 'en-US')), + 'w:decimalSymbol' => array('@attributes' => array('w:val' => '.')), + 'w:listSeparator' => array('@attributes' => array('w:val' => ';')), + 'w:compat' => '', + 'm:mathPr' => array( + 'm:mathFont' => array('@attributes' => array('m:val' => 'Cambria Math')), + 'm:brkBin' => array('@attributes' => array('m:val' => 'before')), + 'm:brkBinSub' => array('@attributes' => array('m:val' => '--')), + 'm:smallFrac' => array('@attributes' => array('m:val' => 'off')), + 'm:dispDef' => '', + 'm:lMargin' => array('@attributes' => array('m:val' => '0')), + 'm:rMargin' => array('@attributes' => array('m:val' => '0')), + 'm:defJc' => array('@attributes' => array('m:val' => 'centerGroup')), + 'm:wrapIndent' => array('@attributes' => array('m:val' => '1440')), + 'm:intLim' => array('@attributes' => array('m:val' => 'subSup')), + 'm:naryLim' => array('@attributes' => array('m:val' => 'undOvr')), + ), + 'w:clrSchemeMapping' => array( + '@attributes' => array( + 'w:bg1' => 'light1', + 'w:t1' => 'dark1', + 'w:bg2' => 'light2', + 'w:t2' => 'dark2', + 'w:accent1' => 'accent1', + 'w:accent2' => 'accent2', + 'w:accent3' => 'accent3', + 'w:accent4' => 'accent4', + 'w:accent5' => 'accent5', + 'w:accent6' => 'accent6', + 'w:hyperlink' => 'hyperlink', + 'w:followedHyperlink' => 'followedHyperlink', + ), + ), + ); + + // Other settings + $this->getProtection(); + $this->getCompatibility(); + } + + /** + * Get protection settings. + * + * @return void + */ + private function getProtection() + { + $protection = $this->getParentWriter()->getPhpWord()->getProtection(); + if ($protection->getEditing() !== null) { + $this->settings['w:documentProtection'] = array( + '@attributes' => array( + 'w:enforcement' => 1, + 'w:edit' => $protection->getEditing(), + ) + ); + } + } + + /** + * Get compatibility setting. + * + * @return void + */ + private function getCompatibility() + { + $compatibility = $this->getParentWriter()->getPhpWord()->getCompatibility(); + if ($compatibility->getOoxmlVersion() !== null) { + $this->settings['w:compat']['w:compatSetting'] = array('@attributes' => array( + 'w:name' => 'compatibilityMode', + 'w:uri' => 'http://schemas.microsoft.com/office/word', + 'w:val' => $compatibility->getOoxmlVersion(), + )); + } + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/Styles.php b/src/PhpWord/Writer/Word2007/Part/Styles.php new file mode 100644 index 00000000..6a8de48a --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/Styles.php @@ -0,0 +1,255 @@ +getXmlWriter(); + + $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); + $xmlWriter->startElement('w:styles'); + $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); + + // Write default styles + $styles = Style::getStyles(); + $this->writeDefaultStyles($xmlWriter, $styles); + + // Write styles + if (count($styles) > 0) { + foreach ($styles as $styleName => $style) { + if ($styleName == 'Normal') { + continue; + } + + // Get style class and execute if the private method exists + $styleClass = substr(get_class($style), strrpos(get_class($style), '\\') + 1); + $method = "write{$styleClass}Style"; + if (method_exists($this, $method)) { + $this->$method($xmlWriter, $styleName, $style); + } + } + } + + $xmlWriter->endElement(); // w:styles + + return $xmlWriter->getData(); + } + + /** + * Write default font and other default styles. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Style\AbstractStyle[] $styles + * @return void + */ + private function writeDefaultStyles(XMLWriter $xmlWriter, $styles) + { + $fontName = PhpWordSettings::getDefaultFontName(); + $fontSize = PhpWordSettings::getDefaultFontSize(); + + // Default font + $xmlWriter->startElement('w:docDefaults'); + $xmlWriter->startElement('w:rPrDefault'); + $xmlWriter->startElement('w:rPr'); + $xmlWriter->startElement('w:rFonts'); + $xmlWriter->writeAttribute('w:ascii', $fontName); + $xmlWriter->writeAttribute('w:hAnsi', $fontName); + $xmlWriter->writeAttribute('w:eastAsia', $fontName); + $xmlWriter->writeAttribute('w:cs', $fontName); + $xmlWriter->endElement(); // w:rFonts + $xmlWriter->startElement('w:sz'); + $xmlWriter->writeAttribute('w:val', $fontSize * 2); + $xmlWriter->endElement(); // w:sz + $xmlWriter->startElement('w:szCs'); + $xmlWriter->writeAttribute('w:val', $fontSize * 2); + $xmlWriter->endElement(); // w:szCs + $xmlWriter->endElement(); // w:rPr + $xmlWriter->endElement(); // w:rPrDefault + $xmlWriter->endElement(); // w:docDefaults + + // Normal style + $xmlWriter->startElement('w:style'); + $xmlWriter->writeAttribute('w:type', 'paragraph'); + $xmlWriter->writeAttribute('w:default', '1'); + $xmlWriter->writeAttribute('w:styleId', 'Normal'); + $xmlWriter->startElement('w:name'); + $xmlWriter->writeAttribute('w:val', 'Normal'); + $xmlWriter->endElement(); // w:name + if (array_key_exists('Normal', $styles)) { + $styleWriter = new ParagraphStyleWriter($xmlWriter, $styles['Normal']); + $styleWriter->write(); + } + $xmlWriter->endElement(); // w:style + + // FootnoteReference style + if (!array_key_exists('FootnoteReference', $styles)) { + $xmlWriter->startElement('w:style'); + $xmlWriter->writeAttribute('w:type', 'character'); + $xmlWriter->writeAttribute('w:styleId', 'FootnoteReference'); + $xmlWriter->startElement('w:name'); + $xmlWriter->writeAttribute('w:val', 'Footnote Reference'); + $xmlWriter->endElement(); // w:name + $xmlWriter->writeElement('w:semiHidden'); + $xmlWriter->writeElement('w:unhideWhenUsed'); + $xmlWriter->startElement('w:rPr'); + $xmlWriter->startElement('w:vertAlign'); + $xmlWriter->writeAttribute('w:val', 'superscript'); + $xmlWriter->endElement(); // w:vertAlign + $xmlWriter->endElement(); // w:rPr + $xmlWriter->endElement(); // w:style + } + } + + /** + * Write font style. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param string $styleName + * @param \PhpOffice\PhpWord\Style\Font $style + * @return void + */ + private function writeFontStyle(XMLWriter $xmlWriter, $styleName, FontStyle $style) + { + $paragraphStyle = $style->getParagraph(); + $styleType = $style->getStyleType(); + $type = ($styleType == 'title') ? 'paragraph' : 'character'; + if (!is_null($paragraphStyle)) { + $type = 'paragraph'; + } + + $xmlWriter->startElement('w:style'); + $xmlWriter->writeAttribute('w:type', $type); + + // Heading style + if ($styleType == 'title') { + $arrStyle = explode('_', $styleName); + $styleId = 'Heading' . $arrStyle[1]; + $styleName = 'heading ' . $arrStyle[1]; + $styleLink = 'Heading' . $arrStyle[1] . 'Char'; + $xmlWriter->writeAttribute('w:styleId', $styleId); + + $xmlWriter->startElement('w:link'); + $xmlWriter->writeAttribute('w:val', $styleLink); + $xmlWriter->endElement(); + } + + // Style name + $xmlWriter->startElement('w:name'); + $xmlWriter->writeAttribute('w:val', $styleName); + $xmlWriter->endElement(); + + // Parent style + $xmlWriter->writeElementIf(!is_null($paragraphStyle), 'w:basedOn', 'w:val', 'Normal'); + + // w:pPr + if (!is_null($paragraphStyle)) { + $styleWriter = new ParagraphStyleWriter($xmlWriter, $paragraphStyle); + $styleWriter->write(); + } + + // w:rPr + $styleWriter = new FontStyleWriter($xmlWriter, $style); + $styleWriter->write(); + + $xmlWriter->endElement(); + } + + /** + * Write paragraph style. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param string $styleName + * @param \PhpOffice\PhpWord\Style\Paragraph $style + * @return void + */ + private function writeParagraphStyle(XMLWriter $xmlWriter, $styleName, ParagraphStyle $style) + { + $xmlWriter->startElement('w:style'); + $xmlWriter->writeAttribute('w:type', 'paragraph'); + $xmlWriter->writeAttribute('w:customStyle', '1'); + $xmlWriter->writeAttribute('w:styleId', $styleName); + $xmlWriter->startElement('w:name'); + $xmlWriter->writeAttribute('w:val', $styleName); + $xmlWriter->endElement(); + + // Parent style + $basedOn = $style->getBasedOn(); + $xmlWriter->writeElementIf(!is_null($basedOn), 'w:basedOn', 'w:val', $basedOn); + + // Next paragraph style + $next = $style->getNext(); + $xmlWriter->writeElementIf(!is_null($next), 'w:next', 'w:val', $next); + + // w:pPr + $styleWriter = new ParagraphStyleWriter($xmlWriter, $style); + $styleWriter->write(); + + $xmlWriter->endElement(); + } + + /** + * Write table style. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param string $styleName + * @param \PhpOffice\PhpWord\Style\Table $style + * @return void + */ + private function writeTableStyle(XMLWriter $xmlWriter, $styleName, TableStyle $style) + { + $xmlWriter->startElement('w:style'); + $xmlWriter->writeAttribute('w:type', 'table'); + $xmlWriter->writeAttribute('w:customStyle', '1'); + $xmlWriter->writeAttribute('w:styleId', $styleName); + $xmlWriter->startElement('w:name'); + $xmlWriter->writeAttribute('w:val', $styleName); + $xmlWriter->endElement(); + $xmlWriter->startElement('w:uiPriority'); + $xmlWriter->writeAttribute('w:val', '99'); + $xmlWriter->endElement(); + + $styleWriter = new TableStyleWriter($xmlWriter, $style); + $styleWriter->write(); + + $xmlWriter->endElement(); // w:style + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/Theme.php b/src/PhpWord/Writer/Word2007/Part/Theme.php new file mode 100644 index 00000000..62911c54 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/Theme.php @@ -0,0 +1,423 @@ +'; + $str .= ''; + $str .= ''; + $str .= $this->writeColorScheme(); + $str .= $this->writeFontScheme(); + $str .= $this->writeFormatScheme(); + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + return $str; + } + + + /** + * Write color scheme + * + * @return string + */ + private function writeColorScheme() + { + $str = ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + return $str; + } + + /** + * Write font scheme + * + * @return string + */ + private function writeFontScheme() + { + $str = ''; + + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + $str .= ''; + + return $str; + } + + /** + * Write format scheme + * + * @return string + */ + private function writeFormatScheme() + { + $str = ''; + + $str .= ''; + $str .= $this->writeFormatFill(); + $str .= $this->writeFormatLine(); + $str .= $this->writeFormatEffect(); + $str .= $this->writeFormatBackground(); + $str .= ''; + + return $str; + } + + /** + * Write fill format scheme + * + * @return string + */ + private function writeFormatFill() + { + $str = ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + return $str; + } + + /** + * Write line format scheme + * + * @return string + */ + private function writeFormatLine() + { + $str = ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + return $str; + } + + /** + * Write effect format scheme + * + * @return string + */ + private function writeFormatEffect() + { + $str = ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + return $str; + } + + /** + * Write background format scheme + * + * @return string + */ + private function writeFormatBackground() + { + $str = ''; + + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + $str .= ''; + + return $str; + } +} diff --git a/src/PhpWord/Writer/Word2007/Part/WebSettings.php b/src/PhpWord/Writer/Word2007/Part/WebSettings.php new file mode 100644 index 00000000..f800ebde --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Part/WebSettings.php @@ -0,0 +1,51 @@ + '', + ); + + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); + $xmlWriter->startElement('w:webSettings'); + $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); + + foreach ($settings as $settingKey => $settingValue) { + $this->writeSetting($xmlWriter, $settingKey, $settingValue); + } + + $xmlWriter->endElement(); // w:settings + + return $xmlWriter->getData(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Rels.php b/src/PhpWord/Writer/Word2007/Rels.php deleted file mode 100755 index ab3198dd..00000000 --- a/src/PhpWord/Writer/Word2007/Rels.php +++ /dev/null @@ -1,143 +0,0 @@ - 'package/2006/relationships/metadata/core-properties', - 'docProps/app.xml' => 'officeDocument/2006/relationships/extended-properties', - 'word/document.xml' => 'officeDocument/2006/relationships/officeDocument', - ); - $xmlWriter = $this->getXmlWriter(); - $this->writeRels($xmlWriter, $xmlRels); - - return $xmlWriter->getData(); - } - - /** - * Write word/_rels/document.xml.rels - * - * @param array $mediaRels - */ - public function writeDocRels($mediaRels) - { - $xmlRels = array( - 'styles.xml' => 'officeDocument/2006/relationships/styles', - 'numbering.xml' => 'officeDocument/2006/relationships/numbering', - 'settings.xml' => 'officeDocument/2006/relationships/settings', - 'theme/theme1.xml' => 'officeDocument/2006/relationships/theme', - 'webSettings.xml' => 'officeDocument/2006/relationships/webSettings', - 'fontTable.xml' => 'officeDocument/2006/relationships/fontTable', - ); - $xmlWriter = $this->getXmlWriter(); - $this->writeRels($xmlWriter, $xmlRels, $mediaRels); - - return $xmlWriter->getData(); - } - - /** - * Write word/_rels/(header|footer|footnotes)*.xml.rels - * - * @param array $mediaRels - */ - public function writeMediaRels($mediaRels) - { - $xmlWriter = $this->getXmlWriter(); - $this->writeRels($xmlWriter, null, $mediaRels); - - return $xmlWriter->getData(); - } - - - /** - * Write relationships - * - * @param XMLWriter $xmlWriter - * @param null|array $xmlRels - * @param null|array $mediaRels - * @param integer $id - */ - private function writeRels(XMLWriter $xmlWriter, $xmlRels = null, $mediaRels = null, $id = 1) - { - $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); - $xmlWriter->startElement('Relationships'); - $xmlWriter->writeAttribute('xmlns', self::RELS_BASE . 'package/2006/relationships'); - - // XML files relationships - if (is_array($xmlRels)) { - foreach ($xmlRels as $target => $type) { - $this->writeRel($xmlWriter, $id++, $type, $target); - } - } - - // Media relationships - if (!is_null($mediaRels) && is_array($mediaRels)) { - $mapping = array('image' => 'image', 'object' => 'oleObject', 'link' => 'hyperlink'); - foreach ($mediaRels as $mediaRel) { - $type = $mediaRel['type']; - $type = array_key_exists($type, $mapping) ? $mapping[$type] : $type; - $target = $mediaRel['target']; - $targetMode = ($type == 'hyperlink') ? 'External' : ''; - $this->writeRel($xmlWriter, $id++, "officeDocument/2006/relationships/{$type}", $target, $targetMode); - } - } - $xmlWriter->endElement(); - } - - /** - * Write individual rels entry - * - * Format: - * - * - * @param XMLWriter $xmlWriter - * @param int $id Relationship ID - * @param string $type Relationship type - * @param string $target Relationship target - * @param string $targetMode Relationship target mode - */ - private function writeRel(XMLWriter $xmlWriter, $id, $type, $target, $targetMode = '') - { - if ($type != '' && $target != '') { - if (strpos($id, 'rId') === false) { - $id = 'rId' . $id; - } - $xmlWriter->startElement('Relationship'); - $xmlWriter->writeAttribute('Id', $id); - $xmlWriter->writeAttribute('Type', self::RELS_BASE . $type); - $xmlWriter->writeAttribute('Target', $target); - if ($targetMode != '') { - $xmlWriter->writeAttribute('TargetMode', $targetMode); - } - $xmlWriter->endElement(); - } else { - throw new Exception("Invalid parameters passed."); - } - } -} diff --git a/src/PhpWord/Writer/Word2007/Style/AbstractStyle.php b/src/PhpWord/Writer/Word2007/Style/AbstractStyle.php new file mode 100644 index 00000000..16335680 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/AbstractStyle.php @@ -0,0 +1,142 @@ +xmlWriter = $xmlWriter; + $this->style = $style; + } + + /** + * Get XML Writer + * + * @return \PhpOffice\PhpWord\Shared\XMLWriter + */ + protected function getXmlWriter() + { + return $this->xmlWriter; + } + + /** + * Get Style + * + * @return \PhpOffice\PhpWord\Style\AbstractStyle + */ + protected function getStyle() + { + return $this->style; + } + + /** + * Convert twip value + * + * @param int|float $value + * @param int $default (int|float) + * @return int|float + */ + protected function convertTwip($value, $default = 0) + { + $factors = array( + Settings::UNIT_CM => 567, + Settings::UNIT_MM => 56.7, + Settings::UNIT_INCH => 1440, + Settings::UNIT_POINT => 20, + Settings::UNIT_PICA => 240, + ); + $unit = Settings::getMeasurementUnit(); + $factor = 1; + if (in_array($unit, $factors) && $value != $default) { + $factor = $factors[$unit]; + } + + return $value * $factor; + } + + /** + * Write child style. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param string $name + * @param mixed $value + * @return void + */ + protected function writeChildStyle(XMLWriter $xmlWriter, $name, $value) + { + if ($value !== null) { + $class = "PhpOffice\\PhpWord\\Writer\\Word2007\\Style\\" . $name; + + /** @var \PhpOffice\PhpWord\Writer\Word2007\Style\AbstractStyle $writer */ + $writer = new $class($xmlWriter, $value); + $writer->write(); + } + } + + /** + * Assemble style array into style string + * + * @param array $styles + * @return string + */ + protected function assembleStyle($styles = array()) + { + $style = ''; + foreach ($styles as $key => $value) { + if (!is_null($value) && $value != '') { + $style .= "{$key}:{$value}; "; + } + } + + return trim($style); + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Alignment.php b/src/PhpWord/Writer/Word2007/Style/Alignment.php new file mode 100644 index 00000000..fabaf8ea --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Alignment.php @@ -0,0 +1,46 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Alignment) { + return; + } + $value = $style->getValue(); + if ($value !== null) { + $xmlWriter = $this->getXmlWriter(); + $xmlWriter->startElement('w:jc'); + $xmlWriter->writeAttribute('w:val', $value); + $xmlWriter->endElement(); // w:jc + } + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Cell.php b/src/PhpWord/Writer/Word2007/Style/Cell.php new file mode 100644 index 00000000..0f90b3aa --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Cell.php @@ -0,0 +1,102 @@ +getStyle(); + if (!$style instanceof CellStyle) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement('w:tcPr'); + + // Width + $xmlWriter->startElement('w:tcW'); + $xmlWriter->writeAttribute('w:w', $this->width); + $xmlWriter->writeAttribute('w:type', 'dxa'); + $xmlWriter->endElement(); // w:tcW + + // Text direction + $textDir = $style->getTextDirection(); + $xmlWriter->writeElementIf(!is_null($textDir), 'w:textDirection', 'w:val', $textDir); + + // Vertical alignment + $vAlign = $style->getVAlign(); + $xmlWriter->writeElementIf(!is_null($vAlign), 'w:vAlign', 'w:val', $vAlign); + + // Border + if ($style->hasBorder()) { + $xmlWriter->startElement('w:tcBorders'); + + $styleWriter = new MarginBorder($xmlWriter); + $styleWriter->setSizes($style->getBorderSize()); + $styleWriter->setColors($style->getBorderColor()); + $styleWriter->setAttributes(array('defaultColor' => CellStyle::DEFAULT_BORDER_COLOR)); + $styleWriter->write(); + + $xmlWriter->endElement(); + } + + // Shading + $shading = $style->getShading(); + if (!is_null($shading)) { + $styleWriter = new Shading($xmlWriter, $shading); + $styleWriter->write(); + } + + // Colspan & rowspan + $gridSpan = $style->getGridSpan(); + $vMerge = $style->getVMerge(); + $xmlWriter->writeElementIf(!is_null($gridSpan), 'w:gridSpan', 'w:val', $gridSpan); + $xmlWriter->writeElementIf(!is_null($vMerge), 'w:vMerge', 'w:val', $vMerge); + + $xmlWriter->endElement(); // w:tcPr + } + + /** + * Set width. + * + * @param int $value + * @return void + */ + public function setWidth($value = null) + { + $this->width = $value; + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Extrusion.php b/src/PhpWord/Writer/Word2007/Style/Extrusion.php new file mode 100644 index 00000000..ba1ee590 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Extrusion.php @@ -0,0 +1,46 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Extrusion) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement("o:extrusion"); + $xmlWriter->writeAttribute('on', 't'); + $xmlWriter->writeAttributeIf($style->getType() !== null, 'type', $style->getType()); + $xmlWriter->writeAttributeIf($style->getColor() !== null, 'color', $style->getColor()); + $xmlWriter->endElement(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Fill.php b/src/PhpWord/Writer/Word2007/Style/Fill.php new file mode 100644 index 00000000..645f1ab0 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Fill.php @@ -0,0 +1,43 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Fill) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->writeAttribute('on', 't'); + $xmlWriter->writeAttributeIf($style->getColor() !== null, 'fillcolor', $style->getColor()); + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Font.php b/src/PhpWord/Writer/Word2007/Style/Font.php new file mode 100644 index 00000000..9371f970 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Font.php @@ -0,0 +1,152 @@ +getXmlWriter(); + + $isStyleName = $this->isInline && !is_null($this->style) && is_string($this->style); + if ($isStyleName) { + $xmlWriter->startElement('w:rPr'); + $xmlWriter->startElement('w:rStyle'); + $xmlWriter->writeAttribute('w:val', $this->style); + $xmlWriter->endElement(); + $xmlWriter->endElement(); + } else { + $this->writeStyle(); + } + } + + /** + * Write full style. + * + * @return void + */ + private function writeStyle() + { + $style = $this->getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Font) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement('w:rPr'); + + // Style name + if ($this->isInline === true) { + $styleName = $style->getStyleName(); + $xmlWriter->writeElementIf($styleName !== null, 'w:rStyle', 'w:val', $styleName); + } + + // Font name/family + $font = $style->getName(); + $hint = $style->getHint(); + if ($font !== null) { + $xmlWriter->startElement('w:rFonts'); + $xmlWriter->writeAttribute('w:ascii', $font); + $xmlWriter->writeAttribute('w:hAnsi', $font); + $xmlWriter->writeAttribute('w:eastAsia', $font); + $xmlWriter->writeAttribute('w:cs', $font); + $xmlWriter->writeAttributeIf($hint !== null, 'w:hint', $hint); + $xmlWriter->endElement(); + } + + // Color + $color = $style->getColor(); + $xmlWriter->writeElementIf($color !== null, 'w:color', 'w:val', $color); + + // Size + $size = $style->getSize(); + $xmlWriter->writeElementIf($size !== null, 'w:sz', 'w:val', $size * 2); + $xmlWriter->writeElementIf($size !== null, 'w:szCs', 'w:val', $size * 2); + + // Bold, italic + $xmlWriter->writeElementIf($style->isBold(), 'w:b'); + $xmlWriter->writeElementIf($style->isItalic(), 'w:i'); + $xmlWriter->writeElementIf($style->isItalic(), 'w:iCs'); + + // Strikethrough, double strikethrough + $xmlWriter->writeElementIf($style->isStrikethrough(), 'w:strike'); + $xmlWriter->writeElementIf($style->isDoubleStrikethrough(), 'w:dstrike'); + + // Small caps, all caps + $xmlWriter->writeElementIf($style->isSmallCaps(), 'w:smallCaps'); + $xmlWriter->writeElementIf($style->isAllCaps(), 'w:caps'); + + // Underline + $xmlWriter->writeElementIf($style->getUnderline() != 'none', 'w:u', 'w:val', $style->getUnderline()); + + // Foreground-Color + $xmlWriter->writeElementIf($style->getFgColor() !== null, 'w:highlight', 'w:val', $style->getFgColor()); + + // Superscript/subscript + $xmlWriter->writeElementIf($style->isSuperScript(), 'w:vertAlign', 'w:val', 'superscript'); + $xmlWriter->writeElementIf($style->isSubScript(), 'w:vertAlign', 'w:val', 'subscript'); + + // Spacing + $xmlWriter->writeElementIf($style->getScale() !== null, 'w:w', 'w:val', $style->getScale()); + $xmlWriter->writeElementIf($style->getSpacing() !== null, 'w:spacing', 'w:val', $style->getSpacing()); + $xmlWriter->writeElementIf($style->getKerning() !== null, 'w:kern', 'w:val', $style->getKerning() * 2); + + // Background-Color + $shading = $style->getShading(); + if (!is_null($shading)) { + $styleWriter = new Shading($xmlWriter, $shading); + $styleWriter->write(); + } + + // RTL + if ($this->isInline === true) { + $styleName = $style->getStyleName(); + $xmlWriter->writeElementIf($styleName === null && $style->isRTL(), 'w:rtl'); + } + + $xmlWriter->endElement(); + } + + /** + * Set is inline. + * + * @param bool $value + * @return void + */ + public function setIsInline($value) + { + $this->isInline = $value; + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Frame.php b/src/PhpWord/Writer/Word2007/Style/Frame.php new file mode 100644 index 00000000..2dd61765 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Frame.php @@ -0,0 +1,161 @@ +getStyle(); + if (!$style instanceof FrameStyle) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $zIndices = array(FrameStyle::WRAP_INFRONT => PHP_INT_MAX, FrameStyle::WRAP_BEHIND => -PHP_INT_MAX); + + $properties = array( + 'width' => 'width', + 'height' => 'height', + 'left' => 'margin-left', + 'top' => 'margin-top', + ); + $sizeStyles = $this->getStyles($style, $properties, $style->getUnit()); + + $properties = array( + 'pos' => 'position', + 'hPos' => 'mso-position-horizontal', + 'vPos' => 'mso-position-vertical', + 'hPosRelTo' => 'mso-position-horizontal-relative', + 'vPosRelTo' => 'mso-position-vertical-relative', + ); + $posStyles = $this->getStyles($style, $properties); + + $styles = array_merge($sizeStyles, $posStyles); + + // zIndex for infront & behind wrap + $wrap = $style->getWrap(); + if ($wrap !== null && array_key_exists($wrap, $zIndices)) { + $styles['z-index'] = $zIndices[$wrap]; + $wrap = null; + } + + // Style attribute + $xmlWriter->writeAttribute('style', $this->assembleStyle($styles)); + + $this->writeWrap($xmlWriter, $style, $wrap); + } + + /** + * Write alignment. + * + * @return void + */ + public function writeAlignment() + { + $style = $this->getStyle(); + if (!$style instanceof FrameStyle) { + return; + } + + $xmlWriter = $this->getXmlWriter(); + $xmlWriter->startElement('w:pPr'); + $styleWriter = new Alignment($xmlWriter, new AlignmentStyle(array('value' => $style->getAlign()))); + $styleWriter->write(); + $xmlWriter->endElement(); // w:pPr + } + + /** + * Write alignment. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Style\Frame $style + * @param string $wrap + * @return void + */ + private function writeWrap(XMLWriter $xmlWriter, FrameStyle $style, $wrap) + { + if ($wrap !== null) { + $xmlWriter->startElement('w10:wrap'); + $xmlWriter->writeAttribute('type', $wrap); + + $relativePositions = array( + FrameStyle::POS_RELTO_MARGIN => 'margin', + FrameStyle::POS_RELTO_PAGE => 'page', + FrameStyle::POS_RELTO_TMARGIN => 'margin', + FrameStyle::POS_RELTO_BMARGIN => 'page', + FrameStyle::POS_RELTO_LMARGIN => 'margin', + FrameStyle::POS_RELTO_RMARGIN => 'page', + ); + $pos = $style->getPos(); + $hPos = $style->getHPosRelTo(); + $vPos = $style->getVPosRelTo(); + + if ($pos == FrameStyle::POS_ABSOLUTE) { + $xmlWriter->writeAttribute('anchorx', "page"); + $xmlWriter->writeAttribute('anchory', "page"); + } elseif ($pos == FrameStyle::POS_RELATIVE) { + if (array_key_exists($hPos, $relativePositions)) { + $xmlWriter->writeAttribute('anchorx', $relativePositions[$hPos]); + } + if (array_key_exists($vPos, $relativePositions)) { + $xmlWriter->writeAttribute('anchory', $relativePositions[$vPos]); + } + } + + $xmlWriter->endElement(); // w10:wrap + } + } + + /** + * Get style values in associative array + * + * @param \PhpOffice\PhpWord\Style\Frame $style + * @param array $properties + * @param string $suffix + * @return array + */ + private function getStyles(FrameStyle $style, $properties, $suffix = '') + { + $styles = array(); + + foreach ($properties as $key => $property) { + $method = "get{$key}"; + $value = $style->$method(); + if ($value !== null) { + $styles[$property] = $style->$method() . $suffix; + } + } + + return $styles; + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Image.php b/src/PhpWord/Writer/Word2007/Style/Image.php new file mode 100644 index 00000000..cabf37ce --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Image.php @@ -0,0 +1,27 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Indentation) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement('w:ind'); + + $xmlWriter->writeAttribute('w:left', $this->convertTwip($style->getLeft())); + $xmlWriter->writeAttribute('w:right', $this->convertTwip($style->getRight())); + + $firstLine = $style->getFirstLine(); + $xmlWriter->writeAttributeIf(!is_null($firstLine), 'w:firstLine', $this->convertTwip($firstLine)); + + $hanging = $style->getHanging(); + $xmlWriter->writeAttributeIf(!is_null($hanging), 'w:hanging', $this->convertTwip($hanging)); + + $xmlWriter->endElement(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Line.php b/src/PhpWord/Writer/Word2007/Style/Line.php new file mode 100644 index 00000000..fd1c21de --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Line.php @@ -0,0 +1,71 @@ +getXmlWriter(); + $style = $this->getStyle(); + if (!$style instanceof LineStyle) { + return; + } + + $dash = $style->getDash(); + $dashStyles = array( + LineStyle::DASH_STYLE_DASH => 'dash', + LineStyle::DASH_STYLE_ROUND_DOT => '1 1', + LineStyle::DASH_STYLE_SQUARE_DOT => '1 1', + LineStyle::DASH_STYLE_DASH_DOT => 'dashDot', + LineStyle::DASH_STYLE_LONG_DASH => 'longDash', + LineStyle::DASH_STYLE_LONG_DASH_DOT => 'longDashDot', + LineStyle::DASH_STYLE_LONG_DASH_DOT_DOT => 'longDashDotDot', + ); + + $xmlWriter->startElement('v:stroke'); + + $xmlWriter->writeAttributeIf($style->getWeight() !== null, 'weight', $style->getWeight() . 'pt'); + $xmlWriter->writeAttributeIf($style->getColor() !== null, 'color', $style->getColor()); + $xmlWriter->writeAttributeIf($style->getBeginArrow() !== null, 'startarrow', $style->getBeginArrow()); + $xmlWriter->writeAttributeIf($style->getEndArrow() !== null, 'endarrow', $style->getEndArrow()); + + if ($dash !== null) { + if (array_key_exists($dash, $dashStyles)) { + $xmlWriter->writeAttribute('dashstyle', $dashStyles[$dash]); + } + if ($dash == LineStyle::DASH_STYLE_ROUND_DOT) { + $xmlWriter->writeAttribute('endcap', 'round'); + } + } + + $xmlWriter->endElement(); //v:stroke + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/LineNumbering.php b/src/PhpWord/Writer/Word2007/Style/LineNumbering.php new file mode 100644 index 00000000..d06fa2d6 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/LineNumbering.php @@ -0,0 +1,49 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\LineNumbering) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement('w:lnNumType'); + $xmlWriter->writeAttribute('w:start', $style->getStart() - 1); + $xmlWriter->writeAttribute('w:countBy', $style->getIncrement()); + $xmlWriter->writeAttribute('w:distance', $style->getDistance()); + $xmlWriter->writeAttribute('w:restart', $style->getRestart()); + $xmlWriter->endElement(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/MarginBorder.php b/src/PhpWord/Writer/Word2007/Style/MarginBorder.php new file mode 100644 index 00000000..fb4afede --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/MarginBorder.php @@ -0,0 +1,137 @@ +getXmlWriter(); + + $sides = array('top', 'left', 'right', 'bottom', 'insideH', 'insideV'); + + foreach ($this->sizes as $i => $size) { + if ($size !== null) { + $color = null; + if (isset($this->colors[$i])) { + $color = $this->colors[$i]; + } + $this->writeSide($xmlWriter, $sides[$i], $this->sizes[$i], $color); + } + } + } + + /** + * Write side. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param string $side + * @param int $width + * @param string $color + * @return void + */ + private function writeSide(XMLWriter $xmlWriter, $side, $width, $color = null) + { + $xmlWriter->startElement('w:' . $side); + if (!empty($this->colors)) { + if ($color === null && !empty($this->attributes)) { + if (array_key_exists('defaultColor', $this->attributes)) { + $color = $this->attributes['defaultColor']; + } + } + $xmlWriter->writeAttribute('w:val', 'single'); + $xmlWriter->writeAttribute('w:sz', $width); + $xmlWriter->writeAttribute('w:color', $color); + if (!empty($this->attributes)) { + if (array_key_exists('space', $this->attributes)) { + $xmlWriter->writeAttribute('w:space', $this->attributes['space']); + } + } + } else { + $xmlWriter->writeAttribute('w:w', $width); + $xmlWriter->writeAttribute('w:type', 'dxa'); + } + $xmlWriter->endElement(); + } + + /** + * Set sizes. + * + * @param integer[] $value + * @return void + */ + public function setSizes($value) + { + $this->sizes = $value; + } + + /** + * Set colors. + * + * @param string[] $value + * @return void + */ + public function setColors($value) + { + $this->colors = $value; + } + + /** + * Set attributes. + * + * @param array $value + * @return void + */ + public function setAttributes($value) + { + $this->attributes = $value; + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Outline.php b/src/PhpWord/Writer/Word2007/Style/Outline.php new file mode 100644 index 00000000..06064d18 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Outline.php @@ -0,0 +1,51 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Outline) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement("v:stroke"); + $xmlWriter->writeAttribute('on', 't'); + $xmlWriter->writeAttributeIf($style->getColor() !== null, 'color', $style->getColor()); + $xmlWriter->writeAttributeIf($style->getWeight() !== null, 'weight', $style->getWeight() . $style->getUnit()); + $xmlWriter->writeAttributeIf($style->getDash() !== null, 'dashstyle', $style->getDash()); + $xmlWriter->writeAttributeIf($style->getLine() !== null, 'linestyle', $style->getLine()); + $xmlWriter->writeAttributeIf($style->getEndCap() !== null, 'endcap', $style->getEndCap()); + $xmlWriter->writeAttributeIf($style->getStartArrow() !== null, 'startarrow', $style->getStartArrow()); + $xmlWriter->writeAttributeIf($style->getEndArrow() !== null, 'endarrow', $style->getEndArrow()); + $xmlWriter->endElement(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Paragraph.php b/src/PhpWord/Writer/Word2007/Style/Paragraph.php new file mode 100644 index 00000000..039b78bf --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Paragraph.php @@ -0,0 +1,202 @@ +getXmlWriter(); + + $isStyleName = $this->isInline && !is_null($this->style) && is_string($this->style); + if ($isStyleName) { + if (!$this->withoutPPR) { + $xmlWriter->startElement('w:pPr'); + } + $xmlWriter->startElement('w:pStyle'); + $xmlWriter->writeAttribute('w:val', $this->style); + $xmlWriter->endElement(); + if (!$this->withoutPPR) { + $xmlWriter->endElement(); + } + } else { + $this->writeStyle(); + } + } + + /** + * Write full style. + * + * @return void + */ + private function writeStyle() + { + $style = $this->getStyle(); + if (!$style instanceof ParagraphStyle) { + return; + } + $xmlWriter = $this->getXmlWriter(); + $styles = $style->getStyleValues(); + + if (!$this->withoutPPR) { + $xmlWriter->startElement('w:pPr'); + } + + // Style name + if ($this->isInline === true) { + $xmlWriter->writeElementIf($styles['name'] !== null, 'w:pStyle', 'w:val', $styles['name']); + } + + // Alignment + $styleWriter = new Alignment($xmlWriter, new AlignmentStyle(array('value' => $styles['alignment']))); + $styleWriter->write(); + + // Pagination + $xmlWriter->writeElementIf($styles['pagination']['widowControl'] === false, 'w:widowControl', 'w:val', '0'); + $xmlWriter->writeElementIf($styles['pagination']['keepNext'] === true, 'w:keepNext', 'w:val', '1'); + $xmlWriter->writeElementIf($styles['pagination']['keepLines'] === true, 'w:keepLines', 'w:val', '1'); + $xmlWriter->writeElementIf($styles['pagination']['pageBreak'] === true, 'w:pageBreakBefore', 'w:val', '1'); + + // Child style: indentation, spacing, and shading + $this->writeChildStyle($xmlWriter, 'Indentation', $styles['indentation']); + $this->writeChildStyle($xmlWriter, 'Spacing', $styles['spacing']); + $this->writeChildStyle($xmlWriter, 'Shading', $styles['shading']); + + // Tabs + $this->writeTabs($xmlWriter, $styles['tabs']); + + // Numbering + $this->writeNumbering($xmlWriter, $styles['numbering']); + + // Border + if ($style->hasBorder()) { + $xmlWriter->startElement('w:pBdr'); + + $styleWriter = new MarginBorder($xmlWriter); + $styleWriter->setSizes($style->getBorderSize()); + $styleWriter->setColors($style->getBorderColor()); + $styleWriter->write(); + + $xmlWriter->endElement(); + } + + if (!$this->withoutPPR) { + $xmlWriter->endElement(); // w:pPr + } + } + + /** + * Write tabs. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Style\Tab[] $tabs + * @return void + */ + private function writeTabs(XMLWriter $xmlWriter, $tabs) + { + if (!empty($tabs)) { + $xmlWriter->startElement("w:tabs"); + foreach ($tabs as $tab) { + $styleWriter = new Tab($xmlWriter, $tab); + $styleWriter->write(); + } + $xmlWriter->endElement(); + } + } + + /** + * Write numbering. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param array $numbering + * @return void + */ + private function writeNumbering(XMLWriter $xmlWriter, $numbering) + { + $numStyle = $numbering['style']; + $numLevel = $numbering['level']; + + /** @var \PhpOffice\PhpWord\Style\Numbering $numbering */ + $numbering = Style::getStyle($numStyle); + if ($numStyle !== null && $numbering !== null) { + $xmlWriter->startElement('w:numPr'); + $xmlWriter->startElement('w:numId'); + $xmlWriter->writeAttribute('w:val', $numbering->getIndex()); + $xmlWriter->endElement(); // w:numId + $xmlWriter->startElement('w:ilvl'); + $xmlWriter->writeAttribute('w:val', $numLevel); + $xmlWriter->endElement(); // w:ilvl + $xmlWriter->endElement(); // w:numPr + + $xmlWriter->startElement('w:outlineLvl'); + $xmlWriter->writeAttribute('w:val', $numLevel); + $xmlWriter->endElement(); // w:outlineLvl + } + } + + /** + * Set without w:pPr. + * + * @param bool $value + * @return void + */ + public function setWithoutPPR($value) + { + $this->withoutPPR = $value; + } + + /** + * Set is inline. + * + * @param bool $value + * @return void + */ + public function setIsInline($value) + { + $this->isInline = $value; + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Row.php b/src/PhpWord/Writer/Word2007/Style/Row.php new file mode 100644 index 00000000..98841dd8 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Row.php @@ -0,0 +1,69 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Row) { + return; + } + + $xmlWriter = $this->getXmlWriter(); + $xmlWriter->startElement('w:trPr'); + + if ($this->height !== null) { + $xmlWriter->startElement('w:trHeight'); + $xmlWriter->writeAttribute('w:val', $this->height); + $xmlWriter->writeAttribute('w:hRule', ($style->isExactHeight() ? 'exact' : 'atLeast')); + $xmlWriter->endElement(); + } + $xmlWriter->writeElementIf($style->isTblHeader(), 'w:tblHeader', 'w:val', '1'); + $xmlWriter->writeElementIf($style->isCantSplit(), 'w:cantSplit', 'w:val', '1'); + + $xmlWriter->endElement(); // w:trPr + } + + /** + * Set height. + * + * @param int $value + * @return void + */ + public function setHeight($value = null) + { + $this->height = $value; + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Section.php b/src/PhpWord/Writer/Word2007/Style/Section.php new file mode 100644 index 00000000..486d0ed2 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Section.php @@ -0,0 +1,99 @@ +getStyle(); + if (!$style instanceof SectionStyle) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + // Break type + $breakType = $style->getBreakType(); + $xmlWriter->writeElementIf(!is_null($breakType), 'w:type', 'w:val', $breakType); + + // Page size & orientation + $xmlWriter->startElement('w:pgSz'); + $xmlWriter->writeAttribute('w:orient', $style->getOrientation()); + $xmlWriter->writeAttribute('w:w', $style->getPageSizeW()); + $xmlWriter->writeAttribute('w:h', $style->getPageSizeH()); + $xmlWriter->endElement(); // w:pgSz + + // Margins + $margins = array( + 'w:top' => array('getMarginTop', SectionStyle::DEFAULT_MARGIN), + 'w:right' => array('getMarginRight', SectionStyle::DEFAULT_MARGIN), + 'w:bottom' => array('getMarginBottom', SectionStyle::DEFAULT_MARGIN), + 'w:left' => array('getMarginLeft', SectionStyle::DEFAULT_MARGIN), + 'w:header' => array('getHeaderHeight', SectionStyle::DEFAULT_HEADER_HEIGHT), + 'w:footer' => array('getFooterHeight', SectionStyle::DEFAULT_FOOTER_HEIGHT), + 'w:gutter' => array('getGutter', SectionStyle::DEFAULT_GUTTER), + ); + $xmlWriter->startElement('w:pgMar'); + foreach ($margins as $attribute => $value) { + list($method, $default) = $value; + $xmlWriter->writeAttribute($attribute, $this->convertTwip($style->$method(), $default)); + } + $xmlWriter->endElement(); + + // Borders + if ($style->hasBorder()) { + $xmlWriter->startElement('w:pgBorders'); + $xmlWriter->writeAttribute('w:offsetFrom', 'page'); + + $styleWriter = new MarginBorder($xmlWriter); + $styleWriter->setSizes($style->getBorderSize()); + $styleWriter->setColors($style->getBorderColor()); + $styleWriter->setAttributes(array('space' => '24')); + $styleWriter->write(); + + $xmlWriter->endElement(); + } + + // Columns + $colsSpace = $style->getColsSpace(); + $xmlWriter->startElement('w:cols'); + $xmlWriter->writeAttribute('w:num', $style->getColsNum()); + $xmlWriter->writeAttribute('w:space', $this->convertTwip($colsSpace, SectionStyle::DEFAULT_COLUMN_SPACING)); + $xmlWriter->endElement(); + + // Page numbering start + $pageNum = $style->getPageNumberingStart(); + $xmlWriter->writeElementIf(!is_null($pageNum), 'w:pgNumType', 'w:start', $pageNum); + + // Line numbering + $styleWriter = new LineNumbering($xmlWriter, $style->getLineNumbering()); + $styleWriter->write(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Shading.php b/src/PhpWord/Writer/Word2007/Style/Shading.php new file mode 100644 index 00000000..8ef8c6b1 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Shading.php @@ -0,0 +1,46 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Shading) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement('w:shd'); + $xmlWriter->writeAttribute('w:val', $style->getPattern()); + $xmlWriter->writeAttribute('w:color', $style->getColor()); + $xmlWriter->writeAttribute('w:fill', $style->getFill()); + $xmlWriter->endElement(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Shadow.php b/src/PhpWord/Writer/Word2007/Style/Shadow.php new file mode 100644 index 00000000..cc746059 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Shadow.php @@ -0,0 +1,46 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Shadow) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement("v:shadow"); + $xmlWriter->writeAttribute('on', 't'); + $xmlWriter->writeAttributeIf($style->getColor() !== null, 'color', $style->getColor()); + $xmlWriter->writeAttributeIf($style->getOffset() !== null, 'offset', $style->getOffset()); + $xmlWriter->endElement(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Shape.php b/src/PhpWord/Writer/Word2007/Style/Shape.php new file mode 100644 index 00000000..ba8dce5b --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Shape.php @@ -0,0 +1,47 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Shape) { + return; + } + + $xmlWriter = $this->getXmlWriter(); + + $childStyles = array('Frame', 'Fill', 'Outline', 'Shadow', 'Extrusion'); + foreach ($childStyles as $childStyle) { + $method = "get{$childStyle}"; + $this->writeChildStyle($xmlWriter, $childStyle, $style->$method()); + } + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Spacing.php b/src/PhpWord/Writer/Word2007/Style/Spacing.php new file mode 100644 index 00000000..2f7e122a --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Spacing.php @@ -0,0 +1,55 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Spacing) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement('w:spacing'); + + $before = $style->getBefore(); + $xmlWriter->writeAttributeIf(!is_null($before), 'w:before', $this->convertTwip($before)); + + $after = $style->getAfter(); + $xmlWriter->writeAttributeIf(!is_null($after), 'w:after', $this->convertTwip($after)); + + $line = $style->getLine(); + $xmlWriter->writeAttributeIf(!is_null($line), 'w:line', $line); + + $xmlWriter->writeAttributeIf(!is_null($line), 'w:lineRule', $style->getRule()); + + $xmlWriter->endElement(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Tab.php b/src/PhpWord/Writer/Word2007/Style/Tab.php new file mode 100644 index 00000000..aa00acc7 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Tab.php @@ -0,0 +1,46 @@ +getStyle(); + if (!$style instanceof \PhpOffice\PhpWord\Style\Tab) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement("w:tab"); + $xmlWriter->writeAttribute("w:val", $style->getType()); + $xmlWriter->writeAttribute("w:leader", $style->getLeader()); + $xmlWriter->writeAttribute('w:pos', $this->convertTwip($style->getPosition())); + $xmlWriter->endElement(); + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/Table.php b/src/PhpWord/Writer/Word2007/Style/Table.php new file mode 100644 index 00000000..8bbad107 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/Table.php @@ -0,0 +1,197 @@ +getStyle(); + $xmlWriter = $this->getXmlWriter(); + + if ($style instanceof TableStyle) { + $this->writeStyle($xmlWriter, $style); + } elseif (is_string($style)) { + $xmlWriter->startElement('w:tblPr'); + $xmlWriter->startElement('w:tblStyle'); + $xmlWriter->writeAttribute('w:val', $style); + $xmlWriter->endElement(); + if ($this->width !== null) { + $this->writeWidth($xmlWriter, $this->width, 'pct'); + } + $xmlWriter->endElement(); + } + } + + /** + * Write full style. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Style\Table $style + * @return void + */ + private function writeStyle(XMLWriter $xmlWriter, TableStyle $style) + { + // w:tblPr + $xmlWriter->startElement('w:tblPr'); + + // Alignment + $styleWriter = new Alignment($xmlWriter, new AlignmentStyle(array('value' => $style->getAlign()))); + $styleWriter->write(); + + $this->writeWidth($xmlWriter, $style->getWidth(), $style->getUnit()); + $this->writeMargin($xmlWriter, $style); + $this->writeBorder($xmlWriter, $style); + + $xmlWriter->endElement(); // w:tblPr + + $this->writeShading($xmlWriter, $style); + + // First row style + $firstRow = $style->getFirstRow(); + if ($firstRow instanceof TableStyle) { + $this->writeFirstRow($xmlWriter, $firstRow); + } + } + + /** + * Write width. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param int $width + * @param string $unit + * @return void + */ + private function writeWidth(XMLWriter $xmlWriter, $width, $unit) + { + $xmlWriter->startElement('w:tblW'); + $xmlWriter->writeAttribute('w:w', $width); + $xmlWriter->writeAttribute('w:type', $unit); + $xmlWriter->endElement(); // w:tblW + } + + /** + * Write margin. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Style\Table $style + * @return void + */ + private function writeMargin(XMLWriter $xmlWriter, TableStyle $style) + { + if ($style->hasMargin()) { + $xmlWriter->startElement('w:tblCellMar'); + + $styleWriter = new MarginBorder($xmlWriter); + $styleWriter->setSizes($style->getCellMargin()); + $styleWriter->write(); + + $xmlWriter->endElement(); // w:tblCellMar + } + } + + /** + * Write border. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Style\Table $style + * @return void + */ + private function writeBorder(XMLWriter $xmlWriter, TableStyle $style) + { + if ($style->hasBorder()) { + $xmlWriter->startElement('w:tblBorders'); + + $styleWriter = new MarginBorder($xmlWriter); + $styleWriter->setSizes($style->getBorderSize()); + $styleWriter->setColors($style->getBorderColor()); + $styleWriter->write(); + + $xmlWriter->endElement(); // w:tblBorders + } + } + + /** + * Write row style. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Style\Table $style + * @return void + */ + private function writeFirstRow(XMLWriter $xmlWriter, TableStyle $style) + { + $xmlWriter->startElement('w:tblStylePr'); + $xmlWriter->writeAttribute('w:type', 'firstRow'); + $xmlWriter->startElement('w:tcPr'); + + $this->writeBorder($xmlWriter, $style); + $this->writeShading($xmlWriter, $style); + + $xmlWriter->endElement(); // w:tcPr + $xmlWriter->endElement(); // w:tblStylePr + } + + /** + * Write shading. + * + * @param \PhpOffice\PhpWord\Shared\XMLWriter $xmlWriter + * @param \PhpOffice\PhpWord\Style\Table $style + * @return void + */ + private function writeShading(XMLWriter $xmlWriter, TableStyle $style) + { + if ($style->getShading() !== null) { + $xmlWriter->startElement('w:tcPr'); + + $styleWriter = new Shading($xmlWriter, $style->getShading()); + $styleWriter->write(); + + $xmlWriter->endElement(); + } + } + + /** + * Set width. + * + * @param int $value + * @return void + */ + public function setWidth($value = null) + { + $this->width = $value; + } +} diff --git a/src/PhpWord/Writer/Word2007/Style/TextBox.php b/src/PhpWord/Writer/Word2007/Style/TextBox.php new file mode 100644 index 00000000..20c68c74 --- /dev/null +++ b/src/PhpWord/Writer/Word2007/Style/TextBox.php @@ -0,0 +1,65 @@ +getStyle(); + if (!$style instanceof TextBoxStyle || !$style->hasInnerMargins()) { + return; + } + + $xmlWriter = $this->getXmlWriter(); + $margins = implode(', ', $style->getInnerMargin()); + + $xmlWriter->writeAttribute('inset', $margins); + } + + /** + * Writer border. + * + * @return void + */ + public function writeBorder() + { + $style = $this->getStyle(); + if (!$style instanceof TextBoxStyle) { + return; + } + $xmlWriter = $this->getXmlWriter(); + + $xmlWriter->startElement('v:stroke'); + $xmlWriter->writeAttributeIf($style->getBorderSize() !== null, 'weight', $style->getBorderSize() . 'pt'); + $xmlWriter->writeAttributeIf($style->getBorderColor() !== null, 'color', $style->getBorderColor()); + $xmlWriter->endElement(); // v:stroke + } +} diff --git a/src/PhpWord/Writer/Word2007/Styles.php b/src/PhpWord/Writer/Word2007/Styles.php deleted file mode 100644 index 38217847..00000000 --- a/src/PhpWord/Writer/Word2007/Styles.php +++ /dev/null @@ -1,206 +0,0 @@ -getXmlWriter(); - - // XML header - $xmlWriter->startDocument('1.0', 'UTF-8', 'yes'); - $xmlWriter->startElement('w:styles'); - $xmlWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - $xmlWriter->writeAttribute('xmlns:w', 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'); - - // Write default styles - $styles = Style::getStyles(); - $this->writeDefaultStyles($xmlWriter, $phpWord, $styles); - - // Write styles - if (count($styles) > 0) { - foreach ($styles as $styleName => $style) { - if ($styleName == 'Normal') { - continue; - } - - // Font style - if ($style instanceof Font) { - $paragraphStyle = $style->getParagraphStyle(); - $styleType = $style->getStyleType(); - $type = ($styleType == 'title') ? 'paragraph' : 'character'; - if (!is_null($paragraphStyle)) { - $type = 'paragraph'; - } - - $xmlWriter->startElement('w:style'); - $xmlWriter->writeAttribute('w:type', $type); - if ($styleType == 'title') { - $arrStyle = explode('_', $styleName); - $styleId = 'Heading' . $arrStyle[1]; - $styleName = 'heading ' . $arrStyle[1]; - $styleLink = 'Heading' . $arrStyle[1] . 'Char'; - $xmlWriter->writeAttribute('w:styleId', $styleId); - - $xmlWriter->startElement('w:link'); - $xmlWriter->writeAttribute('w:val', $styleLink); - $xmlWriter->endElement(); - } - $xmlWriter->startElement('w:name'); - $xmlWriter->writeAttribute('w:val', $styleName); - $xmlWriter->endElement(); - if (!is_null($paragraphStyle)) { - // Point parent style to Normal - $xmlWriter->startElement('w:basedOn'); - $xmlWriter->writeAttribute('w:val', 'Normal'); - $xmlWriter->endElement(); - $this->writeParagraphStyle($xmlWriter, $paragraphStyle); - } - - $this->writeFontStyle($xmlWriter, $style); - $xmlWriter->endElement(); - - // Paragraph style - } elseif ($style instanceof Paragraph) { - $xmlWriter->startElement('w:style'); - $xmlWriter->writeAttribute('w:type', 'paragraph'); - $xmlWriter->writeAttribute('w:customStyle', '1'); - $xmlWriter->writeAttribute('w:styleId', $styleName); - $xmlWriter->startElement('w:name'); - $xmlWriter->writeAttribute('w:val', $styleName); - $xmlWriter->endElement(); - // Parent style - $basedOn = $style->getBasedOn(); - if (!is_null($basedOn)) { - $xmlWriter->startElement('w:basedOn'); - $xmlWriter->writeAttribute('w:val', $basedOn); - $xmlWriter->endElement(); - } - // Next paragraph style - $next = $style->getNext(); - if (!is_null($next)) { - $xmlWriter->startElement('w:next'); - $xmlWriter->writeAttribute('w:val', $next); - $xmlWriter->endElement(); - } - - $this->writeParagraphStyle($xmlWriter, $style); - $xmlWriter->endElement(); - - // Table style - } elseif ($style instanceof Table) { - $xmlWriter->startElement('w:style'); - $xmlWriter->writeAttribute('w:type', 'table'); - $xmlWriter->writeAttribute('w:customStyle', '1'); - $xmlWriter->writeAttribute('w:styleId', $styleName); - $xmlWriter->startElement('w:name'); - $xmlWriter->writeAttribute('w:val', $styleName); - $xmlWriter->endElement(); - $xmlWriter->startElement('w:uiPriority'); - $xmlWriter->writeAttribute('w:val', '99'); - $xmlWriter->endElement(); - - $this->writeTableStyle($xmlWriter, $style); - $xmlWriter->endElement(); // w:style - } - } - } - - $xmlWriter->endElement(); // w:styles - - return $xmlWriter->getData(); - } - - /** - * Write default font and other default styles - * - * @param XMLWriter $xmlWriter - * @param array $styles - */ - private function writeDefaultStyles(XMLWriter $xmlWriter, PhpWord $phpWord, $styles) - { - $fontName = $phpWord->getDefaultFontName(); - $fontSize = $phpWord->getDefaultFontSize(); - - // Default font - $xmlWriter->startElement('w:docDefaults'); - $xmlWriter->startElement('w:rPrDefault'); - $xmlWriter->startElement('w:rPr'); - $xmlWriter->startElement('w:rFonts'); - $xmlWriter->writeAttribute('w:ascii', $fontName); - $xmlWriter->writeAttribute('w:hAnsi', $fontName); - $xmlWriter->writeAttribute('w:eastAsia', $fontName); - $xmlWriter->writeAttribute('w:cs', $fontName); - $xmlWriter->endElement(); // w:rFonts - $xmlWriter->startElement('w:sz'); - $xmlWriter->writeAttribute('w:val', $fontSize * 2); - $xmlWriter->endElement(); // w:sz - $xmlWriter->startElement('w:szCs'); - $xmlWriter->writeAttribute('w:val', $fontSize * 2); - $xmlWriter->endElement(); // w:szCs - $xmlWriter->endElement(); // w:rPr - $xmlWriter->endElement(); // w:rPrDefault - $xmlWriter->endElement(); // w:docDefaults - - // Normal style - $xmlWriter->startElement('w:style'); - $xmlWriter->writeAttribute('w:type', 'paragraph'); - $xmlWriter->writeAttribute('w:default', '1'); - $xmlWriter->writeAttribute('w:styleId', 'Normal'); - $xmlWriter->startElement('w:name'); - $xmlWriter->writeAttribute('w:val', 'Normal'); - $xmlWriter->endElement(); // w:name - if (array_key_exists('Normal', $styles)) { - $this->writeParagraphStyle($xmlWriter, $styles['Normal']); - } - $xmlWriter->endElement(); // w:style - - // FootnoteReference style - if (!array_key_exists('FootnoteReference', $styles)) { - $xmlWriter->startElement('w:style'); - $xmlWriter->writeAttribute('w:type', 'character'); - $xmlWriter->writeAttribute('w:styleId', 'FootnoteReference'); - $xmlWriter->startElement('w:name'); - $xmlWriter->writeAttribute('w:val', 'Footnote Reference'); - $xmlWriter->endElement(); // w:name - $xmlWriter->writeElement('w:semiHidden'); - $xmlWriter->writeElement('w:unhideWhenUsed'); - $xmlWriter->startElement('w:rPr'); - $xmlWriter->startElement('w:vertAlign'); - $xmlWriter->writeAttribute('w:val', 'superscript'); - $xmlWriter->endElement(); // w:vertAlign - $xmlWriter->endElement(); // w:rPr - $xmlWriter->endElement(); // w:style - } - } -} diff --git a/src/PhpWord/Writer/WriterInterface.php b/src/PhpWord/Writer/WriterInterface.php old mode 100755 new mode 100644 index 2c225b2c..eda99f27 --- a/src/PhpWord/Writer/WriterInterface.php +++ b/src/PhpWord/Writer/WriterInterface.php @@ -1,10 +1,18 @@ - \ No newline at end of file diff --git a/src/PhpWord/_staticDocParts/settings.xml b/src/PhpWord/_staticDocParts/settings.xml deleted file mode 100644 index 5eb22891..00000000 --- a/src/PhpWord/_staticDocParts/settings.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/PhpWord/_staticDocParts/theme1.xml b/src/PhpWord/_staticDocParts/theme1.xml deleted file mode 100644 index 4fab507b..00000000 --- a/src/PhpWord/_staticDocParts/theme1.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/src/PhpWord/_staticDocParts/webSettings.xml b/src/PhpWord/_staticDocParts/webSettings.xml deleted file mode 100644 index 72d28307..00000000 --- a/src/PhpWord/_staticDocParts/webSettings.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/src/PhpWord/_staticDocParts/_doc.png b/src/PhpWord/resources/doc.png similarity index 100% rename from src/PhpWord/_staticDocParts/_doc.png rename to src/PhpWord/resources/doc.png diff --git a/src/PhpWord/_staticDocParts/_ppt.png b/src/PhpWord/resources/ppt.png similarity index 100% rename from src/PhpWord/_staticDocParts/_ppt.png rename to src/PhpWord/resources/ppt.png diff --git a/src/PhpWord/_staticDocParts/_xls.png b/src/PhpWord/resources/xls.png similarity index 100% rename from src/PhpWord/_staticDocParts/_xls.png rename to src/PhpWord/resources/xls.png diff --git a/tests/PhpWord/Tests/AutoloaderTest.php b/tests/PhpWord/Tests/AutoloaderTest.php index 2a021aeb..dace5bdb 100644 --- a/tests/PhpWord/Tests/AutoloaderTest.php +++ b/tests/PhpWord/Tests/AutoloaderTest.php @@ -1,10 +1,18 @@ assertEquals( + $this->assertCount( $declaredCount, - count(get_declared_classes()), + get_declared_classes(), 'PhpOffice\\PhpWord\\Autoloader::autoload() is trying to load ' . 'classes outside of the PhpOffice\\PhpWord namespace' ); diff --git a/tests/PhpWord/Tests/Collection/CollectionTest.php b/tests/PhpWord/Tests/Collection/CollectionTest.php new file mode 100644 index 00000000..833b3e80 --- /dev/null +++ b/tests/PhpWord/Tests/Collection/CollectionTest.php @@ -0,0 +1,39 @@ +addItem(new Footnote()); // addItem #1 + + $this->assertEquals(2, $object->addItem(new Footnote())); // addItem #2. Should returns new item index + $this->assertCount(2, $object->getItems()); // getItems returns array + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Footnote', $object->getItem(1)); // getItem returns object + $this->assertNull($object->getItem(3)); // getItem returns null when invalid index is referenced + + $object->setItem(2, null); // Set item #2 to null + + $this->assertNull($object->getItem(2)); // Check if it's null + } +} diff --git a/tests/PhpWord/Tests/Element/AbstractElementTest.php b/tests/PhpWord/Tests/Element/AbstractElementTest.php index 8dbfb5b3..180dd4d0 100644 --- a/tests/PhpWord/Tests/Element/AbstractElementTest.php +++ b/tests/PhpWord/Tests/Element/AbstractElementTest.php @@ -1,18 +1,24 @@ assertInstanceOf('PhpOffice\\PhpWord\\Element\\Cell', $oCell); $this->assertEquals($oCell->getWidth(), null); @@ -35,8 +42,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testConstructWithStyleArray() { - $iVal = rand(1, 1000); - $oCell = new Cell('section', $iVal, null, array('valign' => 'center')); + $oCell = new Cell(null, array('valign' => 'center')); $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\Cell', $oCell->getStyle()); $this->assertEquals($oCell->getWidth(), null); @@ -47,7 +53,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddText() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addText('text'); $this->assertCount(1, $oCell->getElements()); @@ -59,7 +65,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddTextNotUTF8() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addText(utf8_decode('ééé')); $this->assertCount(1, $oCell->getElements()); @@ -72,7 +78,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddLink() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addLink(utf8_decode('ééé'), utf8_decode('ééé')); $this->assertCount(1, $oCell->getElements()); @@ -84,7 +90,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddTextBreak() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $oCell->addTextBreak(); $this->assertCount(1, $oCell->getElements()); @@ -95,7 +101,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddListItem() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addListItem('text'); $this->assertCount(1, $oCell->getElements()); @@ -108,7 +114,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddListItemNotUTF8() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addListItem(utf8_decode('ééé')); $this->assertCount(1, $oCell->getElements()); @@ -122,7 +128,7 @@ class CellTest extends \PHPUnit_Framework_TestCase public function testAddImageSection() { $src = __DIR__ . "/../_files/images/earth.jpg"; - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addImage($src); $this->assertCount(1, $oCell->getElements()); @@ -160,37 +166,9 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddImageSectionByUrl() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addImage( - 'https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png' - ); - - $this->assertCount(1, $oCell->getElements()); - $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Image', $element); - } - - /** - * Add image header by URL - */ - public function testAddImageHeaderByUrl() - { - $oCell = new Cell('header', 1); - $element = $oCell->addImage( - 'https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png' - ); - - $this->assertCount(1, $oCell->getElements()); - $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Image', $element); - } - - /** - * Add image footer by URL - */ - public function testAddImageFooterByUrl() - { - $oCell = new Cell('footer', 1); - $element = $oCell->addImage( - 'https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png' + 'http://php.net/images/logos/php-med-trans-light.gif' ); $this->assertCount(1, $oCell->getElements()); @@ -203,7 +181,7 @@ class CellTest extends \PHPUnit_Framework_TestCase public function testAddObjectXLS() { $src = __DIR__ . "/../_files/documents/sheet.xls"; - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addObject($src); $this->assertCount(1, $oCell->getElements()); @@ -218,8 +196,8 @@ class CellTest extends \PHPUnit_Framework_TestCase public function testAddObjectException() { $src = __DIR__ . "/../_files/xsl/passthrough.xsl"; - $oCell = new Cell('section', 1); - $element = $oCell->addObject($src); + $oCell = new Cell(); + $oCell->addObject($src); } /** @@ -227,7 +205,8 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddPreserveText() { - $oCell = new Cell('header', 1); + $oCell = new Cell(); + $oCell->setDocPart('Header', 1); $element = $oCell->addPreserveText('text'); $this->assertCount(1, $oCell->getElements()); @@ -239,7 +218,8 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddPreserveTextNotUTF8() { - $oCell = new Cell('header', 1); + $oCell = new Cell(); + $oCell->setDocPart('Header', 1); $element = $oCell->addPreserveText(utf8_decode('ééé')); $this->assertCount(1, $oCell->getElements()); @@ -254,8 +234,9 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddPreserveTextException() { - $oCell = new Cell('section', 1); - $element = $oCell->addPreserveText('text'); + $oCell = new Cell(); + $oCell->setDocPart('Section', 1); + $oCell->addPreserveText('text'); } /** @@ -263,7 +244,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testCreateTextRun() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addTextRun(); $this->assertCount(1, $oCell->getElements()); @@ -275,7 +256,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testAddCheckBox() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $element = $oCell->addCheckBox(utf8_decode('ééé'), utf8_decode('ééé')); $this->assertCount(1, $oCell->getElements()); @@ -287,7 +268,7 @@ class CellTest extends \PHPUnit_Framework_TestCase */ public function testGetElements() { - $oCell = new Cell('section', 1); + $oCell = new Cell(); $this->assertInternalType('array', $oCell->getElements()); } diff --git a/tests/PhpWord/Tests/Element/CheckBoxTest.php b/tests/PhpWord/Tests/Element/CheckBoxTest.php index e4611618..8f7bf3cd 100644 --- a/tests/PhpWord/Tests/Element/CheckBoxTest.php +++ b/tests/PhpWord/Tests/Element/CheckBoxTest.php @@ -1,10 +1,18 @@ assertInstanceOf('PhpOffice\\PhpWord\\Element\\Field', $oField); + } + + /** + * New instance with type + */ + public function testConstructWithType() + { + $oField = new Field('DATE'); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Field', $oField); + $this->assertEquals($oField->getType(), 'DATE'); + } + + /** + * New instance with type and properties + */ + public function testConstructWithTypeProperties() + { + $oField = new Field('DATE', array('dateformat'=>'d-M-yyyy')); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Field', $oField); + $this->assertEquals($oField->getType(), 'DATE'); + $this->assertEquals($oField->getProperties(), array('dateformat'=>'d-M-yyyy')); + } + + /** + * New instance with type and properties and options + */ + public function testConstructWithTypePropertiesOptions() + { + $oField = new Field('DATE', array('dateformat'=>'d-M-yyyy'), array('SakaEraCalendar', 'PreserveFormat')); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Field', $oField); + $this->assertEquals($oField->getType(), 'DATE'); + $this->assertEquals($oField->getProperties(), array('dateformat'=>'d-M-yyyy')); + $this->assertEquals($oField->getOptions(), array('SakaEraCalendar', 'PreserveFormat')); + } + + /** + * Test setType exception + * + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Invalid type + */ + public function testSetTypeException() + { + $object = new Field(); + $object->setType('foo'); + } + + /** + * Test setProperties exception + * + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Invalid property + */ + public function testSetPropertiesException() + { + $object = new Field('PAGE'); + $object->setProperties(array('foo' => 'bar')); + } + + /** + * Test setOptions exception + * + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Invalid option + */ + public function testSetOptionsException() + { + $object = new Field('PAGE'); + $object->setOptions(array('foo' => 'bar')); + } +} diff --git a/tests/PhpWord/Tests/Element/FooterTest.php b/tests/PhpWord/Tests/Element/FooterTest.php index d4201149..c5d04b41 100644 --- a/tests/PhpWord/Tests/Element/FooterTest.php +++ b/tests/PhpWord/Tests/Element/FooterTest.php @@ -1,10 +1,18 @@ addImage( - 'https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png' + 'http://php.net/images/logos/php-med-trans-light.gif' ); $this->assertCount(1, $oFooter->getElements()); diff --git a/tests/PhpWord/Tests/Element/FootnoteTest.php b/tests/PhpWord/Tests/Element/FootnoteTest.php index c2571afe..2ba015d7 100644 --- a/tests/PhpWord/Tests/Element/FootnoteTest.php +++ b/tests/PhpWord/Tests/Element/FootnoteTest.php @@ -1,10 +1,18 @@ addImage( - 'https://assets.mozillalabs.com/Brands-Logos/Thunderbird/logo-only/thunderbird_logo-only_RGB.png' + 'http://php.net/images/logos/php-med-trans-light.gif' ); $this->assertCount(1, $oHeader->getElements()); diff --git a/tests/PhpWord/Tests/Element/ImageTest.php b/tests/PhpWord/Tests/Element/ImageTest.php index 6ec6743a..11b33d87 100644 --- a/tests/PhpWord/Tests/Element/ImageTest.php +++ b/tests/PhpWord/Tests/Element/ImageTest.php @@ -1,10 +1,18 @@ assertInstanceOf('PhpOffice\\PhpWord\\Element\\Image', $oImage); $this->assertEquals($oImage->getSource(), $src); $this->assertEquals($oImage->getMediaId(), md5($src)); - $this->assertEquals($oImage->getIsWatermark(), false); + $this->assertEquals($oImage->isWatermark(), false); + $this->assertEquals($oImage->getSourceType(), Image::SOURCE_LOCAL); $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\Image', $oImage->getStyle()); } @@ -51,34 +60,29 @@ class ImageTest extends \PHPUnit_Framework_TestCase /** * Valid image types */ - public function testValidImageTypes() + public function testImages() { - new Image(__DIR__ . "/../_files/images/mars_noext_jpg"); - new Image(__DIR__ . "/../_files/images/mars.jpg"); - new Image(__DIR__ . "/../_files/images/mario.gif"); - new Image(__DIR__ . "/../_files/images/firefox.png"); - new Image(__DIR__ . "/../_files/images/duke_nukem.bmp"); - new Image(__DIR__ . "/../_files/images/angela_merkel.tif"); - } + $images = array( + array('mars.jpg', 'image/jpeg', 'jpg', 'imagecreatefromjpeg', 'imagejpeg'), + array('mario.gif', 'image/gif', 'gif', 'imagecreatefromgif', 'imagegif'), + array('firefox.png', 'image/png', 'png', 'imagecreatefrompng', 'imagepng'), + array('duke_nukem.bmp', 'image/bmp', 'bmp', null, null), + array('angela_merkel.tif', 'image/tiff', 'tif', null, null), + ); - /** - * Image not found - * - * @expectedException \PhpOffice\PhpWord\Exception\InvalidImageException - */ - public function testImageNotFound() - { - new Image(__DIR__ . "/../_files/images/thisisnotarealimage"); - } - - /** - * Invalid image types - * - * @expectedException \PhpOffice\PhpWord\Exception\UnsupportedImageTypeException - */ - public function testInvalidImageTypes() - { - new Image(__DIR__ . "/../_files/images/alexz-johnson.pcx"); + foreach ($images as $imageData) { + list($source, $type, $extension, $createFunction, $imageFunction) = $imageData; + $source = __DIR__ . "/../_files/images/" . $source; + $image = new Image($source); + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Image', $image); + $this->assertEquals($image->getSource(), $source); + $this->assertEquals($image->getMediaId(), md5($source)); + $this->assertEquals($image->getImageType(), $type); + $this->assertEquals($image->getImageExtension(), $extension); + $this->assertEquals($image->getImageCreateFunction(), $createFunction); + $this->assertEquals($image->getImageFunction(), $imageFunction); + $this->assertFalse($image->isMemImage()); + } } /** @@ -88,18 +92,42 @@ class ImageTest extends \PHPUnit_Framework_TestCase { $oImage = new Image( __DIR__ . "/../_files/images/earth.jpg", - array('width' => 210, 'height' => 210, 'align' => 'center') + array('height' => 210, 'align' => 'center') ); $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\Image', $oImage->getStyle()); } /** - * Test set wrapping style + * Test invalid local image + * + * @expectedException \PhpOffice\PhpWord\Exception\InvalidImageException */ - public function testStyleWrappingStyle() + public function testInvalidImageLocal() { + new Image(__DIR__ . "/../_files/images/thisisnotarealimage"); + } + /** + * Test invalid PHP Image + * + * @expectedException \PhpOffice\PhpWord\Exception\InvalidImageException + */ + public function testInvalidImagePhp() + { + $object = new Image('test.php'); + $object->getSource(); + } + + /** + * Test unsupported image + * + * @expectedException \PhpOffice\PhpWord\Exception\UnsupportedImageTypeException + */ + public function testUnsupportedImage() + { + $object = new Image('http://samples.libav.org/image-samples/RACECAR.BMP'); + $object->getSource(); } /** @@ -107,117 +135,20 @@ class ImageTest extends \PHPUnit_Framework_TestCase */ public function testRelationID() { - $oImage = new Image(__DIR__ . "/../_files/images/earth.jpg"); + $oImage = new Image(__DIR__ . "/../_files/images/earth.jpg", array('width' => 100)); $iVal = rand(1, 1000); $oImage->setRelationId($iVal); $this->assertEquals($oImage->getRelationId(), $iVal); } /** - * Get is watermark + * Test archived image */ - public function testWatermark() + public function testArchivedImage() { - $oImage = new Image(__DIR__ . "/../_files/images/earth.jpg"); - $oImage->setIsWatermark(true); - $this->assertEquals($oImage->getIsWatermark(), true); - } - - /** - * Test PNG - */ - public function testPNG() - { - $src = __DIR__ . "/../_files/images/firefox.png"; - $oImage = new Image($src); - - $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Image', $oImage); - $this->assertEquals($oImage->getSource(), $src); - $this->assertEquals($oImage->getMediaId(), md5($src)); - $this->assertEquals($oImage->getImageCreateFunction(), 'imagecreatefrompng'); - $this->assertEquals($oImage->getImageFunction(), 'imagepng'); - $this->assertEquals($oImage->getImageExtension(), 'png'); - $this->assertEquals($oImage->getImageType(), 'image/png'); - } - - /** - * Test GIF - */ - public function testGIF() - { - $src = __DIR__ . "/../_files/images/mario.gif"; - $oImage = new Image($src); - - $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Image', $oImage); - $this->assertEquals($oImage->getSource(), $src); - $this->assertEquals($oImage->getMediaId(), md5($src)); - $this->assertEquals($oImage->getImageCreateFunction(), 'imagecreatefromgif'); - $this->assertEquals($oImage->getImageFunction(), 'imagegif'); - $this->assertEquals($oImage->getImageExtension(), 'gif'); - $this->assertEquals($oImage->getImageType(), 'image/gif'); - } - - /** - * Test JPG - */ - public function testJPG() - { - $src = __DIR__ . "/../_files/images/earth.jpg"; - $oImage = new Image($src); - - $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Image', $oImage); - $this->assertEquals($oImage->getSource(), $src); - $this->assertEquals($oImage->getMediaId(), md5($src)); - $this->assertEquals($oImage->getImageCreateFunction(), 'imagecreatefromjpeg'); - $this->assertEquals($oImage->getImageFunction(), 'imagejpeg'); - $this->assertEquals($oImage->getImageExtension(), 'jpg'); - $this->assertEquals($oImage->getImageType(), 'image/jpeg'); - } - - /** - * Test BMP - */ - public function testBMP() - { - $oImage = new Image(__DIR__ . "/../_files/images/duke_nukem.bmp"); - - $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Image', $oImage); - $this->assertEquals($oImage->getImageCreateFunction(), null); - $this->assertEquals($oImage->getImageFunction(), null); - $this->assertEquals($oImage->getImageExtension(), 'bmp'); - $this->assertEquals($oImage->getImageType(), 'image/bmp'); - } - - /** - * Test TIFF - */ - public function testTIFF() - { - $oImage = new Image(__DIR__ . "/../_files/images/angela_merkel.tif"); - - $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Image', $oImage); - $this->assertEquals($oImage->getImageCreateFunction(), null); - $this->assertEquals($oImage->getImageFunction(), null); - $this->assertEquals($oImage->getImageType(), 'image/tiff'); - } - - /** - * Test PHP Image - * - * @expectedException \PhpOffice\PhpWord\Exception\InvalidImageException - */ - public function testPhpImage() - { - $object = new Image('test.php'); - } - - /** - * Test PCX Image and Memory - * - * @expectedException \PhpOffice\PhpWord\Exception\UnsupportedImageTypeException - */ - public function testPcxImage() - { - $object = new Image('http://samples.libav.org/image-samples/RACECAR.BMP'); + $archiveFile = __DIR__ . "/../_files/documents/reader.docx"; + $imageFile = 'word/media/image1.jpeg'; + $image = new Image("zip://{$archiveFile}#{$imageFile}"); + $this->assertEquals('image/jpeg', $image->getImageType()); } } diff --git a/tests/PhpWord/Tests/Element/LineTest.php b/tests/PhpWord/Tests/Element/LineTest.php new file mode 100644 index 00000000..5add9a6b --- /dev/null +++ b/tests/PhpWord/Tests/Element/LineTest.php @@ -0,0 +1,76 @@ +assertInstanceOf('PhpOffice\\PhpWord\\Element\\Line', $oLine); + $this->assertEquals($oLine->getStyle(), null); + } + + /** + * Get style name + */ + public function testStyleText() + { + $oLine = new Line('lineStyle'); + + $this->assertEquals($oLine->getStyle(), 'lineStyle'); + } + + /** + * Get style array + */ + public function testStyleArray() + { + $oLine = new Line( + array( + 'width' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(14), + 'height' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(4), + 'positioning' => 'absolute', + 'posHorizontalRel' => 'page', + 'posVerticalRel' => 'page', + 'flip' => true, + 'marginLeft' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(5), + 'marginTop' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(3), + 'wrappingStyle' => \PhpOffice\PhpWord\Style\Image::WRAPPING_STYLE_SQUARE, + 'beginArrow' => \PhpOffice\PhpWord\Style\Line::ARROW_STYLE_BLOCK, + 'endArrow' => \PhpOffice\PhpWord\Style\Line::ARROW_STYLE_OVAL, + 'dash' => \PhpOffice\PhpWord\Style\Line::DASH_STYLE_LONG_DASH_DOT_DOT, + 'weight' => 10 + ) + ); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\Line', $oLine->getStyle()); + } +} diff --git a/tests/PhpWord/Tests/Element/LinkTest.php b/tests/PhpWord/Tests/Element/LinkTest.php index 9f89b21c..ada6a36a 100644 --- a/tests/PhpWord/Tests/Element/LinkTest.php +++ b/tests/PhpWord/Tests/Element/LinkTest.php @@ -1,10 +1,18 @@ assertInstanceOf('PhpOffice\\PhpWord\\Element\\Link', $oLink); - $this->assertEquals($oLink->getLinkSrc(), 'http://www.google.com'); - $this->assertEquals($oLink->getLinkName(), null); + $this->assertEquals($oLink->getSource(), 'http://www.google.com'); + $this->assertEquals($oLink->getText(), $oLink->getSource()); $this->assertEquals($oLink->getFontStyle(), null); $this->assertEquals($oLink->getParagraphStyle(), null); } @@ -47,8 +55,8 @@ class LinkTest extends \PHPUnit_Framework_TestCase ); $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Link', $oLink); - $this->assertEquals($oLink->getLinkSrc(), 'http://www.google.com'); - $this->assertEquals($oLink->getLinkName(), 'Search Engine'); + $this->assertEquals($oLink->getSource(), 'http://www.google.com'); + $this->assertEquals($oLink->getText(), 'Search Engine'); $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\Font', $oLink->getFontStyle()); $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\Paragraph', $oLink->getParagraphStyle()); } diff --git a/tests/PhpWord/Tests/Element/ListItemRunTest.php b/tests/PhpWord/Tests/Element/ListItemRunTest.php new file mode 100644 index 00000000..7bb0c25d --- /dev/null +++ b/tests/PhpWord/Tests/Element/ListItemRunTest.php @@ -0,0 +1,175 @@ +assertInstanceOf('PhpOffice\\PhpWord\\Element\\ListItemRun', $oListItemRun); + $this->assertCount(0, $oListItemRun->getElements()); + $this->assertEquals($oListItemRun->getParagraphStyle(), null); + } + + /** + * New instance with string + */ + public function testConstructString() + { + $oListItemRun = new ListItemRun(0, null, 'pStyle'); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\ListItemRun', $oListItemRun); + $this->assertCount(0, $oListItemRun->getElements()); + $this->assertEquals($oListItemRun->getParagraphStyle(), 'pStyle'); + } + + /** + * New instance with string + */ + public function testConstructListString() + { + $oListItemRun = new ListItemRun(0, 'numberingStyle'); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\ListItemRun', $oListItemRun); + $this->assertCount(0, $oListItemRun->getElements()); + } + + /** + * New instance with array + */ + public function testConstructArray() + { + $oListItemRun = new ListItemRun(0, null, array('spacing' => 100)); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\ListItemRun', $oListItemRun); + $this->assertCount(0, $oListItemRun->getElements()); + $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\Paragraph', $oListItemRun->getParagraphStyle()); + } + + /** + * Get style + */ + public function testStyle() + { + $oListItemRun = new ListItemRun(1, array('listType' => \PhpOffice\PhpWord\Style\ListItem::TYPE_NUMBER)); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\ListItem', $oListItemRun->getStyle()); + $this->assertEquals($oListItemRun->getStyle()->getListType(), \PhpOffice\PhpWord\Style\ListItem::TYPE_NUMBER); + } + /** + * getDepth + */ + public function testDepth() + { + $iVal = rand(1, 1000); + $oListItemRun = new ListItemRun($iVal); + + $this->assertEquals($oListItemRun->getDepth(), $iVal); + } + + /** + * Add text + */ + public function testAddText() + { + $oListItemRun = new ListItemRun(); + $element = $oListItemRun->addText('text'); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Text', $element); + $this->assertCount(1, $oListItemRun->getElements()); + $this->assertEquals($element->getText(), 'text'); + } + + /** + * Add text non-UTF8 + */ + public function testAddTextNotUTF8() + { + $oListItemRun = new ListItemRun(); + $element = $oListItemRun->addText(utf8_decode('ééé')); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Text', $element); + $this->assertCount(1, $oListItemRun->getElements()); + $this->assertEquals($element->getText(), 'ééé'); + } + + /** + * Add link + */ + public function testAddLink() + { + $oListItemRun = new ListItemRun(); + $element = $oListItemRun->addLink('http://www.google.fr'); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Link', $element); + $this->assertCount(1, $oListItemRun->getElements()); + $this->assertEquals($element->getSource(), 'http://www.google.fr'); + } + + /** + * Add link with name + */ + public function testAddLinkWithName() + { + $oListItemRun = new ListItemRun(); + $element = $oListItemRun->addLink('http://www.google.fr', utf8_decode('ééé')); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Link', $element); + $this->assertCount(1, $oListItemRun->getElements()); + $this->assertEquals($element->getSource(), 'http://www.google.fr'); + $this->assertEquals($element->getText(), 'ééé'); + } + + /** + * Add text break + */ + public function testAddTextBreak() + { + $oListItemRun = new ListItemRun(); + $oListItemRun->addTextBreak(2); + + $this->assertCount(2, $oListItemRun->getElements()); + } + + /** + * Add image + */ + public function testAddImage() + { + $src = __DIR__ . "/../_files/images/earth.jpg"; + + $oListItemRun = new ListItemRun(); + $element = $oListItemRun->addImage($src); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Image', $element); + $this->assertCount(1, $oListItemRun->getElements()); + } +} diff --git a/tests/PhpWord/Tests/Element/ListItemTest.php b/tests/PhpWord/Tests/Element/ListItemTest.php index 6526f571..1362eb43 100644 --- a/tests/PhpWord/Tests/Element/ListItemTest.php +++ b/tests/PhpWord/Tests/Element/ListItemTest.php @@ -1,10 +1,18 @@ assertInstanceOf('PhpOffice\\PhpWord\\Element\\Object', $oObject); - $this->assertEquals($oObject->getSource(), null); - $this->assertEquals($oObject->getStyle(), null); + $oObject->getSource(); } /** diff --git a/tests/PhpWord/Tests/Element/PageBreakTest.php b/tests/PhpWord/Tests/Element/PageBreakTest.php index 0c6379f5..6b038a82 100644 --- a/tests/PhpWord/Tests/Element/PageBreakTest.php +++ b/tests/PhpWord/Tests/Element/PageBreakTest.php @@ -1,10 +1,18 @@ assertInstanceOf('PhpOffice\\PhpWord\\Element\\Row', $oRow); $this->assertEquals($oRow->getHeight(), null); @@ -40,15 +47,9 @@ class RowTest extends \PHPUnit_Framework_TestCase public function testConstructWithParams() { $iVal = rand(1, 1000); - $iVal2 = rand(1, 1000); - $oRow = new Row( - 'section', - $iVal, - $iVal2, - array('borderBottomSize' => 18, 'borderBottomColor' => '0000FF', 'bgColor' => '66BBFF') - ); + $oRow = new Row($iVal, array('borderBottomSize' => 18, 'borderBottomColor' => '0000FF', 'bgColor' => '66BBFF')); - $this->assertEquals($oRow->getHeight(), $iVal2); + $this->assertEquals($oRow->getHeight(), $iVal); $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\Row', $oRow->getStyle()); } @@ -57,7 +58,7 @@ class RowTest extends \PHPUnit_Framework_TestCase */ public function testAddCell() { - $oRow = new Row('section', 1); + $oRow = new Row(); $element = $oRow->addCell(); $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Cell', $element); diff --git a/tests/PhpWord/Tests/Element/SDTTest.php b/tests/PhpWord/Tests/Element/SDTTest.php new file mode 100644 index 00000000..8c7b4bf3 --- /dev/null +++ b/tests/PhpWord/Tests/Element/SDTTest.php @@ -0,0 +1,69 @@ +setValue($value); + $object->setListItems($types); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\SDT', $object); + $this->assertEquals($type, $object->getType()); + $this->assertEquals($types, $object->getListItems()); + $this->assertEquals($value, $object->getValue()); + } + + /** + * Test set type exception + * + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Invalid style value + */ + public function testSetTypeException() + { + $object = new SDT('comboBox'); + $object->setType('foo'); + } + + /** + * Test set type + */ + public function testSetTypeNull() + { + $object = new SDT('comboBox'); + $object->setType(' '); + + $this->assertEquals('comboBox', $object->getType()); + } +} diff --git a/tests/PhpWord/Tests/Element/SectionTest.php b/tests/PhpWord/Tests/Element/SectionTest.php index d41a1e1f..853ebc5d 100644 --- a/tests/PhpWord/Tests/Element/SectionTest.php +++ b/tests/PhpWord/Tests/Element/SectionTest.php @@ -1,17 +1,26 @@ assertAttributeEquals($oSection->getSettings(), 'settings', new Section(0)); + $this->assertAttributeEquals($oSection->getStyle(), 'style', new Section(0)); } /** @@ -60,12 +69,12 @@ class SectionTest extends \PHPUnit_Framework_TestCase /** * Set settings */ - public function testSetSettings() + public function testSetStyle() { $expected = 'landscape'; $object = new Section(0); - $object->setSettings(array('orientation' => $expected)); - $this->assertEquals($expected, $object->getSettings()->getOrientation()); + $object->setStyle(array('orientation' => $expected, 'foo' => null)); + $this->assertEquals($expected, $object->getStyle()->getOrientation()); } /** @@ -75,9 +84,10 @@ class SectionTest extends \PHPUnit_Framework_TestCase { $objectSource = __DIR__ . "/../_files/documents/reader.docx"; $imageSource = __DIR__ . "/../_files/images/PhpWord.png"; - $imageUrl = 'http://php.net//images/logos/php-med-trans-light.gif'; + // $imageUrl = 'http://php.net//images/logos/php-med-trans-light.gif'; $section = new Section(0); + $section->setPhpWord(new PhpWord()); $section->addText(utf8_decode('ä')); $section->addLink(utf8_decode('http://äää.com'), utf8_decode('ä')); $section->addTextBreak(); @@ -95,13 +105,12 @@ class SectionTest extends \PHPUnit_Framework_TestCase $elementCollection = $section->getElements(); $elementTypes = array('Text', 'Link', 'TextBreak', 'PageBreak', 'Table', 'ListItem', 'Object', 'Image', - 'Title', 'TextRun', 'Footnote', 'CheckBox'); - $i = 0; + 'Title', 'TextRun', 'Footnote', 'CheckBox', 'TOC'); + $elmCount = 0; foreach ($elementTypes as $elementType) { - $this->assertInstanceOf("PhpOffice\\PhpWord\\Element\\{$elementType}", $elementCollection[$i]); - $i++; + $this->assertInstanceOf("PhpOffice\\PhpWord\\Element\\{$elementType}", $elementCollection[$elmCount]); + $elmCount++; } - $this->assertInstanceOf("PhpOffice\\PhpWord\\TOC", $elementCollection[$i]); } /** @@ -123,6 +132,7 @@ class SectionTest extends \PHPUnit_Framework_TestCase { Style::addTitleStyle(1, array('size' => 14)); $section = new Section(0); + $section->setPhpWord(new PhpWord()); $section->addTitle('Test', 1); $elementCollection = $section->getElements(); @@ -164,6 +174,6 @@ class SectionTest extends \PHPUnit_Framework_TestCase public function testAddHeaderException() { $object = new Section(1); - $header = $object->addHeader('ODD'); + $object->addHeader('ODD'); } } diff --git a/tests/PhpWord/Tests/TOCTest.php b/tests/PhpWord/Tests/Element/TOCTest.php similarity index 54% rename from tests/PhpWord/Tests/TOCTest.php rename to tests/PhpWord/Tests/Element/TOCTest.php index 5417bb44..d0ebf343 100644 --- a/tests/PhpWord/Tests/TOCTest.php +++ b/tests/PhpWord/Tests/Element/TOCTest.php @@ -1,18 +1,28 @@ 9062, - 'tabLeader' => \PhpOffice\PhpWord\Style\TOC::TABLEADER_DOT, + 'position' => 9062, + 'leader' => \PhpOffice\PhpWord\Style\Tab::TAB_LEADER_DOT, 'indent' => 200, ); - $object = new TOC(array('_size' => 11), array('_tabPos' => $expected['tabPos'])); + $object = new TOC(array('size' => 11), array('position' => $expected['position'])); $tocStyle = $object->getStyleTOC(); $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\TOC', $tocStyle); @@ -46,43 +56,20 @@ class TOCTest extends \PHPUnit_Framework_TestCase public function testConstructWithStyleName() { $object = new TOC('Font Style'); - $tocStyle = $object->getStyleTOC(); + // $tocStyle = $object->getStyleTOC(); $this->assertEquals('Font Style', $object->getStyleFont()); } /** - * Add and get title + * Test when no PHPWord object is assigned: */ - public function testAddAndGetTitle() + public function testNoPhpWord() { - $titleCount = 3; - $anchor = '_Toc' . (252634154 + $titleCount); - $bookmark = $titleCount - 1; - $titles = array( - 'Heading 1' => 1, - 'Heading 2' => 2, - 'Heading 3' => 3, - ); - $toc = new TOC(); - - foreach ($titles as $text => $depth) { - $response = $toc->addTitle($text, $depth); - } - $this->assertEquals($anchor, $response[0]); - $this->assertEquals($bookmark, $response[1]); - - $i = 0; - $savedTitles = $toc->getTitles(); - foreach ($titles as $text => $depth) { - $this->assertEquals($text, $savedTitles[$i]['text']); - $this->assertEquals($depth, $savedTitles[$i]['depth']); - $i++; - } - - TOC::resetTitles(); - $this->assertEquals(0, count($toc->getTitles())); + $object = new TOC(); + $this->assertEmpty($object->getTitles()); + $this->assertNull($object->getPhpWord()); } /** @@ -90,17 +77,19 @@ class TOCTest extends \PHPUnit_Framework_TestCase */ public function testSetGetMinMaxDepth() { - $toc = new TOC(); $titles = array( 'Heading 1' => 1, 'Heading 2' => 2, 'Heading 3' => 3, 'Heading 4' => 4, ); - foreach ($titles as $text => $depth) { - $toc->addTitle($text, $depth); - } + $phpWord = new PhpWord(); + foreach ($titles as $text => $depth) { + $phpWord->addTitle(new Title($text, $depth)); + } + $toc = new TOC(); + $toc->setPhpWord($phpWord); $this->assertEquals(1, $toc->getMinDepth()); $this->assertEquals(9, $toc->getMaxDepth()); diff --git a/tests/PhpWord/Tests/Element/TableTest.php b/tests/PhpWord/Tests/Element/TableTest.php index 3fc51f98..0977639f 100644 --- a/tests/PhpWord/Tests/Element/TableTest.php +++ b/tests/PhpWord/Tests/Element/TableTest.php @@ -1,10 +1,18 @@ assertInstanceOf('PhpOffice\\PhpWord\\Element\\Table', $oTable); $this->assertEquals($oTable->getStyle(), null); @@ -38,7 +46,7 @@ class TableTest extends \PHPUnit_Framework_TestCase */ public function testStyleText() { - $oTable = new Table('section', 1, 'tableStyle'); + $oTable = new Table('tableStyle'); $this->assertEquals($oTable->getStyle(), 'tableStyle'); } @@ -48,7 +56,7 @@ class TableTest extends \PHPUnit_Framework_TestCase */ public function testStyleArray() { - $oTable = new Table('section', 1, array( + $oTable = new Table(array( 'borderSize' => 6, 'borderColor' => '006699', 'cellMargin' => 80 @@ -62,7 +70,7 @@ class TableTest extends \PHPUnit_Framework_TestCase */ public function testWidth() { - $oTable = new Table('section', 1); + $oTable = new Table(); $iVal = rand(1, 1000); $oTable->setWidth($iVal); $this->assertEquals($oTable->getWidth(), $iVal); @@ -73,7 +81,7 @@ class TableTest extends \PHPUnit_Framework_TestCase */ public function testRow() { - $oTable = new Table('section', 1); + $oTable = new Table(); $element = $oTable->addRow(); $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Row', $element); $this->assertCount(1, $oTable->getRows()); @@ -84,7 +92,7 @@ class TableTest extends \PHPUnit_Framework_TestCase */ public function testCell() { - $oTable = new Table('section', 1); + $oTable = new Table(); $oTable->addRow(); $element = $oTable->addCell(); $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Cell', $element); @@ -95,7 +103,7 @@ class TableTest extends \PHPUnit_Framework_TestCase */ public function testCountColumns() { - $oTable = new Table('section', 1); + $oTable = new Table(); $oTable->addRow(); $element = $oTable->addCell(); $this->assertEquals($oTable->countColumns(), 1); diff --git a/tests/PhpWord/Tests/Element/TextBoxTest.php b/tests/PhpWord/Tests/Element/TextBoxTest.php new file mode 100644 index 00000000..2c6da465 --- /dev/null +++ b/tests/PhpWord/Tests/Element/TextBoxTest.php @@ -0,0 +1,72 @@ +assertInstanceOf('PhpOffice\\PhpWord\\Element\\TextBox', $oTextBox); + $this->assertEquals($oTextBox->getStyle(), null); + } + + /** + * Get style name + */ + public function testStyleText() + { + $oTextBox = new TextBox('textBoxStyle'); + + $this->assertEquals($oTextBox->getStyle(), 'textBoxStyle'); + } + + /** + * Get style array + */ + public function testStyleArray() + { + $oTextBox = new TextBox( + array( + 'width' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(4.5), + 'height' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(17.5), + 'positioning' => 'absolute', + 'marginLeft' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(15.4), + 'marginTop' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(9.9), + 'stroke' => 0, + 'innerMargin' => 0, + 'borderSize' => 1, + 'borderColor' => '' + ) + ); + + $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\TextBox', $oTextBox->getStyle()); + } +} diff --git a/tests/PhpWord/Tests/Element/TextBreakTest.php b/tests/PhpWord/Tests/Element/TextBreakTest.php index c228215f..1d9479ee 100644 --- a/tests/PhpWord/Tests/Element/TextBreakTest.php +++ b/tests/PhpWord/Tests/Element/TextBreakTest.php @@ -1,10 +1,18 @@ assertInstanceOf('PhpOffice\\PhpWord\\Element\\Link', $element); $this->assertCount(1, $oTextRun->getElements()); - $this->assertEquals($element->getLinkSrc(), 'http://www.google.fr'); + $this->assertEquals($element->getSource(), 'http://www.google.fr'); } /** @@ -103,8 +112,8 @@ class TextRunTest extends \PHPUnit_Framework_TestCase $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Link', $element); $this->assertCount(1, $oTextRun->getElements()); - $this->assertEquals($element->getLinkSrc(), 'http://www.google.fr'); - $this->assertEquals($element->getLinkName(), 'ééé'); + $this->assertEquals($element->getSource(), 'http://www.google.fr'); + $this->assertEquals($element->getText(), 'ééé'); } /** @@ -113,7 +122,7 @@ class TextRunTest extends \PHPUnit_Framework_TestCase public function testAddTextBreak() { $oTextRun = new TextRun(); - $element = $oTextRun->addTextBreak(2); + $oTextRun->addTextBreak(2); $this->assertCount(2, $oTextRun->getElements()); } @@ -138,6 +147,7 @@ class TextRunTest extends \PHPUnit_Framework_TestCase public function testCreateFootnote() { $oTextRun = new TextRun(); + $oTextRun->setPhpWord(new PhpWord()); $element = $oTextRun->addFootnote(); $this->assertInstanceOf('PhpOffice\\PhpWord\\Element\\Footnote', $element); diff --git a/tests/PhpWord/Tests/Element/TextTest.php b/tests/PhpWord/Tests/Element/TextTest.php index 953dfc8f..a306d4b9 100644 --- a/tests/PhpWord/Tests/Element/TextTest.php +++ b/tests/PhpWord/Tests/Element/TextTest.php @@ -1,10 +1,18 @@ assertEquals($oTitle->getStyle(), null); } - - /** - * Get style not null - */ - public function testStyleNotNull() - { - $oTitle = new Title('text', 1, 'style'); - - $this->assertEquals($oTitle->getStyle(), 'style'); - } - - /** - * Get anchor - */ - public function testAnchor() - { - $oTitle = new Title('text'); - - $iVal = rand(1, 1000); - $oTitle->setAnchor($iVal); - $this->assertEquals($oTitle->getAnchor(), $iVal); - } - - /** - * Get bookmark Id - */ - public function testBookmarkID() - { - $oTitle = new Title('text'); - - $iVal = rand(1, 1000); - $oTitle->setBookmarkId($iVal); - $this->assertEquals($oTitle->getBookmarkId(), $iVal); - } } diff --git a/tests/PhpWord/Tests/EndnotesTest.php b/tests/PhpWord/Tests/EndnotesTest.php deleted file mode 100644 index a72e85f9..00000000 --- a/tests/PhpWord/Tests/EndnotesTest.php +++ /dev/null @@ -1,39 +0,0 @@ -assertEquals(1, $rId); - $this->assertEquals(1, count(Endnotes::getElements())); - $this->assertEquals($endnote2, Endnotes::getElement(1)); - $this->assertNull(Endnotes::getElement(2)); - - Endnotes::resetElements(); - $this->assertEquals(0, Endnotes::countElements()); - } -} diff --git a/tests/PhpWord/Tests/Exception/CopyFileExceptionTest.php b/tests/PhpWord/Tests/Exception/CopyFileExceptionTest.php new file mode 100644 index 00000000..3d92595f --- /dev/null +++ b/tests/PhpWord/Tests/Exception/CopyFileExceptionTest.php @@ -0,0 +1,39 @@ +assertEquals(1, $rId); - $this->assertEquals(1, count(Footnotes::getElements())); - $this->assertEquals($footnote2, Footnotes::getElement(1)); - $this->assertNull(Footnotes::getElement(2)); - - Footnotes::resetElements(); - $this->assertEquals(0, Footnotes::countElements()); - } -} diff --git a/tests/PhpWord/Tests/IOFactoryTest.php b/tests/PhpWord/Tests/IOFactoryTest.php index 405eabe0..60db16d0 100644 --- a/tests/PhpWord/Tests/IOFactoryTest.php +++ b/tests/PhpWord/Tests/IOFactoryTest.php @@ -1,16 +1,24 @@ assertEquals(Media::countElements('section'), 0); + $this->assertEquals(0, Media::countElements('section')); } /** @@ -50,7 +57,7 @@ class MediaTest extends \PHPUnit_Framework_TestCase Media::addElement('section', 'object', $object); Media::addElement('section', 'object', $object); - $this->assertEquals(3, Media::countElements('section')); + $this->assertCount(3, Media::getElements('section')); } /** @@ -62,8 +69,7 @@ class MediaTest extends \PHPUnit_Framework_TestCase $actual = Media::addElement('section', 'link', 'http://test.com'); $this->assertEquals($expected, $actual); - $this->assertEquals(1, Media::countElements('section', 'link')); - $this->assertEquals(1, count(Media::getElements('section', 'link'))); + $this->assertCount(1, Media::getElements('section', 'link')); } /** @@ -77,8 +83,7 @@ class MediaTest extends \PHPUnit_Framework_TestCase Media::addElement('header1', 'image', $local, new Image($local)); Media::addElement('header1', 'image', $remote, new Image($remote)); - $this->assertEquals(2, Media::countElements('header1')); - $this->assertEquals(2, count(Media::getElements('header1'))); + $this->assertCount(2, Media::getElements('header1')); $this->assertEmpty(Media::getElements('header2')); } @@ -93,10 +98,10 @@ class MediaTest extends \PHPUnit_Framework_TestCase Media::addElement('footer1', 'image', $local, new Image($local)); Media::addElement('footer1', 'image', $remote, new Image($remote)); - $this->assertEquals(2, Media::countElements('footer1')); + $this->assertCount(2, Media::getElements('footer1')); Media::resetElements(); - $this->assertEquals(0, Media::countElements('footer1')); + $this->assertCount(0, Media::getElements('footer1')); } /** diff --git a/tests/PhpWord/Tests/DocumentPropertiesTest.php b/tests/PhpWord/Tests/Metadata/DocInfoTest.php similarity index 64% rename from tests/PhpWord/Tests/DocumentPropertiesTest.php rename to tests/PhpWord/Tests/Metadata/DocInfoTest.php index 207eb195..c860a0d9 100644 --- a/tests/PhpWord/Tests/DocumentPropertiesTest.php +++ b/tests/PhpWord/Tests/Metadata/DocInfoTest.php @@ -1,29 +1,37 @@ setCreator(); $this->assertEquals('', $oProperties->getCreator()); @@ -36,7 +44,7 @@ class DocumentPropertiesTest extends \PHPUnit_Framework_TestCase */ public function testLastModifiedBy() { - $oProperties = new DocumentProperties(); + $oProperties = new DocInfo(); $oProperties->setLastModifiedBy(); $this->assertEquals('', $oProperties->getLastModifiedBy()); @@ -49,7 +57,7 @@ class DocumentPropertiesTest extends \PHPUnit_Framework_TestCase */ public function testCreated() { - $oProperties = new DocumentProperties(); + $oProperties = new DocInfo(); $oProperties->setCreated(); $this->assertEquals(time(), $oProperties->getCreated()); @@ -63,7 +71,7 @@ class DocumentPropertiesTest extends \PHPUnit_Framework_TestCase */ public function testModified() { - $oProperties = new DocumentProperties(); + $oProperties = new DocInfo(); $oProperties->setModified(); $this->assertEquals(time(), $oProperties->getModified()); @@ -77,7 +85,7 @@ class DocumentPropertiesTest extends \PHPUnit_Framework_TestCase */ public function testTitle() { - $oProperties = new DocumentProperties(); + $oProperties = new DocInfo(); $oProperties->setTitle(); $this->assertEquals('', $oProperties->getTitle()); @@ -90,7 +98,7 @@ class DocumentPropertiesTest extends \PHPUnit_Framework_TestCase */ public function testDescription() { - $oProperties = new DocumentProperties(); + $oProperties = new DocInfo(); $oProperties->setDescription(); $this->assertEquals('', $oProperties->getDescription()); @@ -103,7 +111,7 @@ class DocumentPropertiesTest extends \PHPUnit_Framework_TestCase */ public function testSubject() { - $oProperties = new DocumentProperties(); + $oProperties = new DocInfo(); $oProperties->setSubject(); $this->assertEquals('', $oProperties->getSubject()); @@ -116,7 +124,7 @@ class DocumentPropertiesTest extends \PHPUnit_Framework_TestCase */ public function testKeywords() { - $oProperties = new DocumentProperties(); + $oProperties = new DocInfo(); $oProperties->setKeywords(); $this->assertEquals('', $oProperties->getKeywords()); @@ -129,7 +137,7 @@ class DocumentPropertiesTest extends \PHPUnit_Framework_TestCase */ public function testCategory() { - $oProperties = new DocumentProperties(); + $oProperties = new DocInfo(); $oProperties->setCategory(); $this->assertEquals('', $oProperties->getCategory()); @@ -142,7 +150,7 @@ class DocumentPropertiesTest extends \PHPUnit_Framework_TestCase */ public function testCompany() { - $oProperties = new DocumentProperties(); + $oProperties = new DocInfo(); $oProperties->setCompany(); $this->assertEquals('', $oProperties->getCompany()); @@ -155,7 +163,7 @@ class DocumentPropertiesTest extends \PHPUnit_Framework_TestCase */ public function testManager() { - $oProperties = new DocumentProperties(); + $oProperties = new DocInfo(); $oProperties->setManager(); $this->assertEquals('', $oProperties->getManager()); @@ -168,30 +176,30 @@ class DocumentPropertiesTest extends \PHPUnit_Framework_TestCase */ public function testCustomProperty() { - $oProperties = new DocumentProperties(); + $oProperties = new DocInfo(); $oProperties->setCustomProperty('key1', null); $oProperties->setCustomProperty('key2', true); $oProperties->setCustomProperty('key3', 3); $oProperties->setCustomProperty('key4', 4.4); $oProperties->setCustomProperty('key5', 'value5'); $this->assertEquals( - DocumentProperties::PROPERTY_TYPE_STRING, + DocInfo::PROPERTY_TYPE_STRING, $oProperties->getCustomPropertyType('key1') ); $this->assertEquals( - DocumentProperties::PROPERTY_TYPE_BOOLEAN, + DocInfo::PROPERTY_TYPE_BOOLEAN, $oProperties->getCustomPropertyType('key2') ); $this->assertEquals( - DocumentProperties::PROPERTY_TYPE_INTEGER, + DocInfo::PROPERTY_TYPE_INTEGER, $oProperties->getCustomPropertyType('key3') ); $this->assertEquals( - DocumentProperties::PROPERTY_TYPE_FLOAT, + DocInfo::PROPERTY_TYPE_FLOAT, $oProperties->getCustomPropertyType('key4') ); $this->assertEquals( - DocumentProperties::PROPERTY_TYPE_STRING, + DocInfo::PROPERTY_TYPE_STRING, $oProperties->getCustomPropertyType('key5') ); $this->assertEquals(null, $oProperties->getCustomPropertyType('key6')); @@ -217,50 +225,50 @@ class DocumentPropertiesTest extends \PHPUnit_Framework_TestCase */ public function testConvertProperty() { - $this->assertEquals('', DocumentProperties::convertProperty('a', 'empty')); - $this->assertEquals(null, DocumentProperties::convertProperty('a', 'null')); - $this->assertEquals(8, DocumentProperties::convertProperty('8', 'int')); - $this->assertEquals(8, DocumentProperties::convertProperty('8.3', 'uint')); - $this->assertEquals(8.3, DocumentProperties::convertProperty('8.3', 'decimal')); - $this->assertEquals('8.3', DocumentProperties::convertProperty('8.3', 'lpstr')); - $this->assertEquals(strtotime('10/11/2013'), DocumentProperties::convertProperty('10/11/2013', 'date')); - $this->assertEquals(true, DocumentProperties::convertProperty('true', 'bool')); - $this->assertEquals(false, DocumentProperties::convertProperty('1', 'bool')); - $this->assertEquals('1', DocumentProperties::convertProperty('1', 'array')); - $this->assertEquals('1', DocumentProperties::convertProperty('1', '')); + $this->assertEquals('', DocInfo::convertProperty('a', 'empty')); + $this->assertEquals(null, DocInfo::convertProperty('a', 'null')); + $this->assertEquals(8, DocInfo::convertProperty('8', 'int')); + $this->assertEquals(8, DocInfo::convertProperty('8.3', 'uint')); + $this->assertEquals(8.3, DocInfo::convertProperty('8.3', 'decimal')); + $this->assertEquals('8.3', DocInfo::convertProperty('8.3', 'lpstr')); + $this->assertEquals(strtotime('10/11/2013'), DocInfo::convertProperty('10/11/2013', 'date')); + $this->assertEquals(true, DocInfo::convertProperty('true', 'bool')); + $this->assertEquals(false, DocInfo::convertProperty('1', 'bool')); + $this->assertEquals('1', DocInfo::convertProperty('1', 'array')); + $this->assertEquals('1', DocInfo::convertProperty('1', '')); $this->assertEquals( - DocumentProperties::PROPERTY_TYPE_INTEGER, - DocumentProperties::convertPropertyType('int') + DocInfo::PROPERTY_TYPE_INTEGER, + DocInfo::convertPropertyType('int') ); $this->assertEquals( - DocumentProperties::PROPERTY_TYPE_INTEGER, - DocumentProperties::convertPropertyType('uint') + DocInfo::PROPERTY_TYPE_INTEGER, + DocInfo::convertPropertyType('uint') ); $this->assertEquals( - DocumentProperties::PROPERTY_TYPE_FLOAT, - DocumentProperties::convertPropertyType('decimal') + DocInfo::PROPERTY_TYPE_FLOAT, + DocInfo::convertPropertyType('decimal') ); $this->assertEquals( - DocumentProperties::PROPERTY_TYPE_STRING, - DocumentProperties::convertPropertyType('lpstr') + DocInfo::PROPERTY_TYPE_STRING, + DocInfo::convertPropertyType('lpstr') ); $this->assertEquals( - DocumentProperties::PROPERTY_TYPE_DATE, - DocumentProperties::convertPropertyType('date') + DocInfo::PROPERTY_TYPE_DATE, + DocInfo::convertPropertyType('date') ); $this->assertEquals( - DocumentProperties::PROPERTY_TYPE_BOOLEAN, - DocumentProperties::convertPropertyType('bool') + DocInfo::PROPERTY_TYPE_BOOLEAN, + DocInfo::convertPropertyType('bool') ); $this->assertEquals( - DocumentProperties::PROPERTY_TYPE_UNKNOWN, - DocumentProperties::convertPropertyType('array') + DocInfo::PROPERTY_TYPE_UNKNOWN, + DocInfo::convertPropertyType('array') ); $this->assertEquals( - DocumentProperties::PROPERTY_TYPE_UNKNOWN, - DocumentProperties::convertPropertyType('') + DocInfo::PROPERTY_TYPE_UNKNOWN, + DocInfo::convertPropertyType('') ); } } diff --git a/tests/PhpWord/Tests/PhpWordTest.php b/tests/PhpWord/Tests/PhpWordTest.php index 8de6f808..756f848f 100644 --- a/tests/PhpWord/Tests/PhpWordTest.php +++ b/tests/PhpWord/Tests/PhpWordTest.php @@ -1,17 +1,25 @@ assertEquals(new DocumentProperties(), $phpWord->getDocumentProperties()); - $this->assertEquals(PhpWord::DEFAULT_FONT_NAME, $phpWord->getDefaultFontName()); - $this->assertEquals(PhpWord::DEFAULT_FONT_SIZE, $phpWord->getDefaultFontSize()); - } - - /** - * Test set/get document properties - */ - public function testSetGetDocumentProperties() - { - $phpWord = new PhpWord(); - $creator = 'PhpWord'; - $properties = $phpWord->getDocumentProperties(); - $properties->setCreator($creator); - $phpWord->setDocumentProperties($properties); - $this->assertEquals($creator, $phpWord->getDocumentProperties()->getCreator()); + $this->assertEquals(new DocInfo(), $phpWord->getDocInfo()); + $this->assertEquals(Settings::DEFAULT_FONT_NAME, $phpWord->getDefaultFontName()); + $this->assertEquals(Settings::DEFAULT_FONT_SIZE, $phpWord->getDefaultFontSize()); } /** @@ -51,9 +46,8 @@ class PhpWordTest extends \PHPUnit_Framework_TestCase public function testCreateGetSections() { $phpWord = new PhpWord(); - $this->assertEquals(new Section(1), $phpWord->addSection()); $phpWord->addSection(); - $this->assertEquals(2, count($phpWord->getSections())); + $this->assertCount(1, $phpWord->getSections()); } /** @@ -63,7 +57,7 @@ class PhpWordTest extends \PHPUnit_Framework_TestCase { $phpWord = new PhpWord(); $fontName = 'Times New Roman'; - $this->assertEquals(PhpWord::DEFAULT_FONT_NAME, $phpWord->getDefaultFontName()); + $this->assertEquals(Settings::DEFAULT_FONT_NAME, $phpWord->getDefaultFontName()); $phpWord->setDefaultFontName($fontName); $this->assertEquals($fontName, $phpWord->getDefaultFontName()); } @@ -75,7 +69,7 @@ class PhpWordTest extends \PHPUnit_Framework_TestCase { $phpWord = new PhpWord(); $fontSize = 16; - $this->assertEquals(PhpWord::DEFAULT_FONT_SIZE, $phpWord->getDefaultFontSize()); + $this->assertEquals(Settings::DEFAULT_FONT_SIZE, $phpWord->getDefaultFontSize()); $phpWord->setDefaultFontSize($fontSize); $this->assertEquals($fontSize, $phpWord->getDefaultFontSize()); } @@ -151,4 +145,28 @@ class PhpWordTest extends \PHPUnit_Framework_TestCase $phpWord = new PhpWord(); $phpWord->loadTemplate($templateFqfn); } + + /** + * Test save + */ + public function testSave() + { + $phpWord = new PhpWord(); + $section = $phpWord->addSection(); + $section->addText('Hello world!'); + + $this->assertTrue($phpWord->save('test.docx', 'Word2007', true)); + } + + /** + * Test calling undefined method + * + * @expectedException \BadMethodCallException + * @expectedExceptionMessage is not defined + */ + public function testCallUndefinedMethod() + { + $phpWord = new PhpWord(); + $phpWord->undefinedMethod(); + } } diff --git a/tests/PhpWord/Tests/Reader/HTMLTest.php b/tests/PhpWord/Tests/Reader/HTMLTest.php new file mode 100644 index 00000000..cb3dc55c --- /dev/null +++ b/tests/PhpWord/Tests/Reader/HTMLTest.php @@ -0,0 +1,51 @@ +assertInstanceOf('PhpOffice\\PhpWord\\PhpWord', $phpWord); + } + + /** + * Test load exception + * + * @expectedException \Exception + * @expectedExceptionMessage Cannot read + */ + public function testLoadException() + { + $filename = __DIR__ . '/../_files/documents/foo.html'; + IOFactory::load($filename, 'HTML'); + } +} diff --git a/tests/PhpWord/Tests/Reader/ODTextTest.php b/tests/PhpWord/Tests/Reader/ODTextTest.php new file mode 100644 index 00000000..fc4d2e33 --- /dev/null +++ b/tests/PhpWord/Tests/Reader/ODTextTest.php @@ -0,0 +1,39 @@ +assertInstanceOf('PhpOffice\\PhpWord\\PhpWord', $phpWord); + } +} diff --git a/tests/PhpWord/Tests/Reader/RTFTest.php b/tests/PhpWord/Tests/Reader/RTFTest.php new file mode 100644 index 00000000..c495db68 --- /dev/null +++ b/tests/PhpWord/Tests/Reader/RTFTest.php @@ -0,0 +1,51 @@ +assertInstanceOf('PhpOffice\\PhpWord\\PhpWord', $phpWord); + } + + /** + * Test load exception + * + * @expectedException \Exception + * @expectedExceptionMessage Cannot read + */ + public function testLoadException() + { + $filename = __DIR__ . '/../_files/documents/foo.rtf'; + IOFactory::load($filename, 'RTF'); + } +} diff --git a/tests/PhpWord/Tests/Reader/Word2007Test.php b/tests/PhpWord/Tests/Reader/Word2007Test.php index 3a572f4d..f2257012 100644 --- a/tests/PhpWord/Tests/Reader/Word2007Test.php +++ b/tests/PhpWord/Tests/Reader/Word2007Test.php @@ -1,16 +1,24 @@ assertTrue($object->canRead($fqFilename)); + $filename = __DIR__ . '/../_files/documents/reader.docx'; + $this->assertTrue($object->canRead($filename)); } /** * Can read exception - * - * @expectedException \PhpOffice\PhpWord\Exception\Exception */ public function testCanReadFailed() { $object = new Word2007(); - $fqFilename = join( - DIRECTORY_SEPARATOR, - array(PHPWORD_TESTS_BASE_DIR, 'PhpWord', 'Tests', '_files', 'documents', 'foo.docx') - ); - $this->assertFalse($object->canRead($fqFilename)); - $object = IOFactory::load($fqFilename); + $filename = __DIR__ . '/../_files/documents/foo.docx'; + $this->assertFalse($object->canRead($filename)); } /** @@ -61,11 +53,8 @@ class Word2007Test extends \PHPUnit_Framework_TestCase */ public function testLoad() { - $fqFilename = join( - DIRECTORY_SEPARATOR, - array(PHPWORD_TESTS_BASE_DIR, 'PhpWord', 'Tests', '_files', 'documents', 'reader.docx') - ); - $object = IOFactory::load($fqFilename); - $this->assertInstanceOf('PhpOffice\\PhpWord\\PhpWord', $object); + $filename = __DIR__ . '/../_files/documents/reader.docx'; + $phpWord = IOFactory::load($filename); + $this->assertInstanceOf('PhpOffice\\PhpWord\\PhpWord', $phpWord); } } diff --git a/tests/PhpWord/Tests/SettingsTest.php b/tests/PhpWord/Tests/SettingsTest.php index fa78489e..0d3d66ae 100644 --- a/tests/PhpWord/Tests/SettingsTest.php +++ b/tests/PhpWord/Tests/SettingsTest.php @@ -1,10 +1,18 @@ assertTrue(Settings::getCompatibility()); + $this->assertTrue(Settings::hasCompatibility()); $this->assertTrue(Settings::setCompatibility(false)); - $this->assertFalse(Settings::getCompatibility()); - $this->assertFalse(Settings::setCompatibility('Non boolean')); + $this->assertFalse(Settings::hasCompatibility()); } /** - * Get/set zip class + * Test set/get zip class */ - public function testGetSetZipClass() + public function testSetGetZipClass() { $this->assertEquals(Settings::ZIPARCHIVE, Settings::getZipClass()); $this->assertTrue(Settings::setZipClass(Settings::PCLZIP)); $this->assertFalse(Settings::setZipClass('foo')); } + + /** + * Test set/get PDF renderer + */ + public function testSetGetPdfRenderer() + { + $domPdfPath = realpath(PHPWORD_TESTS_BASE_DIR . '/../vendor/dompdf/dompdf'); + + $this->assertFalse(Settings::setPdfRenderer('FOO', 'dummy/path')); + $this->assertTrue(Settings::setPdfRenderer(Settings::PDF_RENDERER_DOMPDF, $domPdfPath)); + $this->assertEquals(Settings::PDF_RENDERER_DOMPDF, Settings::getPdfRendererName()); + $this->assertEquals($domPdfPath, Settings::getPdfRendererPath()); + $this->assertFalse(Settings::setPdfRendererPath('dummy/path')); + } + + /** + * Test set/get measurement unit + */ + public function testSetGetMeasurementUnit() + { + $this->assertEquals(Settings::UNIT_TWIP, Settings::getMeasurementUnit()); + $this->assertTrue(Settings::setMeasurementUnit(Settings::UNIT_INCH)); + $this->assertFalse(Settings::setMeasurementUnit('foo')); + } + + /** + * @covers ::getTempDir + * @test + */ + public function testPhpTempDirIsUsedByDefault() + { + $this->assertEquals(sys_get_temp_dir(), Settings::getTempDir()); + } + + + /** + * @covers ::setTempDir + * @covers ::getTempDir + * @depends testPhpTempDirIsUsedByDefault + * @test + */ + public function testTempDirCanBeSet() + { + $userDefinedTempDir = 'C:\PhpWordTemp'; + Settings::setTempDir($userDefinedTempDir); + $currentTempDir = Settings::getTempDir(); + $this->assertEquals($userDefinedTempDir, $currentTempDir); + $this->assertNotEquals(sys_get_temp_dir(), $currentTempDir); + } + + /** + * Test set/get default font name + */ + public function testSetGetDefaultFontName() + { + $this->assertEquals(Settings::DEFAULT_FONT_NAME, Settings::getDefaultFontName()); + $this->assertTrue(Settings::setDefaultFontName('Times New Roman')); + $this->assertFalse(Settings::setDefaultFontName(' ')); + } + + /** + * Test set/get default font size + */ + public function testSetGetDefaultFontSize() + { + $this->assertEquals(Settings::DEFAULT_FONT_SIZE, Settings::getDefaultFontSize()); + $this->assertTrue(Settings::setDefaultFontSize(12)); + $this->assertFalse(Settings::setDefaultFontSize(null)); + } + + /** + * Test load config + */ + public function testLoadConfig() + { + $expected = array( + 'compatibility' => true, + 'zipClass' => 'ZipArchive', + 'pdfRendererName' => 'DomPDF', + 'pdfRendererPath' => '', + 'defaultFontName' => 'Arial', + 'defaultFontSize' => 10, + ); + + // Test default value + $this->assertEquals($expected, Settings::loadConfig()); + + // Test with valid file + $this->assertEquals($expected, Settings::loadConfig(__DIR__ . '/../../../phpword.ini.dist')); + + // Test with invalid file + $this->assertEmpty(Settings::loadConfig(__DIR__ . '/../../../phpunit.xml.dist')); + } } diff --git a/tests/PhpWord/Tests/Shared/ConverterTest.php b/tests/PhpWord/Tests/Shared/ConverterTest.php new file mode 100644 index 00000000..002e2e33 --- /dev/null +++ b/tests/PhpWord/Tests/Shared/ConverterTest.php @@ -0,0 +1,117 @@ +assertEquals($value / 2.54 * 1440, $result); + + $result = Converter::cmToInch($value); + $this->assertEquals($value / 2.54, $result); + + $result = Converter::cmToPixel($value); + $this->assertEquals($value / 2.54 * 96, $result); + + $result = Converter::cmToPoint($value); + $this->assertEquals($value / 2.54 * 72, $result); + + $result = Converter::cmToEmu($value); + $this->assertEquals(round($value / 2.54 * 96 * 9525), $result); + + $result = Converter::inchToTwip($value); + $this->assertEquals($value * 1440, $result); + + $result = Converter::inchToCm($value); + $this->assertEquals($value * 2.54, $result); + + $result = Converter::inchToPixel($value); + $this->assertEquals($value * 96, $result); + + $result = Converter::inchToPoint($value); + $this->assertEquals($value * 72, $result); + + $result = Converter::inchToEmu($value); + $this->assertEquals(round($value * 96 * 9525), $result); + + $result = Converter::pixelToTwip($value); + $this->assertEquals($value / 96 * 1440, $result); + + $result = Converter::pixelToCm($value); + $this->assertEquals($value / 96 * 2.54, $result); + + $result = Converter::pixelToPoint($value); + $this->assertEquals($value / 96 * 72, $result); + + $result = Converter::pixelToEMU($value); + $this->assertEquals(round($value * 9525), $result); + + $result = Converter::pointToTwip($value); + $this->assertEquals($value * 20, $result); + + $result = Converter::pointToPixel($value); + $this->assertEquals($value / 72 * 96, $result); + + $result = Converter::pointToEMU($value); + $this->assertEquals(round($value / 72 * 96 * 9525), $result); + + $result = Converter::emuToPixel($value); + $this->assertEquals(round($value / 9525), $result); + + $result = Converter::degreeToAngle($value); + $this->assertEquals((int)round($value * 60000), $result); + + $result = Converter::angleToDegree($value); + $this->assertEquals(round($value / 60000), $result); + } + } + + /** + * Test htmlToRGB() + */ + public function testHtmlToRGB() + { + // Prepare test values [ original, expected ] + $values[] = array('#FF99DD', array(255, 153, 221)); // With # + $values[] = array('FF99DD', array(255, 153, 221)); // 6 characters + $values[] = array('F9D', array(255, 153, 221)); // 3 characters + $values[] = array('0F9D', false); // 4 characters + // Conduct test + foreach ($values as $value) { + $result = Converter::htmlToRGB($value[0]); + $this->assertEquals($value[1], $result); + } + } +} diff --git a/tests/PhpWord/Tests/Shared/DrawingTest.php b/tests/PhpWord/Tests/Shared/DrawingTest.php deleted file mode 100644 index 713cebcd..00000000 --- a/tests/PhpWord/Tests/Shared/DrawingTest.php +++ /dev/null @@ -1,74 +0,0 @@ -assertEquals(round($value * 9525), $result); - - $result = Drawing::EMUToPixels($value); - $this->assertEquals(round($value / 9525), $result); - - $result = Drawing::pixelsToPoints($value); - $this->assertEquals($value * 0.67777777, $result); - - $result = Drawing::pointsToPixels($value); - $this->assertEquals($value * 1.333333333, $result); - - $result = Drawing::degreesToAngle($value); - $this->assertEquals((int)round($value * 60000), $result); - - $result = Drawing::angleToDegrees($value); - $this->assertEquals(round($value / 60000), $result); - - $result = Drawing::pixelsToCentimeters($value); - $this->assertEquals($value * 0.028, $result); - - $result = Drawing::centimetersToPixels($value); - $this->assertEquals($value / 0.028, $result); - } - } - - /** - * Test htmlToRGB() - */ - public function testHtmlToRGB() - { - // Prepare test values [ original, expected ] - $values[] = array('#FF99DD', array(255, 153, 221)); // With # - $values[] = array('FF99DD', array(255, 153, 221)); // 6 characters - $values[] = array('F9D', array(255, 153, 221)); // 3 characters - $values[] = array('0F9D', false); // 4 characters - // Conduct test - foreach ($values as $value) { - $result = Drawing::htmlToRGB($value[0]); - $this->assertEquals($value[1], $result); - } - } -} diff --git a/tests/PhpWord/Tests/Shared/FontTest.php b/tests/PhpWord/Tests/Shared/FontTest.php deleted file mode 100644 index f36f1074..00000000 --- a/tests/PhpWord/Tests/Shared/FontTest.php +++ /dev/null @@ -1,53 +0,0 @@ -assertEquals($original * 16 / 12, $result); - - $result = Font::inchSizeToPixels($original); - $this->assertEquals($original * 96, $result); - - $result = Font::centimeterSizeToPixels($original); - $this->assertEquals($original * 37.795275591, $result); - - $result = Font::centimeterSizeToTwips($original); - $this->assertEquals($original * 565.217, $result); - - $result = Font::inchSizeToTwips($original); - $this->assertEquals($original * 565.217 * 2.54, $result); - - $result = Font::pixelSizeToTwips($original); - $this->assertEquals($original * 565.217 / 37.795275591, $result); - - $result = Font::pointSizeToTwips($original); - $this->assertEquals($original * 20, $result); - } -} diff --git a/tests/PhpWord/Tests/Shared/HtmlTest.php b/tests/PhpWord/Tests/Shared/HtmlTest.php new file mode 100644 index 00000000..c4c0fc9d --- /dev/null +++ b/tests/PhpWord/Tests/Shared/HtmlTest.php @@ -0,0 +1,71 @@ +assertCount(0, $section->getElements()); + + // Heading + $styles = array('strong', 'em', 'sup', 'sub'); + for ($level = 1; $level <= 6; $level++) { + $content .= "Heading {$level}"; + } + + // Styles + $content .= '

'; + foreach ($styles as $style) { + $content .= "<{$style}>{$style}"; + } + $content .= '

'; + + // Add HTML + Html::addHtml($section, $content); + $this->assertCount(7, $section->getElements()); + + // Other parts + $section = new Section(1); + $content = ''; + $content .= '
HeaderContent
'; + $content .= '
  • Bullet
    • Bullet
'; + $content .= '
  1. Bullet
'; + $content .= "'Single Quoted Text'"; + $content .= '"Double Quoted Text"'; + $content .= '& Ampersand'; + $content .= '<>“‘’«»‹›'; + $content .= '&•°…™©®—'; + $content .= '–   ²³¼½¾'; + Html::addHtml($section, $content); + } +} diff --git a/tests/PhpWord/Tests/Shared/StringTest.php b/tests/PhpWord/Tests/Shared/StringTest.php index 02b4898a..a3524ede 100644 --- a/tests/PhpWord/Tests/Shared/StringTest.php +++ b/tests/PhpWord/Tests/Shared/StringTest.php @@ -1,10 +1,18 @@ assertEquals('', String::controlCharacterPHP2OOXML('')); $this->assertEquals('_x0008_', String::controlCharacterPHP2OOXML(chr(0x08))); } + + /** + * Test unicode conversion + */ + public function testToUnicode() + { + $this->assertEquals('a', String::toUnicode('a')); + $this->assertEquals('\uc0{\u8364}', String::toUnicode('€')); + $this->assertEquals('\uc0{\u233}', String::toUnicode('é')); + } + + /** + * Test remove underscore prefix + */ + public function testRemoveUnderscorePrefix() + { + $this->assertEquals('item', String::removeUnderscorePrefix('_item')); + } } diff --git a/tests/PhpWord/Tests/Shared/XMLReaderTest.php b/tests/PhpWord/Tests/Shared/XMLReaderTest.php index 759bf580..2bb6ef65 100644 --- a/tests/PhpWord/Tests/Shared/XMLReaderTest.php +++ b/tests/PhpWord/Tests/Shared/XMLReaderTest.php @@ -1,10 +1,18 @@ getDomFromZip($filename, 'yadayadaya'); + } + /** * Test get DOMDocument from ZipArchive returns false */ diff --git a/tests/PhpWord/Tests/Shared/XMLWriterTest.php b/tests/PhpWord/Tests/Shared/XMLWriterTest.php new file mode 100644 index 00000000..08db3918 --- /dev/null +++ b/tests/PhpWord/Tests/Shared/XMLWriterTest.php @@ -0,0 +1,40 @@ +foo(); + } +} diff --git a/tests/PhpWord/Tests/Shared/ZipArchiveTest.php b/tests/PhpWord/Tests/Shared/ZipArchiveTest.php index 40bdde68..11a0d9a3 100644 --- a/tests/PhpWord/Tests/Shared/ZipArchiveTest.php +++ b/tests/PhpWord/Tests/Shared/ZipArchiveTest.php @@ -1,75 +1,136 @@ open($zipFile); - $object->addFile($existingFile, 'xls/new.xls'); - $object->addFromString('content/string.txt', 'Test'); + // $zipFile = __DIR__ . "/../_files/documents/ziptest.zip"; - $this->assertTrue($object->locateName('xls/new.xls')); - $this->assertEquals('Test', $object->getFromName('content/string.txt')); - $this->assertEquals('Test', $object->getFromName('/content/string.txt')); + // $object = new ZipArchive(); + // $object->open($zipFile, ZipArchive::CREATE); + // $object->addFromString('content/string.txt', 'Test'); - unlink($zipFile); + // // Lock the file + // $resource = fopen($zipFile, "w"); + // flock($resource, LOCK_EX); + + // // Closing the file should throws an exception + // $object->close(); + + // // Unlock the file + // flock($resource, LOCK_UN); + // fclose($resource); + + // @unlink($zipFile); } /** - * Test find if a given name exists in the archive + * Test all methods + * + * @param string $zipClass + * @covers :: */ - public function testLocate() + public function testZipArchive($zipClass = 'ZipArchive') { + // Preparation $existingFile = __DIR__ . "/../_files/documents/sheet.xls"; $zipFile = __DIR__ . "/../_files/documents/ziptest.zip"; - $object = new ZipArchive(); - $object->open($zipFile); + $destination1 = __DIR__ . "/../_files/documents/extract1"; + $destination2 = __DIR__ . "/../_files/documents/extract2"; + @mkdir($destination1); + @mkdir($destination2); + + Settings::setZipClass($zipClass); + + $object = new ZipArchive(); + $object->open($zipFile, ZipArchive::CREATE); $object->addFile($existingFile, 'xls/new.xls'); $object->addFromString('content/string.txt', 'Test'); + $object->close(); + $object->open($zipFile); - $this->assertEquals(1, $object->locateName('content/string.txt')); + // Run tests + $this->assertEquals(0, $object->locateName('xls/new.xls')); $this->assertFalse($object->locateName('blablabla')); - unlink($zipFile); - } - - /** - * Test returns the name of an entry using its index - */ - public function testNameIndex() - { - $existingFile = __DIR__ . "/../_files/documents/sheet.xls"; - $zipFile = __DIR__ . "/../_files/documents/ziptest.zip"; - $object = new ZipArchive(); - $object->open($zipFile); - $object->addFile($existingFile, 'xls/new.xls'); - $object->addFromString('content/string.txt', 'Test'); + $this->assertEquals('Test', $object->getFromName('content/string.txt')); + $this->assertEquals('Test', $object->getFromName('/content/string.txt')); $this->assertFalse($object->getNameIndex(-1)); $this->assertEquals('content/string.txt', $object->getNameIndex(1)); - unlink($zipFile); + $this->assertFalse($object->extractTo('blablabla')); + $this->assertTrue($object->extractTo($destination1)); + $this->assertTrue($object->extractTo($destination2, 'xls/new.xls')); + $this->assertFalse($object->extractTo($destination2, 'blablabla')); + + // Cleanup + $this->deleteDir($destination1); + $this->deleteDir($destination2); + @unlink($zipFile); + } + + /** + * Test PclZip + * + * @covers :: + */ + public function testPCLZip() + { + $this->testZipArchive('PhpOffice\PhpWord\Shared\ZipArchive'); + } + + /** + * Delete directory + * + * @param string $dir + */ + private function deleteDir($dir) + { + foreach (scandir($dir) as $file) { + if ($file === '.' || $file === '..') { + continue; + } elseif (is_file($dir . "/" . $file)) { + unlink($dir . "/" . $file); + } elseif (is_dir($dir . "/" . $file)) { + $this->deleteDir($dir . "/" . $file); + } + } + + rmdir($dir); } } diff --git a/tests/PhpWord/Tests/Style/AbstractStyleTest.php b/tests/PhpWord/Tests/Style/AbstractStyleTest.php index a9eace9d..d35e1090 100644 --- a/tests/PhpWord/Tests/Style/AbstractStyleTest.php +++ b/tests/PhpWord/Tests/Style/AbstractStyleTest.php @@ -1,10 +1,18 @@ assertEquals(true, self::callProtectedMethod($stub, 'setBoolVal', array(true, false))); $this->assertEquals(12, self::callProtectedMethod($stub, 'setIntVal', array(12, 200))); $this->assertEquals(871.1, self::callProtectedMethod($stub, 'setFloatVal', array(871.1, 2.1))); + $this->assertEquals(871.1, self::callProtectedMethod($stub, 'setFloatVal', array('871.1', 2.1))); $this->assertEquals('a', self::callProtectedMethod($stub, 'setEnumVal', array('a', array('a', 'b'), 'b'))); } @@ -50,11 +59,27 @@ class AbstractStyleTest extends \PHPUnit_Framework_TestCase $this->assertEquals(false, self::callProtectedMethod($stub, 'setBoolVal', array('a', false))); $this->assertEquals(200, self::callProtectedMethod($stub, 'setIntVal', array('foo', 200))); $this->assertEquals(2.1, self::callProtectedMethod($stub, 'setFloatVal', array('foo', 2.1))); + $this->assertEquals('b', self::callProtectedMethod($stub, 'setEnumVal', array(null, array('a', 'b'), 'b'))); + } + + /** + * Test setEnumVal exception + * + * @expectedException \InvalidArgumentException + */ + public function testSetValEnumException() + { + $stub = $this->getMockForAbstractClass('\PhpOffice\PhpWord\Style\AbstractStyle'); + $this->assertEquals('b', self::callProtectedMethod($stub, 'setEnumVal', array('z', array('a', 'b'), 'b'))); } /** * Helper function to call protected method + * + * @param mixed $object + * @param string $method + * @param array $args */ public static function callProtectedMethod($object, $method, array $args = array()) { diff --git a/tests/PhpWord/Tests/Style/CellTest.php b/tests/PhpWord/Tests/Style/CellTest.php index 9bf5a917..f9131728 100644 --- a/tests/PhpWord/Tests/Style/CellTest.php +++ b/tests/PhpWord/Tests/Style/CellTest.php @@ -1,10 +1,18 @@ 'left', + 'valign' => Cell::VALIGN_TOP, 'textDirection' => Cell::TEXT_DIR_BTLR, 'bgColor' => 'FFFF00', 'borderTopSize' => 120, @@ -39,12 +47,16 @@ class CellTest extends \PHPUnit_Framework_TestCase 'borderBottomSize' => 120, 'borderBottomColor' => 'FFFF00', 'gridSpan' => 2, - 'vMerge' => 2, + 'vMerge' => Cell::VMERGE_RESTART, ); foreach ($attributes as $key => $value) { $set = "set{$key}"; $get = "get{$key}"; + + $this->assertNull($object->$get()); // Init with null value + $object->$set($value); + $this->assertEquals($value, $object->$get()); } } @@ -56,14 +68,8 @@ class CellTest extends \PHPUnit_Framework_TestCase { $object = new Cell(); - $default = '000000'; $value = 'FF0000'; - $this->assertEquals($default, $object->getDefaultBorderColor()); - - $object->setStyleValue('defaultBorderColor', $value); - $this->assertEquals($value, $object->getDefaultBorderColor()); - $object->setStyleValue('borderColor', $value); $expected = array($value, $value, $value, $value); $this->assertEquals($expected, $object->getBorderColor()); diff --git a/tests/PhpWord/Tests/Style/FontTest.php b/tests/PhpWord/Tests/Style/FontTest.php index 9185d646..c21ea4ce 100644 --- a/tests/PhpWord/Tests/Style/FontTest.php +++ b/tests/PhpWord/Tests/Style/FontTest.php @@ -1,15 +1,24 @@ assertEquals('text', $object->getStyleType()); $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\Paragraph', $object->getParagraphStyle()); + $this->assertTrue(is_array($object->getStyleValues())); } /** @@ -47,21 +57,28 @@ class FontTest extends \PHPUnit_Framework_TestCase $object = new Font(); $attributes = array( - 'name' => PhpWord::DEFAULT_FONT_NAME, - 'size' => PhpWord::DEFAULT_FONT_SIZE, + 'name' => null, + 'size' => null, + 'hint' => null, + 'color' => null, 'bold' => false, 'italic' => false, + 'underline' => Font::UNDERLINE_NONE, 'superScript' => false, 'subScript' => false, - 'underline' => Font::UNDERLINE_NONE, 'strikethrough' => false, - 'color' => PhpWord::DEFAULT_FONT_COLOR, + 'doubleStrikethrough' => false, + 'smallCaps' => false, + 'allCaps' => false, 'fgColor' => null, 'bgColor' => null, - 'hint' => PhpWord::DEFAULT_FONT_CONTENT_TYPE, + 'scale' => null, + 'spacing' => null, + 'kerning' => null, ); foreach ($attributes as $key => $default) { - $get = "get{$key}"; + $get = is_bool($default) ? "is{$key}" : "get{$key}"; + $this->assertEquals($default, $object->$get()); $object->setStyleValue("$key", null); $this->assertEquals($default, $object->$get()); $object->setStyleValue("$key", ''); @@ -79,20 +96,27 @@ class FontTest extends \PHPUnit_Framework_TestCase $attributes = array( 'name' => 'Times New Roman', 'size' => 9, + 'color' => '999999', + 'hint' => 'eastAsia', 'bold' => true, 'italic' => true, + 'underline' => Font::UNDERLINE_HEAVY, 'superScript' => true, 'subScript' => false, - 'underline' => Font::UNDERLINE_HEAVY, 'strikethrough' => true, - 'color' => '999999', + 'doubleStrikethrough' => false, + 'smallCaps' => true, + 'allCaps' => false, 'fgColor' => Font::FGCOLOR_YELLOW, 'bgColor' => 'FFFF00', - 'hint' => 'eastAsia', + 'lineHeight' => 2, + 'scale' => 150, + 'spacing' => 240, + 'kerning' => 10, ); - $object->setArrayStyle($attributes); + $object->setStyleByArray($attributes); foreach ($attributes as $key => $value) { - $get = "get{$key}"; + $get = is_bool($value) ? "is{$key}" : "get{$key}"; $this->assertEquals($value, $object->$get()); } } diff --git a/tests/PhpWord/Tests/Style/ImageTest.php b/tests/PhpWord/Tests/Style/ImageTest.php index fd74d73c..1a679da3 100644 --- a/tests/PhpWord/Tests/Style/ImageTest.php +++ b/tests/PhpWord/Tests/Style/ImageTest.php @@ -1,10 +1,18 @@ 200, 'align' => 'left', 'marginTop' => 240, - 'marginLeft' => 240 + 'marginLeft' => 240, + 'positioning' => \PhpOffice\PhpWord\Style\Image::POSITION_ABSOLUTE, + 'posHorizontal' => \PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_CENTER, + 'posVertical' => \PhpOffice\PhpWord\Style\Image::POSITION_VERTICAL_TOP, + 'posHorizontalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_COLUMN, + 'posVerticalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_IMARGIN ); foreach ($properties as $key => $value) { $get = "get{$key}"; diff --git a/tests/PhpWord/Tests/Style/IndentationTest.php b/tests/PhpWord/Tests/Style/IndentationTest.php new file mode 100644 index 00000000..d0e88f2c --- /dev/null +++ b/tests/PhpWord/Tests/Style/IndentationTest.php @@ -0,0 +1,53 @@ + array(0, 10), + 'right' => array(0, 10), + 'firstLine' => array(null, 20), + 'hanging' => array(null, 20), + ); + foreach ($properties as $property => $value) { + list($default, $expected) = $value; + $get = "get{$property}"; + $set = "set{$property}"; + + $this->assertEquals($default, $object->$get()); // Default value + + $object->$set($expected); + + $this->assertEquals($expected, $object->$get()); // New value + } + } +} diff --git a/tests/PhpWord/Tests/Style/LineNumberingTest.php b/tests/PhpWord/Tests/Style/LineNumberingTest.php new file mode 100644 index 00000000..bc4dc603 --- /dev/null +++ b/tests/PhpWord/Tests/Style/LineNumberingTest.php @@ -0,0 +1,53 @@ + array(1, 2), + 'increment' => array(1, 10), + 'distance' => array(null, 10), + 'restart' => array(null, 'continuous'), + ); + foreach ($properties as $property => $value) { + list($default, $expected) = $value; + $get = "get{$property}"; + $set = "set{$property}"; + + $this->assertEquals($default, $object->$get()); // Default value + + $object->$set($expected); + + $this->assertEquals($expected, $object->$get()); // New value + } + } +} diff --git a/tests/PhpWord/Tests/Style/LineTest.php b/tests/PhpWord/Tests/Style/LineTest.php new file mode 100644 index 00000000..02d5ba16 --- /dev/null +++ b/tests/PhpWord/Tests/Style/LineTest.php @@ -0,0 +1,151 @@ + \PhpOffice\PhpWord\Style\Line::CONNECTOR_TYPE_STRAIGHT, + 'beginArrow' => \PhpOffice\PhpWord\Style\Line::ARROW_STYLE_BLOCK, + 'endArrow' => \PhpOffice\PhpWord\Style\Line::ARROW_STYLE_OVAL, + 'dash' => \PhpOffice\PhpWord\Style\Line::DASH_STYLE_LONG_DASH_DOT_DOT, + 'weight' => 10, + 'color' => 'red' + ); + foreach ($properties as $key => $value) { + $set = "set{$key}"; + $get = "get{$key}"; + $object->$set($value); + $this->assertEquals($value, $object->$get()); + } + } + + /** + * Test setStyleValue method + */ + public function testSetStyleValue() + { + $object = new Line(); + + $properties = array( + 'connectorType' => \PhpOffice\PhpWord\Style\Line::CONNECTOR_TYPE_STRAIGHT, + 'beginArrow' => \PhpOffice\PhpWord\Style\Line::ARROW_STYLE_BLOCK, + 'endArrow' => \PhpOffice\PhpWord\Style\Line::ARROW_STYLE_OVAL, + 'dash' => \PhpOffice\PhpWord\Style\Line::DASH_STYLE_LONG_DASH_DOT_DOT, + 'weight' => 10, + 'color' => 'red' + ); + foreach ($properties as $key => $value) { + $get = "get{$key}"; + $object->setStyleValue("{$key}", $value); + $this->assertEquals($value, $object->$get()); + } + } + + /** + * Test set/get flip + */ + public function testSetGetFlip() + { + $expected=true; + $object = new Line(); + $object->setFlip($expected); + $this->assertEquals($expected, $object->isFlip()); + } + + /** + * Test set/get connectorType + */ + public function testSetGetConnectorType() + { + $expected=\PhpOffice\PhpWord\Style\Line::CONNECTOR_TYPE_STRAIGHT; + $object = new Line(); + $object->setConnectorType($expected); + $this->assertEquals($expected, $object->getConnectorType()); + } + + /** + * Test set/get weight + */ + public function testSetGetWeight() + { + $expected=10; + $object = new Line(); + $object->setWeight($expected); + $this->assertEquals($expected, $object->getWeight()); + } + + /** + * Test set/get color + */ + public function testSetGetColor() + { + $expected='red'; + $object = new Line(); + $object->setColor($expected); + $this->assertEquals($expected, $object->getColor()); + } + + /** + * Test set/get dash + */ + public function testSetGetDash() + { + $expected=\PhpOffice\PhpWord\Style\Line::DASH_STYLE_LONG_DASH_DOT_DOT; + $object = new Line(); + $object->setDash($expected); + $this->assertEquals($expected, $object->getDash()); + } + + /** + * Test set/get beginArrow + */ + public function testSetGetBeginArrow() + { + $expected=\PhpOffice\PhpWord\Style\Line::ARROW_STYLE_BLOCK; + $object = new Line(); + $object->setBeginArrow($expected); + $this->assertEquals($expected, $object->getBeginArrow()); + } + + /** + * Test set/get endArrow + */ + public function testSetGetEndArrow() + { + $expected=\PhpOffice\PhpWord\Style\Line::ARROW_STYLE_CLASSIC; + $object = new Line(); + $object->setEndArrow($expected); + $this->assertEquals($expected, $object->getEndArrow()); + } +} diff --git a/tests/PhpWord/Tests/Style/ListItemTest.php b/tests/PhpWord/Tests/Style/ListItemTest.php index 6eef720c..a97c8dd6 100644 --- a/tests/PhpWord/Tests/Style/ListItemTest.php +++ b/tests/PhpWord/Tests/Style/ListItemTest.php @@ -1,10 +1,18 @@ 1, 'format' => 'decimal', 'restart' => 1, + 'pStyle' => 'pStyle', 'suffix' => 'space', 'text' => '%1.', 'align' => 'left', diff --git a/tests/PhpWord/Tests/Style/NumberingTest.php b/tests/PhpWord/Tests/Style/NumberingTest.php new file mode 100644 index 00000000..e1575357 --- /dev/null +++ b/tests/PhpWord/Tests/Style/NumberingTest.php @@ -0,0 +1,61 @@ +object = new Numbering(); + $this->properties = array( + 'numId' => array(null, 1), + 'type' => array(null, 'singleLevel'), + ); + foreach ($this->properties as $property => $value) { + list($default, $expected) = $value; + $get = "get{$property}"; + $set = "set{$property}"; + + $this->assertEquals($default, $this->object->$get()); // Default value + + $this->object->$set($expected); + + $this->assertEquals($expected, $this->object->$get()); // New value + } + } + + /** + * Test get level + */ + public function testGetLevels() + { + $this->object = new Numbering(); + + $this->assertEmpty($this->object->getLevels()); + } +} diff --git a/tests/PhpWord/Tests/Style/ParagraphTest.php b/tests/PhpWord/Tests/Style/ParagraphTest.php index 413eb149..73540b0c 100644 --- a/tests/PhpWord/Tests/Style/ParagraphTest.php +++ b/tests/PhpWord/Tests/Style/ParagraphTest.php @@ -1,10 +1,18 @@ null, 'widowControl' => true, 'keepNext' => false, 'keepLines' => false, @@ -68,6 +75,8 @@ class ParagraphTest extends \PHPUnit_Framework_TestCase 'spacing' => 120, 'basedOn' => 'Normal', 'next' => 'Normal', + 'numStyle' => 'numStyle', + 'numLevel' => 1, 'widowControl' => false, 'keepNext' => true, 'keepLines' => true, @@ -89,6 +98,20 @@ class ParagraphTest extends \PHPUnit_Framework_TestCase } } + /** + * Test get null style value + */ + public function testGetNullStyleValue() + { + $object = new Paragraph(); + + $attributes = array('spacing', 'indent', 'hanging', 'spaceBefore', 'spaceAfter'); + foreach ($attributes as $key) { + $get = "get{$key}"; + $this->assertNull($object->$get()); + } + } + /** * Test tabs */ @@ -96,7 +119,7 @@ class ParagraphTest extends \PHPUnit_Framework_TestCase { $object = new Paragraph(); $object->setTabs(array(new Tab('left', 1550), new Tab('right', 5300))); - $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\Tabs', $object->getTabs()); + $this->assertCount(2, $object->getTabs()); } /** diff --git a/tests/PhpWord/Tests/Style/RowTest.php b/tests/PhpWord/Tests/Style/RowTest.php index ad193f80..679e9982 100644 --- a/tests/PhpWord/Tests/Style/RowTest.php +++ b/tests/PhpWord/Tests/Style/RowTest.php @@ -1,10 +1,18 @@ setSettingValue('_orientation', 'landscape'); - $this->assertEquals('landscape', $oSettings->getOrientation()); - $this->assertEquals(16838, $oSettings->getPageSizeW()); - $this->assertEquals(11906, $oSettings->getPageSizeH()); + $this->assertEquals('portrait', $oSettings->getOrientation()); + $this->assertEquals(Section::DEFAULT_WIDTH, $oSettings->getPageSizeW()); + $this->assertEquals(Section::DEFAULT_HEIGHT, $oSettings->getPageSizeH()); + $this->assertEquals('A4', $oSettings->getPaperSize()); - $oSettings->setSettingValue('_orientation', null); - $this->assertNull($oSettings->getOrientation()); - $this->assertEquals(11906, $oSettings->getPageSizeW()); - $this->assertEquals(16838, $oSettings->getPageSizeH()); + $oSettings->setSettingValue('orientation', 'landscape'); + $this->assertEquals('landscape', $oSettings->getOrientation()); + $this->assertEquals(Section::DEFAULT_HEIGHT, $oSettings->getPageSizeW()); + $this->assertEquals(Section::DEFAULT_WIDTH, $oSettings->getPageSizeH()); $iVal = rand(1, 1000); - $oSettings->setSettingValue('_borderSize', $iVal); + $oSettings->setSettingValue('borderSize', $iVal); $this->assertEquals(array($iVal, $iVal, $iVal, $iVal), $oSettings->getBorderSize()); $this->assertEquals($iVal, $oSettings->getBorderBottomSize()); $this->assertEquals($iVal, $oSettings->getBorderLeftSize()); $this->assertEquals($iVal, $oSettings->getBorderRightSize()); $this->assertEquals($iVal, $oSettings->getBorderTopSize()); - $oSettings->setSettingValue('_borderColor', 'FF00AA'); + $oSettings->setSettingValue('borderColor', 'FF00AA'); $this->assertEquals(array('FF00AA', 'FF00AA', 'FF00AA', 'FF00AA'), $oSettings->getBorderColor()); $this->assertEquals('FF00AA', $oSettings->getBorderBottomColor()); $this->assertEquals('FF00AA', $oSettings->getBorderLeftColor()); @@ -55,6 +62,14 @@ class SettingsTest extends \PHPUnit_Framework_TestCase $iVal = rand(1, 1000); $oSettings->setSettingValue('headerHeight', $iVal); $this->assertEquals($iVal, $oSettings->getHeaderHeight()); + + $oSettings->setSettingValue('lineNumbering', array()); + $oSettings->setSettingValue('lineNumbering', array('start' => 1, 'increment' => 1, + 'distance' => 240, 'restart' => 'newPage')); + $this->assertInstanceOf('PhpOffice\\PhpWord\\Style\\LineNumbering', $oSettings->getLineNumbering()); + + $oSettings->setSettingValue('lineNumbering', null); + $this->assertNull($oSettings->getLineNumbering()); } /** @@ -92,8 +107,8 @@ class SettingsTest extends \PHPUnit_Framework_TestCase $oSettings->setLandscape(); $this->assertEquals('landscape', $oSettings->getOrientation()); - $this->assertEquals(16838, $oSettings->getPageSizeW()); - $this->assertEquals(11906, $oSettings->getPageSizeH()); + $this->assertEquals(Section::DEFAULT_HEIGHT, $oSettings->getPageSizeW()); + $this->assertEquals(Section::DEFAULT_WIDTH, $oSettings->getPageSizeH()); } /** @@ -105,9 +120,9 @@ class SettingsTest extends \PHPUnit_Framework_TestCase $oSettings = new Section(); $oSettings->setPortrait(); - $this->assertNull($oSettings->getOrientation()); - $this->assertEquals(11906, $oSettings->getPageSizeW()); - $this->assertEquals(16838, $oSettings->getPageSizeH()); + $this->assertEquals('portrait', $oSettings->getOrientation()); + $this->assertEquals(Section::DEFAULT_WIDTH, $oSettings->getPageSizeW()); + $this->assertEquals(Section::DEFAULT_HEIGHT, $oSettings->getPageSizeH()); } /** @@ -235,12 +250,14 @@ class SettingsTest extends \PHPUnit_Framework_TestCase // Default $this->assertEquals(1, $oSettings->getColsNum()); + // Null value + $oSettings->setColsNum(); + $this->assertEquals(1, $oSettings->getColsNum()); + + // Random value $iVal = rand(1, 1000); $oSettings->setColsNum($iVal); $this->assertEquals($iVal, $oSettings->getColsNum()); - - $oSettings->setColsNum(); - $this->assertEquals(1, $oSettings->getColsNum()); } /** diff --git a/tests/PhpWord/Tests/Style/ShadingTest.php b/tests/PhpWord/Tests/Style/ShadingTest.php new file mode 100644 index 00000000..5a965e1d --- /dev/null +++ b/tests/PhpWord/Tests/Style/ShadingTest.php @@ -0,0 +1,52 @@ + array('clear', 'solid'), + 'color' => array(null, 'FF0000'), + 'fill' => array(null, 'FF0000'), + ); + foreach ($properties as $property => $value) { + list($default, $expected) = $value; + $get = "get{$property}"; + $set = "set{$property}"; + + $this->assertEquals($default, $object->$get()); // Default value + + $object->$set($expected); + + $this->assertEquals($expected, $object->$get()); // New value + } + } +} diff --git a/tests/PhpWord/Tests/Style/SpacingTest.php b/tests/PhpWord/Tests/Style/SpacingTest.php new file mode 100644 index 00000000..a4022b74 --- /dev/null +++ b/tests/PhpWord/Tests/Style/SpacingTest.php @@ -0,0 +1,53 @@ + array(null, 10), + 'after' => array(null, 10), + 'line' => array(null, 10), + 'rule' => array('auto', 'exact'), + ); + foreach ($properties as $property => $value) { + list($default, $expected) = $value; + $get = "get{$property}"; + $set = "set{$property}"; + + $this->assertEquals($default, $object->$get()); // Default value + + $object->$set($expected); + + $this->assertEquals($expected, $object->$get()); // New value + } + } +} diff --git a/tests/PhpWord/Tests/Style/TOCTest.php b/tests/PhpWord/Tests/Style/TOCTest.php index 2c10de8d..e6e32e6b 100644 --- a/tests/PhpWord/Tests/Style/TOCTest.php +++ b/tests/PhpWord/Tests/Style/TOCTest.php @@ -1,10 +1,18 @@ 9062, - 'tabLeader' => TOC::TABLEADER_DOT, - 'indent' => 200, + 'tabLeader' => array(TOC::TAB_LEADER_DOT, TOC::TAB_LEADER_UNDERSCORE), + 'tabPos' => array(9062, 10), + 'indent' => array(200, 10), ); - foreach ($properties as $key => $value) { - // set/get - $set = "set{$key}"; - $get = "get{$key}"; - $object->$set($value); - $this->assertEquals($value, $object->$get()); + foreach ($properties as $property => $value) { + list($default, $expected) = $value; + $get = "get{$property}"; + $set = "set{$property}"; - // setStyleValue - $object->setStyleValue("{$key}", null); - $this->assertEquals(null, $object->$get()); + $this->assertEquals($default, $object->$get()); // Default value + + $object->$set($expected); + + $this->assertEquals($expected, $object->$get()); // New value } } } diff --git a/tests/PhpWord/Tests/Style/TabTest.php b/tests/PhpWord/Tests/Style/TabTest.php new file mode 100644 index 00000000..784b4e47 --- /dev/null +++ b/tests/PhpWord/Tests/Style/TabTest.php @@ -0,0 +1,52 @@ + array(Tab::TAB_STOP_CLEAR, Tab::TAB_STOP_RIGHT), + 'leader' => array(Tab::TAB_LEADER_NONE, Tab::TAB_LEADER_DOT), + 'position' => array(0, 10), + ); + foreach ($properties as $property => $value) { + list($default, $expected) = $value; + $get = "get{$property}"; + $set = "set{$property}"; + + $this->assertEquals($default, $object->$get()); // Default value + + $object->$set($expected); + + $this->assertEquals($expected, $object->$get()); // New value + } + } +} diff --git a/tests/PhpWord/Tests/Style/TableTest.php b/tests/PhpWord/Tests/Style/TableTest.php index e5c3ab66..2afbab74 100644 --- a/tests/PhpWord/Tests/Style/TableTest.php +++ b/tests/PhpWord/Tests/Style/TableTest.php @@ -1,10 +1,18 @@ 'FF0000'); $styleFirstRow = array('borderBottomSize' => 3); + $object = new Table(); + $this->assertNull($object->getBgColor()); + $object = new Table($styleTable, $styleFirstRow); $this->assertEquals('FF0000', $object->getBgColor()); @@ -63,6 +74,9 @@ class TableTest extends \PHPUnit_Framework_TestCase 'cellMarginLeft' => 240, 'cellMarginRight' => 240, 'cellMarginBottom' => 240, + 'align' => 'center', + 'width' => 100, + 'unit' => 'pct', ); foreach ($attributes as $key => $value) { $set = "set{$key}"; @@ -135,6 +149,7 @@ class TableTest extends \PHPUnit_Framework_TestCase $this->assertEquals($value, $object->$get()); } $this->assertEquals($values, $object->getCellMargin()); + $this->assertTrue($object->hasMargin()); } /** diff --git a/tests/PhpWord/Tests/Style/TabsTest.php b/tests/PhpWord/Tests/Style/TabsTest.php deleted file mode 100644 index 26ee41d0..00000000 --- a/tests/PhpWord/Tests/Style/TabsTest.php +++ /dev/null @@ -1,47 +0,0 @@ -addParagraphStyle('tabbed', array('tabs' => array(new Tab('left', 1440, 'dot')))); - $doc = TestHelperDOCX::getDocument($phpWord); - $file = 'word/styles.xml'; - $path = '/w:styles/w:style[@w:styleId="tabbed"]/w:pPr/w:tabs/w:tab[1]'; - $element = $doc->getElement($path, $file); - $this->assertEquals('left', $element->getAttribute('w:val')); - $this->assertEquals(1440, $element->getAttribute('w:pos')); - $this->assertEquals('dot', $element->getAttribute('w:leader')); - } -} diff --git a/tests/PhpWord/Tests/Style/TextBoxTest.php b/tests/PhpWord/Tests/Style/TextBoxTest.php new file mode 100644 index 00000000..cd2d8695 --- /dev/null +++ b/tests/PhpWord/Tests/Style/TextBoxTest.php @@ -0,0 +1,305 @@ + 200, + 'height' => 200, + 'align' => 'left', + 'marginTop' => 240, + 'marginLeft' => 240, + 'wrappingStyle' => 'inline', + 'positioning' => 'absolute', + 'posHorizontal' => 'center', + 'posVertical' => 'top', + 'posHorizontalRel' => 'margin', + 'posVerticalRel' => 'page', + 'innerMarginTop' => '5', + 'innerMarginRight' => '5', + 'innerMarginBottom' => '5', + 'innerMarginLeft' => '5', + 'borderSize' => '2', + 'borderColor' => 'red' + ); + foreach ($properties as $key => $value) { + $set = "set{$key}"; + $get = "get{$key}"; + $object->$set($value); + $this->assertEquals($value, $object->$get()); + } + } + + /** + * Test setStyleValue method + */ + public function testSetStyleValue() + { + $object = new TextBox(); + + $properties = array( + 'width' => 200, + 'height' => 200, + 'align' => 'left', + 'marginTop' => 240, + 'marginLeft' => 240, + 'wrappingStyle' => 'inline', + 'positioning' => 'absolute', + 'posHorizontal' => 'center', + 'posVertical' => 'top', + 'posHorizontalRel' => 'margin', + 'posVerticalRel' => 'page', + 'innerMarginTop' => '5', + 'innerMarginRight' => '5', + 'innerMarginBottom' => '5', + 'innerMarginLeft' => '5', + 'borderSize' => '2', + 'borderColor' => 'red' + ); + foreach ($properties as $key => $value) { + $get = "get{$key}"; + $object->setStyleValue("{$key}", $value); + $this->assertEquals($value, $object->$get()); + } + } + + /** + * Test setWrappingStyle exception + * + * @expectedException \InvalidArgumentException + */ + public function testSetWrappingStyleException() + { + $object = new TextBox(); + $object->setWrappingStyle('foo'); + } + + /** + * Test set/get width + */ + public function testSetGetWidth() + { + $expected=200; + $object = new TextBox(); + $object->setWidth($expected); + $this->assertEquals($expected, $object->getWidth()); + } + + /** + * Test set/get height + */ + public function testSetGetHeight() + { + $expected=200; + $object = new TextBox(); + $object->setHeight($expected); + $this->assertEquals($expected, $object->getHeight()); + } + + /** + * Test set/get height + */ + public function testSetGetAlign() + { + $expected='left'; + $object = new TextBox(); + $object->setAlign($expected); + $this->assertEquals($expected, $object->getAlign()); + } + + /** + * Test set/get marginTop + */ + public function testSetGetMarginTop() + { + $expected=5; + $object = new TextBox(); + $object->setMarginTop($expected); + $this->assertEquals($expected, $object->getMarginTop()); + } + + /** + * Test set/get marginLeft + */ + public function testSetGetMarginLeft() + { + $expected=5; + $object = new TextBox(); + $object->setMarginLeft($expected); + $this->assertEquals($expected, $object->getMarginLeft()); + } + /** + * Test set/get innerMarginTop + */ + public function testSetGetInnerMarginTop() + { + $expected=5; + $object = new TextBox(); + $object->setInnerMarginTop($expected); + $this->assertEquals($expected, $object->getInnerMarginTop()); + } + + /** + * Test set/get wrappingStyle + */ + public function testSetGetWrappingStyle() + { + $expected='inline'; + $object = new TextBox(); + $object->setWrappingStyle($expected); + $this->assertEquals($expected, $object->getWrappingStyle()); + } + + /** + * Test set/get positioning + */ + public function testSetGetPositioning() + { + $expected='absolute'; + $object = new TextBox(); + $object->setPositioning($expected); + $this->assertEquals($expected, $object->getPositioning()); + } + + /** + * Test set/get posHorizontal + */ + public function testSetGetPosHorizontal() + { + $expected='center'; + $object = new TextBox(); + $object->setPosHorizontal($expected); + $this->assertEquals($expected, $object->getPosHorizontal()); + } + + /** + * Test set/get posVertical + */ + public function testSetGetPosVertical() + { + $expected='top'; + $object = new TextBox(); + $object->setPosVertical($expected); + $this->assertEquals($expected, $object->getPosVertical()); + } + + /** + * Test set/get posHorizontalRel + */ + public function testSetGetPosHorizontalRel() + { + $expected='margin'; + $object = new TextBox(); + $object->setPosHorizontalRel($expected); + $this->assertEquals($expected, $object->getPosHorizontalRel()); + } + + /** + * Test set/get posVerticalRel + */ + public function testSetGetPosVerticalRel() + { + $expected='page'; + $object = new TextBox(); + $object->setPosVerticalRel($expected); + $this->assertEquals($expected, $object->getPosVerticalRel()); + } + + + /** + * Test set/get innerMarginRight + */ + public function testSetGetInnerMarginRight() + { + $expected=5; + $object = new TextBox(); + $object->setInnerMarginRight($expected); + $this->assertEquals($expected, $object->getInnerMarginRight()); + } + + /** + * Test set/get innerMarginBottom + */ + public function testSetGetInnerMarginBottom() + { + $expected=5; + $object = new TextBox(); + $object->setInnerMarginBottom($expected); + $this->assertEquals($expected, $object->getInnerMarginBottom()); + } + + /** + * Test set/get innerMarginLeft + */ + public function testSetGetInnerMarginLeft() + { + $expected=5; + $object = new TextBox(); + $object->setInnerMarginLeft($expected); + $this->assertEquals($expected, $object->getInnerMarginLeft()); + } + + /** + * Test set/get innerMarginLeft + */ + public function testSetGetInnerMargin() + { + $expected=5; + $object = new TextBox(); + $object->setInnerMargin($expected); + $this->assertEquals(array($expected, $expected, $expected, $expected), $object->getInnerMargin()); + } + + /** + * Test set/get borderSize + */ + public function testSetGetBorderSize() + { + $expected=2; + $object = new TextBox(); + $object->setBorderSize($expected); + $this->assertEquals($expected, $object->getBorderSize()); + } + + /** + * Test set/get borderColor + */ + public function testSetGetBorderColor() + { + $expected='red'; + $object = new TextBox(); + $object->setBorderColor($expected); + $this->assertEquals($expected, $object->getBorderColor()); + } +} diff --git a/tests/PhpWord/Tests/StyleTest.php b/tests/PhpWord/Tests/StyleTest.php index 4ace72b6..6165e4fd 100644 --- a/tests/PhpWord/Tests/StyleTest.php +++ b/tests/PhpWord/Tests/StyleTest.php @@ -1,10 +1,18 @@ 'center'); $font = array('italic' => true, '_bold' => true); $table = array('bgColor' => 'CCCCCC'); - $styles = array('Paragraph' => 'Paragraph', 'Font' => 'Font', - 'Link' => 'Font', 'Table' => 'Table', - 'Heading_1' => 'Font', 'Normal' => 'Paragraph'); - $elementCount = 6; + $styles = array( + 'Paragraph' => 'Paragraph', + 'Font' => 'Font', + 'Link' => 'Font', + 'Table' => 'Table', + 'Heading_1' => 'Font', + 'Normal' => 'Paragraph', + ); Style::addParagraphStyle('Paragraph', $paragraph); Style::addFontStyle('Font', $font); Style::addLinkStyle('Link', $font); - Style::addTableStyle('Table', $table); + // @todo Style::addNumberingStyle Style::addTitleStyle(1, $font); + Style::addTableStyle('Table', $table); Style::setDefaultParagraphStyle($paragraph); - $this->assertEquals($elementCount, count(Style::getStyles())); + $this->assertCount(count($styles), Style::getStyles()); foreach ($styles as $name => $style) { $this->assertInstanceOf("PhpOffice\\PhpWord\\Style\\{$style}", Style::getStyle($name)); } $this->assertNull(Style::getStyle('Unknown')); Style::resetStyles(); - $this->assertEquals(0, count(Style::getStyles())); - + $this->assertCount(0, Style::getStyles()); } /** - * Set default paragraph style + * Test default paragraph style + * + * @covers ::setDefaultParagraphStyle + * @test */ public function testDefaultParagraphStyle() { diff --git a/tests/PhpWord/Tests/TemplateTest.php b/tests/PhpWord/Tests/TemplateTest.php index f99ce294..57ee229e 100644 --- a/tests/PhpWord/Tests/TemplateTest.php +++ b/tests/PhpWord/Tests/TemplateTest.php @@ -1,15 +1,22 @@ assertEquals('', $object->write()); + } + } + + /** + * Test write element text + */ + public function testWriteTextElement() + { + $object = new Text(new HTML(), new TextElement('A')); + $object->setOpeningText('-'); + $object->setClosingText('-'); + $object->setWithoutP(true); + + $this->assertEquals('-A-', $object->write()); + } +} diff --git a/tests/PhpWord/Tests/Writer/HTML/PartTest.php b/tests/PhpWord/Tests/Writer/HTML/PartTest.php new file mode 100644 index 00000000..93e9a98e --- /dev/null +++ b/tests/PhpWord/Tests/Writer/HTML/PartTest.php @@ -0,0 +1,36 @@ +getParentWriter(); + } +} diff --git a/tests/PhpWord/Tests/Writer/HTML/StyleTest.php b/tests/PhpWord/Tests/Writer/HTML/StyleTest.php new file mode 100644 index 00000000..8af1e479 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/HTML/StyleTest.php @@ -0,0 +1,39 @@ +assertEquals('', $object->write()); + } + } +} diff --git a/tests/PhpWord/Tests/Writer/HTMLTest.php b/tests/PhpWord/Tests/Writer/HTMLTest.php new file mode 100644 index 00000000..c3339d1a --- /dev/null +++ b/tests/PhpWord/Tests/Writer/HTMLTest.php @@ -0,0 +1,120 @@ +assertInstanceOf('PhpOffice\\PhpWord\\PhpWord', $object->getPhpWord()); + } + + /** + * Construct with null + * + * @expectedException \PhpOffice\PhpWord\Exception\Exception + * @expectedExceptionMessage No PhpWord assigned. + */ + public function testConstructWithNull() + { + $object = new HTML(); + $object->getPhpWord(); + } + + /** + * Save + */ + public function testSave() + { + $localImage = __DIR__ . "/../_files/images/PhpWord.png"; + $archiveImage = 'zip://' . __DIR__ . '/../_files/documents/reader.docx#word/media/image1.jpeg'; + $gdImage = 'http://php.net/images/logos/php-med-trans-light.gif'; + $objectSrc = __DIR__ . "/../_files/documents/sheet.xls"; + $file = __DIR__ . "/../_files/temp.html"; + + $phpWord = new PhpWord(); + + $docProps = $phpWord->getDocInfo(); + $docProps->setTitle('HTML Test'); + + $phpWord->addTitleStyle(1, array('bold' => true)); + $phpWord->addFontStyle('Font', array('name' => 'Verdana', 'size' => 11, + 'color' => 'FF0000', 'fgColor' => 'FF0000')); + $phpWord->addParagraphStyle('Paragraph', array('align' => 'center', 'spaceAfter' => 20, 'spaceBefore' => 20)); + $section = $phpWord->addSection(); + $section->addText('Test 1', 'Font', 'Paragraph'); + $section->addTextBreak(); + $section->addText('Test 2', array('name' => 'Tahoma', 'bold' => true, 'italic' => true, 'subscript' => true)); + $section->addLink('http://test.com'); + $section->addTitle('Test', 1); + $section->addPageBreak(); + $section->addListItem('Test'); + $section->addImage($localImage); + $section->addImage($archiveImage); + $section->addImage($gdImage); + $section->addObject($objectSrc); + $section->addFootnote(); + $section->addEndnote(); + + $section = $phpWord->addSection(); + + $textrun = $section->addTextRun(array('align' => 'center')); + $textrun->addText('Test 3'); + $textrun->addTextBreak(); + + $textrun = $section->addTextRun('Paragraph'); + $textrun->addLink('http://test.com'); + $textrun->addImage($localImage); + $textrun->addFootnote()->addText('Footnote'); + $textrun->addEndnote()->addText('Endnote'); + + $section = $phpWord->addSection(); + + $table = $section->addTable(); + $cell = $table->addRow()->addCell(); + $cell->addText('Test 1', array('superscript' => true, 'underline' => 'dash', 'strikethrough' => true)); + $cell->addTextRun(); + $cell->addLink('http://test.com'); + $cell->addTextBreak(); + $cell->addListItem('Test'); + $cell->addImage($localImage); + $cell->addObject($objectSrc); + $cell->addFootnote(); + $cell->addEndnote(); + $cell = $table->addRow()->addCell(); + + $writer = new HTML($phpWord); + $writer->save($file); + + $this->assertTrue(file_exists($file)); + + unlink($file); + } +} diff --git a/tests/PhpWord/Tests/Writer/ODText/AbstractWriterPartTest.php b/tests/PhpWord/Tests/Writer/ODText/AbstractWriterPartTest.php deleted file mode 100644 index a8863087..00000000 --- a/tests/PhpWord/Tests/Writer/ODText/AbstractWriterPartTest.php +++ /dev/null @@ -1,50 +0,0 @@ -getMockForAbstractClass( - 'PhpOffice\\PhpWord\\Writer\\ODText\\AbstractWriterPart' - ); - $object->setParentWriter(new ODText()); - $this->assertEquals( - new ODText(), - $object->getParentWriter() - ); - } - - /** - * covers ::getParentWriter - * @expectedException Exception - * @expectedExceptionMessage No parent WriterInterface assigned. - */ - public function testSetGetParentWriterNull() - { - $object = $this->getMockForAbstractClass( - 'PhpOffice\\PhpWord\\Writer\\ODText\\AbstractWriterPart' - ); - $object->getParentWriter(); - } -} diff --git a/tests/PhpWord/Tests/Writer/ODText/ContentTest.php b/tests/PhpWord/Tests/Writer/ODText/ContentTest.php deleted file mode 100644 index 4808de9e..00000000 --- a/tests/PhpWord/Tests/Writer/ODText/ContentTest.php +++ /dev/null @@ -1,64 +0,0 @@ - - */ - public function testWriteContent() - { - $imageSrc = __DIR__ . "/../../_files/images/PhpWord.png"; - $objectSrc = __DIR__ . "/../../_files/documents/sheet.xls"; - $expected = 'Expected'; - - $phpWord = new PhpWord(); - $phpWord->setDefaultFontName('Verdana'); - $phpWord->addFontStyle('Font', array('size' => 11)); - $phpWord->addParagraphStyle('Paragraph', array('align' => 'center')); - $section = $phpWord->addSection(); - $section->addText($expected); - $section->addText('Test font style', 'Font'); - $section->addText('Test paragraph style', null, 'Paragraph'); - $section->addTextBreak(); - $section->addLink('http://test.com', 'Test link'); - $section->addTitle('Test title', 1); - $section->addPageBreak(); - $section->addTable(); - $section->addListItem('Test list item'); - $section->addImage($imageSrc); - $section->addObject($objectSrc); - $section->addTOC(); - $textrun = $section->addTextRun(); - $textrun->addText('Test text run'); - $doc = TestHelperDOCX::getDocument($phpWord, 'ODText'); - - $element = "/office:document-content/office:body/office:text/text:p"; - $this->assertEquals($expected, $doc->getElement($element, 'content.xml')->nodeValue); - } -} diff --git a/tests/PhpWord/Tests/Writer/ODText/ElementTest.php b/tests/PhpWord/Tests/Writer/ODText/ElementTest.php new file mode 100644 index 00000000..fa9532d1 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/ODText/ElementTest.php @@ -0,0 +1,42 @@ +write(); + + $this->assertEquals('', $xmlWriter->getData()); + } + } +} diff --git a/tests/PhpWord/Tests/Writer/ODText/Part/AbstractPartTest.php b/tests/PhpWord/Tests/Writer/ODText/Part/AbstractPartTest.php new file mode 100644 index 00000000..92fab26f --- /dev/null +++ b/tests/PhpWord/Tests/Writer/ODText/Part/AbstractPartTest.php @@ -0,0 +1,58 @@ +getMockForAbstractClass( + 'PhpOffice\\PhpWord\\Writer\\ODText\\Part\\AbstractPart' + ); + $object->setParentWriter(new ODText()); + $this->assertEquals( + new ODText(), + $object->getParentWriter() + ); + } + + /** + * covers ::getParentWriter + * @expectedException Exception + * @expectedExceptionMessage No parent WriterInterface assigned. + */ + public function testSetGetParentWriterNull() + { + $object = $this->getMockForAbstractClass( + 'PhpOffice\\PhpWord\\Writer\\ODText\\Part\\AbstractPart' + ); + $object->getParentWriter(); + } +} diff --git a/tests/PhpWord/Tests/Writer/ODText/Part/ContentTest.php b/tests/PhpWord/Tests/Writer/ODText/Part/ContentTest.php new file mode 100644 index 00000000..85ddada6 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/ODText/Part/ContentTest.php @@ -0,0 +1,110 @@ +getDocInfo(); + $docProps->setCustomProperty('Company', 'PHPWord'); + + $phpWord->setDefaultFontName('Verdana'); + $phpWord->addFontStyle('Font', array('size' => 11)); + $phpWord->addParagraphStyle('Paragraph', array('align' => 'center')); + $phpWord->addTableStyle('tblStyle', array('width' => 100)); + + $section = $phpWord->addSection(array('colsNum' => 2)); + $section->addText($expected); + $section->addText('Test font style', 'Font'); + $section->addText('Test paragraph style', null, 'Paragraph'); + $section->addLink('http://test.com', 'Test link'); + $section->addTitle('Test title', 1); + $section->addTextBreak(); + $section->addPageBreak(); + $section->addListItem('Test list item'); + $section->addImage($imageSrc, array('width' => 50)); + $section->addObject($objectSrc); + $section->addTOC(); + + $textrun = $section->addTextRun(); + $textrun->addText('Test text run'); + + $table = $section->addTable(array('width' => 50)); + $cell = $table->addRow()->addCell(); + $cell = $table->addRow()->addCell(); + $cell->addText('Test'); + $cell->addLink('http://test.com', 'Test link'); + $cell->addTextBreak(); + $cell->addListItem('Test list item'); + $cell->addImage($imageSrc); + $cell->addObject($objectSrc); + $textrun = $cell->addTextRun(); + $textrun->addText('Test text run'); + + $footer = $section->addFooter(); + $footer->addPreserveText('{PAGE}'); + + $table = $section->addTable('tblStyle')->addRow()->addCell(); + + $doc = TestHelperDOCX::getDocument($phpWord, 'ODText'); + + $element = "/office:document-content/office:body/office:text/text:section/text:p"; + $this->assertEquals($expected, $doc->getElement($element, 'content.xml')->nodeValue); + } + + /** + * Test no paragraph style + */ + public function testWriteNoStyle() + { + $phpWord = new PhpWord(); + $phpWord->addFontStyle('Font', array('size' => 11)); + + $doc = TestHelperDOCX::getDocument($phpWord, 'ODText'); + + $element = "/office:document-content/office:automatic-styles/style:style"; + $this->assertTrue($doc->elementExists($element, 'content.xml')); + } +} diff --git a/tests/PhpWord/Tests/Writer/ODText/StyleTest.php b/tests/PhpWord/Tests/Writer/ODText/StyleTest.php new file mode 100644 index 00000000..cd5ea0eb --- /dev/null +++ b/tests/PhpWord/Tests/Writer/ODText/StyleTest.php @@ -0,0 +1,41 @@ +write(); + + $this->assertEquals('', $xmlWriter->getData()); + } + } +} diff --git a/tests/PhpWord/Tests/Writer/ODTextTest.php b/tests/PhpWord/Tests/Writer/ODTextTest.php index fad3a6c0..25b8095b 100644 --- a/tests/PhpWord/Tests/Writer/ODTextTest.php +++ b/tests/PhpWord/Tests/Writer/ODTextTest.php @@ -1,10 +1,18 @@ assertEquals('./', $object->getDiskCachingDirectory()); foreach (array('Content', 'Manifest', 'Meta', 'Mimetype', 'Styles') as $part) { $this->assertInstanceOf( - "PhpOffice\\PhpWord\\Writer\\ODText\\{$part}", + "PhpOffice\\PhpWord\\Writer\\ODText\\Part\\{$part}", $object->getWriterPart($part) ); $this->assertInstanceOf( @@ -71,7 +79,7 @@ class ODTextTest extends \PHPUnit_Framework_TestCase $section->addLink('http://test.com'); $section->addTitle('Test', 1); $section->addPageBreak(); - $section->addTable(); + $section->addTable()->addRow()->addCell()->addText('Test'); $section->addListItem('Test'); $section->addImage($imageSrc); $section->addObject($objectSrc); @@ -101,18 +109,6 @@ class ODTextTest extends \PHPUnit_Framework_TestCase $writer->save('php://output'); } - /** - * Save with no PhpWord object assigned - * - * @expectedException \PhpOffice\PhpWord\Exception\Exception - * @expectedExceptionMessage PhpWord object unassigned. - */ - public function testSaveException() - { - $writer = new ODText(); - $writer->save(); - } - /** * Get writer part return null value */ @@ -129,7 +125,7 @@ class ODTextTest extends \PHPUnit_Framework_TestCase { $object = new ODText(); $object->setUseDiskCaching(true, PHPWORD_TESTS_BASE_DIR); - $this->assertTrue($object->getUseDiskCaching()); + $this->assertTrue($object->isUseDiskCaching()); $this->assertEquals(PHPWORD_TESTS_BASE_DIR, $object->getDiskCachingDirectory()); } diff --git a/tests/PhpWord/Tests/Writer/PDF/DomPDFTest.php b/tests/PhpWord/Tests/Writer/PDF/DomPDFTest.php new file mode 100644 index 00000000..476c9011 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/PDF/DomPDFTest.php @@ -0,0 +1,77 @@ +addSection(); + $section->addText('Test 1'); + + $rendererName = Settings::PDF_RENDERER_DOMPDF; + $rendererLibraryPath = realpath(PHPWORD_TESTS_BASE_DIR . '/../vendor/dompdf/dompdf'); + Settings::setPdfRenderer($rendererName, $rendererLibraryPath); + $writer = new PDF($phpWord); + $writer->save($file); + + $this->assertTrue(file_exists($file)); + + unlink($file); + } + + /** + * Test set/get abstract renderer properties + */ + public function testSetGetAbstractRendererProperties() + { + define('DOMPDF_ENABLE_AUTOLOAD', false); + + $rendererName = Settings::PDF_RENDERER_DOMPDF; + $rendererLibraryPath = realpath(PHPWORD_TESTS_BASE_DIR . '/../vendor/dompdf/dompdf'); + Settings::setPdfRenderer($rendererName, $rendererLibraryPath); + $writer = new PDF(new PhpWord()); + + $writer->setFont('arial'); + $this->assertEquals('arial', $writer->getFont()); + + $writer->setPaperSize(); + $this->assertEquals(9, $writer->getPaperSize()); + + $writer->setOrientation(); + $this->assertEquals('default', $writer->getOrientation()); + + $writer->setTempDir(Settings::getTempDir()); + $this->assertEquals(Settings::getTempDir(), $writer->getTempDir()); + } +} diff --git a/tests/PhpWord/Tests/Writer/PDF/MPDFTest.php b/tests/PhpWord/Tests/Writer/PDF/MPDFTest.php new file mode 100644 index 00000000..4728b7f1 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/PDF/MPDFTest.php @@ -0,0 +1,51 @@ +addSection(); + $section->addText('Test 1'); + + $rendererName = Settings::PDF_RENDERER_MPDF; + $rendererLibraryPath = realpath(PHPWORD_TESTS_BASE_DIR . '/../vendor/mpdf/mpdf'); + Settings::setPdfRenderer($rendererName, $rendererLibraryPath); + $writer = new PDF($phpWord); + $writer->save($file); + + $this->assertTrue(file_exists($file)); + + unlink($file); + } +} diff --git a/tests/PhpWord/Tests/Writer/PDF/TCPDFTest.php b/tests/PhpWord/Tests/Writer/PDF/TCPDFTest.php new file mode 100644 index 00000000..c73f0043 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/PDF/TCPDFTest.php @@ -0,0 +1,51 @@ +addSection(); + $section->addText('Test 1'); + + $rendererName = Settings::PDF_RENDERER_TCPDF; + $rendererLibraryPath = realpath(PHPWORD_TESTS_BASE_DIR . '/../vendor/tecnick.com/tcpdf'); + Settings::setPdfRenderer($rendererName, $rendererLibraryPath); + $writer = new PDF($phpWord); + $writer->save($file); + + $this->assertTrue(file_exists($file)); + + unlink($file); + } +} diff --git a/tests/PhpWord/Tests/Writer/PDFTest.php b/tests/PhpWord/Tests/Writer/PDFTest.php new file mode 100644 index 00000000..87814b41 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/PDFTest.php @@ -0,0 +1,60 @@ +save($file); + + $this->assertTrue(file_exists($file)); + + unlink($file); + } + + /** + * Test construct exception + * + * @expectedException \PhpOffice\PhpWord\Exception\Exception + * @expectedExceptionMessage PDF rendering library or library path has not been defined. + */ + public function testConstructException() + { + $writer = new PDF(new PhpWord()); + $writer->save(); + } +} diff --git a/tests/PhpWord/Tests/Writer/RTF/ElementTest.php b/tests/PhpWord/Tests/Writer/RTF/ElementTest.php new file mode 100644 index 00000000..e090b349 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/RTF/ElementTest.php @@ -0,0 +1,41 @@ +assertEquals('', $object->write()); + } + } +} diff --git a/tests/PhpWord/Tests/Writer/RTF/StyleTest.php b/tests/PhpWord/Tests/Writer/RTF/StyleTest.php new file mode 100644 index 00000000..542e34fe --- /dev/null +++ b/tests/PhpWord/Tests/Writer/RTF/StyleTest.php @@ -0,0 +1,39 @@ +assertEquals('', $object->write()); + } + } +} diff --git a/tests/PhpWord/Tests/Writer/RTFTest.php b/tests/PhpWord/Tests/Writer/RTFTest.php index 9cc7ed71..5b983b35 100644 --- a/tests/PhpWord/Tests/Writer/RTFTest.php +++ b/tests/PhpWord/Tests/Writer/RTFTest.php @@ -1,10 +1,18 @@ addFontStyle('Font', array('name' => 'Verdana', 'size' => 11, 'color' => 'FF0000', 'fgColor' => 'FF0000')); + $phpWord->addFontStyle('Font', array('name' => 'Verdana', 'size' => 11, + 'color' => 'FF0000', 'fgColor' => '00FF00')); $phpWord->addParagraphStyle('Paragraph', array('align' => 'center')); $section = $phpWord->addSection(); $section->addText('Test 1', 'Font', 'Paragraph'); @@ -59,7 +68,16 @@ class RTFTest extends \PHPUnit_Framework_TestCase $section->addLink('http://test.com'); $section->addTitle('Test', 1); $section->addPageBreak(); - $section->addTable(); + + // Rowspan + $table = $section->addTable(); + $table->addRow()->addCell(null, array('vMerge' => 'restart'))->addText('Test'); + $table->addRow()->addCell(null, array('vMerge' => 'continue'))->addText('Test'); + + // Nested table + $cell = $section->addTable()->addRow()->addCell(); + $cell->addTable()->addRow()->addCell(); + $section->addListItem('Test'); $section->addImage($imageSrc); $section->addObject($objectSrc); @@ -73,7 +91,7 @@ class RTFTest extends \PHPUnit_Framework_TestCase $this->assertTrue(file_exists($file)); - unlink($file); + @unlink($file); } /** @@ -89,16 +107,4 @@ class RTFTest extends \PHPUnit_Framework_TestCase $writer = new RTF($phpWord); $writer->save('php://output'); } - - /** - * Save with no PhpWord object assigned - * - * @expectedException \PhpOffice\PhpWord\Exception\Exception - * @expectedExceptionMessage PhpWord object unassigned. - */ - public function testSaveException() - { - $writer = new RTF(); - $writer->save(); - } } diff --git a/tests/PhpWord/Tests/Writer/Word2007/AbstractWriterPartTest.php b/tests/PhpWord/Tests/Writer/Word2007/AbstractWriterPartTest.php deleted file mode 100644 index 33051d6f..00000000 --- a/tests/PhpWord/Tests/Writer/Word2007/AbstractWriterPartTest.php +++ /dev/null @@ -1,51 +0,0 @@ -getMockForAbstractClass( - 'PhpOffice\\PhpWord\\Writer\\Word2007\\AbstractWriterPart' - ); - $object->setParentWriter(new Word2007()); - $this->assertEquals( - new Word2007(), - $object->getParentWriter() - ); - } - - /** - * covers ::getParentWriter - * @expectedException Exception - * @expectedExceptionMessage No parent WriterInterface assigned. - */ - public function testSetGetParentWriterNull() - { - $object = $this->getMockForAbstractClass( - 'PhpOffice\\PhpWord\\Writer\\Word2007\\AbstractWriterPart' - ); - $object->getParentWriter(); - } -} diff --git a/tests/PhpWord/Tests/Writer/Word2007/DocumentTest.php b/tests/PhpWord/Tests/Writer/Word2007/DocumentTest.php deleted file mode 100644 index fa11638e..00000000 --- a/tests/PhpWord/Tests/Writer/Word2007/DocumentTest.php +++ /dev/null @@ -1,128 +0,0 @@ -addSection(); - $settings = $section->getSettings(); - $settings->setLandscape(); - $settings->setPageNumberingStart(2); - $settings->setBorderSize(240); - $settings->setBreakType('nextPage'); - - $doc = TestHelperDOCX::getDocument($phpWord); - $element = $doc->getElement('/w:document/w:body/w:sectPr/w:pgNumType'); - - $this->assertEquals(2, $element->getAttribute('w:start')); - } - - /** - * Write elements - */ - public function testElements() - { - $objectSrc = __DIR__ . "/../../_files/documents/sheet.xls"; - - $phpWord = new PhpWord(); - $phpWord->addTitleStyle(1, array('color' => '333333', 'bold'=>true)); - $phpWord->addTitleStyle(2, array('color'=>'666666')); - $section = $phpWord->addSection(); - $section->addTOC(); - $section->addPageBreak(); - $section->addTitle('Title 1', 1); - $section->addListItem('List Item 1', 0); - $section->addListItem('List Item 2', 0); - $section->addListItem('List Item 3', 0); - $section = $phpWord->addSection(); - $section->addTitle('Title 2', 2); - $section->addObject($objectSrc); - $doc = TestHelperDOCX::getDocument($phpWord); - - // TOC - $element = $doc->getElement('/w:document/w:body/w:p[1]/w:pPr/w:tabs/w:tab'); - $this->assertEquals('right', $element->getAttribute('w:val')); - $this->assertEquals('dot', $element->getAttribute('w:leader')); - $this->assertEquals(9062, $element->getAttribute('w:pos')); - - // Page break - $element = $doc->getElement('/w:document/w:body/w:p[4]/w:r/w:br'); - $this->assertEquals('page', $element->getAttribute('w:type')); - - // Title - $element = $doc->getElement('/w:document/w:body/w:p[5]/w:pPr/w:pStyle'); - $this->assertEquals('Heading1', $element->getAttribute('w:val')); - - // List item - $element = $doc->getElement('/w:document/w:body/w:p[6]/w:pPr/w:numPr/w:numId'); - $this->assertEquals(3, $element->getAttribute('w:val')); - - // Object - $element = $doc->getElement('/w:document/w:body/w:p[11]/w:r/w:object/o:OLEObject'); - $this->assertEquals('Embed', $element->getAttribute('Type')); - } - - /** - * Write element with some styles - */ - public function testElementStyles() - { - $objectSrc = __DIR__ . "/../../_files/documents/sheet.xls"; - - $phpWord = new PhpWord(); - $phpWord->addParagraphStyle('pStyle', array('align' => 'center')); // Style #1 - $phpWord->addFontStyle('fStyle', array('size' => '20')); // Style #2 - $phpWord->addTitleStyle(1, array('color' => '333333', 'bold' => true)); // Style #3 - $fontStyle = new Font('text', array('align' => 'center')); - $section = $phpWord->addSection(); - $section->addListItem('List Item', 0, null, null, 'pStyle'); // Style #4 - $section->addObject($objectSrc, array('align' => 'center')); - $section->addTOC($fontStyle); - $section->addTitle('Title 1', 1); - $section->addTOC('fStyle'); - $doc = TestHelperDOCX::getDocument($phpWord); - - // List item - $element = $doc->getElement('/w:document/w:body/w:p[1]/w:pPr/w:numPr/w:numId'); - $this->assertEquals(4, $element->getAttribute('w:val')); - - // Object - $element = $doc->getElement('/w:document/w:body/w:p[2]/w:r/w:object/o:OLEObject'); - $this->assertEquals('Embed', $element->getAttribute('Type')); - - // TOC - $element = $doc->getElement('/w:document/w:body/w:p[3]/w:pPr/w:tabs/w:tab'); - $this->assertEquals('right', $element->getAttribute('w:val')); - $this->assertEquals('dot', $element->getAttribute('w:leader')); - $this->assertEquals(9062, $element->getAttribute('w:pos')); - } -} diff --git a/tests/PhpWord/Tests/Writer/Word2007/ElementTest.php b/tests/PhpWord/Tests/Writer/Word2007/ElementTest.php new file mode 100644 index 00000000..92a74c15 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/Word2007/ElementTest.php @@ -0,0 +1,219 @@ +write(); + + $this->assertEquals('', $xmlWriter->getData()); + } + } + + /** + * Test line element + */ + public function testLineElement() + { + $phpWord = new PhpWord(); + $section = $phpWord->addSection(); + + $section->addLine(array('width' => 1000, 'height' => 1000, 'positioning' => 'absolute', 'flip' => true)); + $doc = TestHelperDOCX::getDocument($phpWord); + + $element = "/w:document/w:body/w:p/w:r/w:pict/v:shapetype"; + $this->assertTrue($doc->elementExists($element)); + } + + /** + * Test shape elements + */ + public function testShapeElements() + { + $phpWord = new PhpWord(); + $section = $phpWord->addSection(); + + // Arc + $section->addShape( + 'arc', + array( + 'points' => '-90 20', + 'frame' => array('width' => 120, 'height' => 120), + 'outline' => array('color' => '#333333', 'weight' => 2, 'startArrow' => 'oval', 'endArrow' => 'open'), + ) + ); + + // Curve + $section->addShape( + 'curve', + array( + 'points' => '1,100 200,1 1,50 200,50', 'connector' => 'elbow', + 'outline' => array('color' => '#66cc00', 'weight' => 2, 'dash' => 'dash', + 'startArrow' => 'diamond', 'endArrow' => 'block'), + ) + ); + + // Line + $section->addShape( + 'line', + array( + 'points' => '1,1 150,30', + 'outline' => array('color' => '#cc00ff', 'line' => 'thickThin', 'weight' => 3, + 'startArrow' => 'oval', 'endArrow' => 'classic', 'endCap' => 'round'), + ) + ); + + // Polyline + $section->addShape( + 'polyline', + array( + 'points' => '1,30 20,10 55,20 75,10 100,40 115,50, 120,15 200,50', + 'outline' => array('color' => '#cc6666', 'weight' => 2, + 'startArrow' => 'none', 'endArrow' => 'classic'), + ) + ); + + // Rectangle + $section->addShape( + 'rect', + array( + 'roundness' => 0.2, + 'frame' => array('width' => 100, 'height' => 100, 'left' => 1, 'top' => 1), + 'fill' => array('color' => '#FFCC33'), + 'outline' => array('color' => '#990000', 'weight' => 1), + 'shadow' => array('color' => '#EEEEEE', 'offset' => '3pt,3pt'), + ) + ); + + // Oval + $section->addShape( + 'oval', + array( + 'frame' => array('width' => 100, 'height' => 70, 'left' => 1, 'top' => 1), + 'fill' => array('color' => '#33CC99'), + 'outline' => array('color' => '#333333', 'weight' => 2), + 'extrusion' => array('type' => 'perspective', 'color' => '#EEEEEE'), + ) + ); + + $doc = TestHelperDOCX::getDocument($phpWord); + + $elements = array('arc', 'curve', 'line', 'polyline', 'roundrect', 'oval'); + foreach ($elements as $element) { + $path = "/w:document/w:body/w:p/w:r/w:pict/v:{$element}"; + $this->assertTrue($doc->elementExists($path)); + } + } + + /** + * Test shape elements + */ + public function testChartElements() + { + $phpWord = new PhpWord(); + $section = $phpWord->addSection(); + $style = array('width' => 1000000, 'height' => 1000000); + + $chartTypes = array('pie', 'doughnut', 'bar', 'line', 'area', 'scatter', 'radar'); + $categories = array('A', 'B', 'C', 'D', 'E'); + $series1 = array(1, 3, 2, 5, 4); + foreach ($chartTypes as $chartType) { + $section->addChart($chartType, $categories, $series1, $style); + } + $section->addChart('pie', $categories, $series1, array('3d' => true)); + + $doc = TestHelperDOCX::getDocument($phpWord); + + $index = 0; + foreach ($chartTypes as $chartType) { + $index++; + $file = "word/charts/chart{$index}.xml"; + $path = "/c:chartSpace/c:chart/c:plotArea/c:{$chartType}Chart"; + $this->assertTrue($doc->elementExists($path, $file)); + } + } + + /** + * Test form fields + */ + public function testFormFieldElements() + { + $phpWord = new PhpWord(); + $section = $phpWord->addSection(); + + $section->addFormField('textinput')->setName('MyTextBox'); + $section->addFormField('checkbox')->setDefault(true)->setValue('Your name'); + $section->addFormField('dropdown')->setEntries(array('Choice 1', 'Choice 2', 'Choice 3')); + + $doc = TestHelperDOCX::getDocument($phpWord); + + $path = "/w:document/w:body/w:p/w:r/w:fldChar/w:ffData"; + $this->assertTrue($doc->elementExists($path . '/w:textInput')); + $this->assertTrue($doc->elementExists($path . '/w:checkBox')); + $this->assertTrue($doc->elementExists($path . '/w:ddList')); + } + + /** + * Test SDT elements + */ + public function testSDTElements() + { + $phpWord = new PhpWord(); + $section = $phpWord->addSection(); + + $section->addSDT('comboBox'); + $section->addSDT('dropDownList'); + $section->addSDT('date'); + + $doc = TestHelperDOCX::getDocument($phpWord); + + $path = "/w:document/w:body/w:p/w:sdt/w:sdtPr"; + $this->assertTrue($doc->elementExists($path . '/w:comboBox')); + $this->assertTrue($doc->elementExists($path . '/w:dropDownList')); + $this->assertTrue($doc->elementExists($path . '/w:date')); + } +} diff --git a/tests/PhpWord/Tests/Writer/Word2007/FooterTest.php b/tests/PhpWord/Tests/Writer/Word2007/FooterTest.php deleted file mode 100644 index b1bff02b..00000000 --- a/tests/PhpWord/Tests/Writer/Word2007/FooterTest.php +++ /dev/null @@ -1,48 +0,0 @@ -addText(''); - $container->addPreserveText(''); - $container->addTextBreak(); - $container->addTextRun(); - $container->addTable()->addRow()->addCell()->addText(''); - $container->addImage($imageSrc); - - $writer = new Word2007(); - $object = new Footer(); - $object->setParentWriter($writer); - $object->writeFooter($container); - $writer->setUseDiskCaching(true); - $xml = simplexml_load_string($object->writeFooter($container)); - - $this->assertInstanceOf('SimpleXMLElement', $xml); - } -} diff --git a/tests/PhpWord/Tests/Writer/Word2007/HeaderTest.php b/tests/PhpWord/Tests/Writer/Word2007/HeaderTest.php deleted file mode 100644 index b836b619..00000000 --- a/tests/PhpWord/Tests/Writer/Word2007/HeaderTest.php +++ /dev/null @@ -1,47 +0,0 @@ -addText('Test'); - $container->addPreserveText(''); - $container->addTextBreak(); - $container->addTextRun(); - $container->addTable()->addRow()->addCell()->addText(''); - $container->addImage($imageSrc); - $container->addWatermark($imageSrc); - - $writer = new Word2007(); - $object = new Header(); - $object->setParentWriter($writer); - $object->writeHeader($container); - $writer->setUseDiskCaching(true); - $xml = simplexml_load_string($object->writeHeader($container)); - - $this->assertInstanceOf('SimpleXMLElement', $xml); - } -} diff --git a/tests/PhpWord/Tests/Writer/Word2007/NotesTest.php b/tests/PhpWord/Tests/Writer/Word2007/NotesTest.php deleted file mode 100644 index f883314a..00000000 --- a/tests/PhpWord/Tests/Writer/Word2007/NotesTest.php +++ /dev/null @@ -1,48 +0,0 @@ -addParagraphStyle('pStyle', array('align' => 'left')); - $section = $phpWord->addSection(); - $section->addText('Text'); - $footnote1 = $section->addFootnote('pStyle'); - $footnote1->addText('Footnote'); - $footnote1->addTextBreak(); - $footnote1->addLink('http://google.com'); - $footnote2 = $section->addFootnote(array('align' => 'left')); - $footnote2->addText('Footnote'); - $doc = TestHelperDOCX::getDocument($phpWord); - - $this->assertTrue($doc->elementExists("/w:document/w:body/w:p/w:r/w:footnoteReference")); - } -} diff --git a/tests/PhpWord/Tests/Writer/Word2007/Part/AbstractPartTest.php b/tests/PhpWord/Tests/Writer/Word2007/Part/AbstractPartTest.php new file mode 100644 index 00000000..2ff80ab8 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/Word2007/Part/AbstractPartTest.php @@ -0,0 +1,59 @@ +getMockForAbstractClass( + 'PhpOffice\\PhpWord\\Writer\\Word2007\\Part\\AbstractPart' + ); + $object->setParentWriter(new Word2007()); + $this->assertEquals( + new Word2007(), + $object->getParentWriter() + ); + } + + /** + * covers ::getParentWriter + * @expectedException Exception + * @expectedExceptionMessage No parent WriterInterface assigned. + */ + public function testSetGetParentWriterNull() + { + $object = $this->getMockForAbstractClass( + 'PhpOffice\\PhpWord\\Writer\\Word2007\\Part\\AbstractPart' + ); + $object->getParentWriter(); + } +} diff --git a/tests/PhpWord/Tests/Writer/Word2007/BaseTest.php b/tests/PhpWord/Tests/Writer/Word2007/Part/DocumentTest.php similarity index 56% rename from tests/PhpWord/Tests/Writer/Word2007/BaseTest.php rename to tests/PhpWord/Tests/Writer/Word2007/Part/DocumentTest.php index d9d1b3c5..ef36e0dd 100644 --- a/tests/PhpWord/Tests/Writer/Word2007/BaseTest.php +++ b/tests/PhpWord/Tests/Writer/Word2007/Part/DocumentTest.php @@ -1,23 +1,32 @@ addSection(); + $section->addHeader(); + $section->addHeader('first'); + $style = $section->getStyle(); + $style->setLandscape(); + $style->setPageNumberingStart(2); + $style->setBorderSize(240); + $style->setBreakType('nextPage'); + + $doc = TestHelperDOCX::getDocument($phpWord); + $element = $doc->getElement('/w:document/w:body/w:sectPr/w:pgNumType'); + + $this->assertEquals(2, $element->getAttribute('w:start')); + } + + /** + * Write elements + */ + public function testElements() + { + $objectSrc = __DIR__ . "/../../../_files/documents/sheet.xls"; + + $phpWord = new PhpWord(); + $phpWord->addTitleStyle(1, array('color' => '333333', 'bold'=>true)); + $phpWord->addTitleStyle(2, array('color'=>'666666')); + $section = $phpWord->addSection(); + $section->addTOC(); + $section->addPageBreak(); + $section->addText('After page break.'); + $section->addTitle('Title 1', 1); + $section->addListItem('List Item 1', 0); + $section->addListItem('List Item 2', 0); + $section->addListItem('List Item 3', 0); + + $section = $phpWord->addSection(); + $section->addTitle('Title 2', 2); + $section->addObject($objectSrc); + $section->addTextBox(array()); + $section->addTextBox(array('wrappingStyle' => 'square', 'positioning' => 'relative', + 'posHorizontalRel' => 'margin', 'posVerticalRel' => 'margin', + 'innerMargin' => 10, 'borderSize' => 1, 'borderColor' => '#FF0')); + $section->addTextBox(array('wrappingStyle' => 'tight', 'positioning' => 'absolute', 'align' => 'center')); + $section->addListItemRun()->addText('List item run 1'); + $section->addField('DATE', array('dateformat'=>'dddd d MMMM yyyy H:mm:ss'), array('PreserveFormat', 'LunarCalendar')); + $section->addField('DATE', array('dateformat'=>'dddd d MMMM yyyy H:mm:ss'), array('PreserveFormat', 'SakaEraCalendar')); + $section->addField('DATE', array('dateformat'=>'dddd d MMMM yyyy H:mm:ss'), array('PreserveFormat', 'LastUsedFormat')); + $section->addField('PAGE', array('format'=>'ArabicDash')); + $section->addLine( + array( + 'width' => 10, + 'height' => 10, + 'positioning' => 'absolute', + 'beginArrow' => 'block', + 'endArrow' => 'open', + 'dash' => 'rounddot', + 'weight' => 10 + ) + ); + + $doc = TestHelperDOCX::getDocument($phpWord); + + // TOC + $element = $doc->getElement('/w:document/w:body/w:p[1]/w:pPr/w:tabs/w:tab'); + $this->assertEquals('right', $element->getAttribute('w:val')); + $this->assertEquals('dot', $element->getAttribute('w:leader')); + $this->assertEquals(9062, $element->getAttribute('w:pos')); + + // Page break + $element = $doc->getElement('/w:document/w:body/w:p[4]/w:r/w:br'); + $this->assertEquals('page', $element->getAttribute('w:type')); + + // Title + $element = $doc->getElement('/w:document/w:body/w:p[6]/w:pPr/w:pStyle'); + $this->assertEquals('Heading1', $element->getAttribute('w:val')); + + // List item + $element = $doc->getElement('/w:document/w:body/w:p[7]/w:pPr/w:numPr/w:numId'); + $this->assertEquals(3, $element->getAttribute('w:val')); + + // Object + $element = $doc->getElement('/w:document/w:body/w:p[12]/w:r/w:object/o:OLEObject'); + $this->assertEquals('Embed', $element->getAttribute('Type')); + } + + /** + * Write element with some styles + */ + public function testElementStyles() + { + $objectSrc = __DIR__ . "/../../../_files/documents/sheet.xls"; + + $tabs = array(new \PhpOffice\PhpWord\Style\Tab('right', 9090)); + $phpWord = new PhpWord(); + $phpWord->addParagraphStyle('pStyle', array( + 'align' => 'center', + 'tabs' => $tabs, + 'shading' => array('fill' => 'FFFF99'), + 'borderSize' => 4, + )); // Style #1 + $phpWord->addFontStyle('fStyle', array('size' => '20', 'bold' => true, 'allCaps' => true, + 'scale' => 200, 'spacing' => 240, 'kerning' => 10)); // Style #2 + $phpWord->addTitleStyle(1, array('color' => '333333', 'doubleStrikethrough' => true)); // Style #3 + $phpWord->addTableStyle('tStyle', array('borderSize' => 1)); + $fontStyle = new Font('text', array('align' => 'center')); + + $section = $phpWord->addSection(); + $section->addListItem('List Item', 0, null, null, 'pStyle'); // Style #5 + $section->addObject($objectSrc, array('align' => 'center')); + $section->addTOC($fontStyle); + $section->addTitle('Title 1', 1); + $section->addTOC('fStyle'); + $table = $section->addTable('tStyle'); + $table->setWidth(100); + $doc = TestHelperDOCX::getDocument($phpWord); + + // List item + $element = $doc->getElement('/w:document/w:body/w:p[1]/w:pPr/w:numPr/w:numId'); + $this->assertEquals(5, $element->getAttribute('w:val')); + + // Object + $element = $doc->getElement('/w:document/w:body/w:p[2]/w:r/w:object/o:OLEObject'); + $this->assertEquals('Embed', $element->getAttribute('Type')); + + // TOC + $element = $doc->getElement('/w:document/w:body/w:p[3]/w:pPr/w:tabs/w:tab'); + $this->assertEquals('right', $element->getAttribute('w:val')); + $this->assertEquals('dot', $element->getAttribute('w:leader')); + $this->assertEquals(9062, $element->getAttribute('w:pos')); + } + + /** + * Test write text element */ public function testWriteText() { @@ -49,13 +194,13 @@ class BaseTest extends \PHPUnit_Framework_TestCase } /** - * covers ::_writeTextRun + * Test write textrun element */ public function testWriteTextRun() { $pStyle = 'pStyle'; $aStyle = array('align' => 'justify', 'spaceBefore' => 120, 'spaceAfter' => 120); - $imageSrc = __DIR__ . "/../../_files/images/earth.jpg"; + $imageSrc = __DIR__ . "/../../../_files/images/earth.jpg"; $phpWord = new PhpWord(); $phpWord->addParagraphStyle($pStyle, $aStyle); @@ -65,7 +210,7 @@ class BaseTest extends \PHPUnit_Framework_TestCase $textrun->addTextBreak(); $textrun = $section->addTextRun($aStyle); $textrun->addLink('http://test.com'); - $textrun->addImage($imageSrc, array('align' => 'top')); + $textrun->addImage($imageSrc, array('align' => 'center')); $textrun->addFootnote(); $doc = TestHelperDOCX::getDocument($phpWord); @@ -74,7 +219,7 @@ class BaseTest extends \PHPUnit_Framework_TestCase } /** - * covers ::_writeLink + * Test write link element */ public function testWriteLink() { @@ -97,7 +242,7 @@ class BaseTest extends \PHPUnit_Framework_TestCase } /** - * covers ::_writePreserveText + * Test write preserve text element */ public function testWritePreserveText() { @@ -121,7 +266,7 @@ class BaseTest extends \PHPUnit_Framework_TestCase } /** - * covers ::_writeTextBreak + * Test write text break */ public function testWriteTextBreak() { @@ -146,30 +291,96 @@ class BaseTest extends \PHPUnit_Framework_TestCase } /** - * covers ::_writeParagraphStyle + * covers ::_writeImage */ - public function testWriteParagraphStyleAlign() + public function testWriteImage() { $phpWord = new PhpWord(); + $styles = array('align' => 'left', 'width' => 40, 'height' => 40, 'marginTop' => -1, 'marginLeft' => -1); + $wraps = array('inline', 'behind', 'infront', 'square', 'tight'); $section = $phpWord->addSection(); + foreach ($wraps as $wrap) { + $styles['wrappingStyle'] = $wrap; + $section->addImage(__DIR__ . "/../../../_files/images/earth.jpg", $styles); + } - $section->addText('This is my text', null, array('align' => 'right')); + $archiveFile = realpath(__DIR__ . '/../../../_files/documents/reader.docx'); + $imageFile = 'word/media/image1.jpeg'; + $source = 'zip://' . $archiveFile . '#' . $imageFile; + $section->addImage($source); $doc = TestHelperDOCX::getDocument($phpWord); - $element = $doc->getElement('/w:document/w:body/w:p/w:pPr/w:jc'); - $this->assertEquals('right', $element->getAttribute('w:val')); + // behind + $element = $doc->getElement('/w:document/w:body/w:p[2]/w:r/w:pict/v:shape'); + $style = $element->getAttribute('style'); + $this->assertRegExp('/z\-index:\-[0-9]*/', $style); + + // square + $element = $doc->getElement('/w:document/w:body/w:p[4]/w:r/w:pict/v:shape/w10:wrap'); + $this->assertEquals('square', $element->getAttribute('type')); + } + + /** + * covers ::_writeWatermark + */ + public function testWriteWatermark() + { + $imageSrc = __DIR__ . "/../../../_files/images/earth.jpg"; + + $phpWord = new PhpWord(); + $section = $phpWord->addSection(); + $header = $section->addHeader(); + $header->addWatermark($imageSrc); + $doc = TestHelperDOCX::getDocument($phpWord); + + $element = $doc->getElement("/w:document/w:body/w:sectPr/w:headerReference"); + $this->assertStringStartsWith("rId", $element->getAttribute('r:id')); + } + + /** + * covers ::_writeTitle + */ + public function testWriteTitle() + { + $phpWord = new PhpWord(); + $phpWord->addTitleStyle(1, array('bold' => true), array('spaceAfter' => 240)); + $phpWord->addSection()->addTitle('Test', 1); + $doc = TestHelperDOCX::getDocument($phpWord); + + $element = "/w:document/w:body/w:p/w:pPr/w:pStyle"; + $this->assertEquals('Heading1', $doc->getElementAttribute($element, 'w:val')); + } + + /** + * covers ::_writeCheckbox + */ + public function testWriteCheckbox() + { + $rStyle = 'rStyle'; + $pStyle = 'pStyle'; + + $phpWord = new PhpWord(); + // $phpWord->addFontStyle($rStyle, array('bold' => true)); + // $phpWord->addParagraphStyle($pStyle, array('hanging' => 120, 'indent' => 120)); + $section = $phpWord->addSection(); + $section->addCheckBox('Check1', 'Test', $rStyle, $pStyle); + $doc = TestHelperDOCX::getDocument($phpWord); + + $element = '/w:document/w:body/w:p/w:r/w:fldChar/w:ffData/w:name'; + $this->assertEquals('Check1', $doc->getElementAttribute($element, 'w:val')); } /** * covers ::_writeParagraphStyle */ - public function testWriteParagraphStylePagination() + public function testWriteParagraphStyle() { // Create the doc $phpWord = new PhpWord(); $section = $phpWord->addSection(); $attributes = array( + 'align' => 'right', 'widowControl' => false, 'keepNext' => true, 'keepLines' => true, @@ -181,13 +392,16 @@ class BaseTest extends \PHPUnit_Framework_TestCase $doc = TestHelperDOCX::getDocument($phpWord); // Test the attributes - $i = 0; + $attributeCount = 0; foreach ($attributes as $key => $value) { - $i++; - $path = "/w:document/w:body/w:p[{$i}]/w:pPr/w:{$key}"; + $attributeCount++; + $nodeName = ($key == 'align') ? 'jc' : $key; + $path = "/w:document/w:body/w:p[{$attributeCount}]/w:pPr/w:{$nodeName}"; + if ($key != 'align') { + $value = $value ? 1 : 0; + } $element = $doc->getElement($path); - $expected = $value ? 1 : 0; - $this->assertEquals($expected, $element->getAttribute('w:val')); + $this->assertEquals($value, $element->getAttribute('w:val')); } } @@ -208,6 +422,7 @@ class BaseTest extends \PHPUnit_Framework_TestCase $styles['fgColor'] = 'yellow'; $styles['bgColor'] = 'FFFF00'; $styles['hint'] = 'eastAsia'; + $styles['smallCaps'] = true; $section = $phpWord->addSection(); $section->addText('Test', $styles); @@ -223,6 +438,7 @@ class BaseTest extends \PHPUnit_Framework_TestCase $this->assertEquals('superscript', $doc->getElementAttribute("{$parent}/w:vertAlign", 'w:val')); $this->assertEquals($styles['color'], $doc->getElementAttribute("{$parent}/w:color", 'w:val')); $this->assertEquals($styles['fgColor'], $doc->getElementAttribute("{$parent}/w:highlight", 'w:val')); + $this->assertTrue($doc->elementExists("{$parent}/w:smallCaps")); } /** @@ -231,11 +447,10 @@ class BaseTest extends \PHPUnit_Framework_TestCase public function testWriteTableStyle() { $phpWord = new PhpWord(); - $tWidth = 120; $rHeight = 120; $cWidth = 120; - $imageSrc = __DIR__ . "/../../_files/images/earth.jpg"; - $objectSrc = __DIR__ . "/../../_files/documents/sheet.xls"; + $imageSrc = __DIR__ . "/../../../_files/images/earth.jpg"; + $objectSrc = __DIR__ . "/../../../_files/documents/sheet.xls"; $tStyles["width"] = 50; $tStyles["cellMarginTop"] = 120; @@ -311,6 +526,10 @@ class BaseTest extends \PHPUnit_Framework_TestCase $table->addCell(40); $table->addCell(40); + $table->addRow(); + $cell = $table->addCell(200, array('borderRightColor' => 'FF0000')); + $cell->getStyle()->setGridSpan(5); + $doc = TestHelperDOCX::getDocument($phpWord); $element = $doc->getElement('/w:document/w:body/w:tbl/w:tr/w:tc/w:tcPr/w:gridSpan'); @@ -318,79 +537,18 @@ class BaseTest extends \PHPUnit_Framework_TestCase } /** - * covers ::_writeImage + * Test write gutter and line numbering */ - public function testWriteImagePosition() + public function testWriteGutterAndLineNumbering() { - $phpWord = new PhpWord(); - $section = $phpWord->addSection(); - $section->addImage( - __DIR__ . "/../../_files/images/earth.jpg", - array( - 'marginTop' => -1, - 'marginLeft' => -1, - 'wrappingStyle' => 'behind' - ) - ); - - $doc = TestHelperDOCX::getDocument($phpWord); - $element = $doc->getElement('/w:document/w:body/w:p/w:r/w:pict/v:shape'); - - $style = $element->getAttribute('style'); - - $this->assertRegExp('/z\-index:\-[0-9]*/', $style); - $this->assertRegExp('/position:absolute;/', $style); - } - - /** - * covers ::_writeWatermark - */ - public function testWriteWatermark() - { - $imageSrc = __DIR__ . "/../../_files/images/earth.jpg"; + $pageMarginPath = '/w:document/w:body/w:sectPr/w:pgMar'; + $lineNumberingPath = '/w:document/w:body/w:sectPr/w:lnNumType'; $phpWord = new PhpWord(); - $section = $phpWord->addSection(); - $header = $section->addHeader(); - $header->addWatermark($imageSrc); + $phpWord->addSection(array('gutter' => 240, 'lineNumbering' => array())); $doc = TestHelperDOCX::getDocument($phpWord); - $element = $doc->getElement("/w:document/w:body/w:sectPr/w:headerReference"); - $this->assertStringStartsWith("rId", $element->getAttribute('r:id')); - } - - /** - * covers ::_writeTitle - */ - public function testWriteTitle() - { - $phpWord = new PhpWord(); - $phpWord->addTitleStyle(1, array('bold' => true), array('spaceAfter' => 240)); - $phpWord->addSection()->addTitle('Test', 1); - $doc = TestHelperDOCX::getDocument($phpWord); - - $element = "/w:document/w:body/w:p/w:pPr/w:pStyle"; - $this->assertEquals('Heading1', $doc->getElementAttribute($element, 'w:val')); - $element = "/w:document/w:body/w:p/w:r/w:fldChar"; - $this->assertEquals('end', $doc->getElementAttribute($element, 'w:fldCharType')); - } - - /** - * covers ::_writeCheckbox - */ - public function testWriteCheckbox() - { - $rStyle = 'rStyle'; - $pStyle = 'pStyle'; - - $phpWord = new PhpWord(); - $phpWord->addFontStyle($rStyle, array('bold' => true)); - $phpWord->addParagraphStyle($pStyle, array('hanging' => 120, 'indent' => 120)); - $section = $phpWord->addSection(); - $section->addCheckbox('Check1', 'Test', $rStyle, $pStyle); - $doc = TestHelperDOCX::getDocument($phpWord); - - $element = '/w:document/w:body/w:p/w:r/w:fldChar/w:ffData/w:name'; - $this->assertEquals('Check1', $doc->getElementAttribute($element, 'w:val')); + $this->assertEquals(240, $doc->getElement($pageMarginPath)->getAttribute('w:gutter')); + $this->assertTrue($doc->elementExists($lineNumberingPath)); } } diff --git a/tests/PhpWord/Tests/Writer/Word2007/Part/FooterTest.php b/tests/PhpWord/Tests/Writer/Word2007/Part/FooterTest.php new file mode 100644 index 00000000..5c9d2d30 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/Word2007/Part/FooterTest.php @@ -0,0 +1,53 @@ +addText(''); + $container->addPreserveText(''); + $container->addTextBreak(); + $container->addTextRun(); + $container->addTable()->addRow()->addCell()->addText(''); + $container->addImage($imageSrc); + + $writer = new Word2007(); + $writer->setUseDiskCaching(true); + $object = new Footer(); + $object->setParentWriter($writer); + $object->setElement($container); + $xml = simplexml_load_string($object->write()); + + $this->assertInstanceOf('SimpleXMLElement', $xml); + } +} diff --git a/tests/PhpWord/Tests/Writer/Word2007/Part/FootnotesTest.php b/tests/PhpWord/Tests/Writer/Word2007/Part/FootnotesTest.php new file mode 100644 index 00000000..d7a3d667 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/Word2007/Part/FootnotesTest.php @@ -0,0 +1,57 @@ +addParagraphStyle('pStyle', array('align' => 'left')); + $section = $phpWord->addSection(); + $section->addText('Text'); + $footnote1 = $section->addFootnote('pStyle'); + $footnote1->addText('Footnote'); + $footnote1->addTextBreak(); + $footnote1->addLink('http://google.com'); + $footnote2 = $section->addEndnote(array('align' => 'left')); + $footnote2->addText('Endnote'); + $doc = TestHelperDOCX::getDocument($phpWord); + + $this->assertTrue($doc->elementExists("/w:document/w:body/w:p/w:r/w:footnoteReference")); + $this->assertTrue($doc->elementExists("/w:document/w:body/w:p/w:r/w:endnoteReference")); + } +} diff --git a/tests/PhpWord/Tests/Writer/Word2007/Part/HeaderTest.php b/tests/PhpWord/Tests/Writer/Word2007/Part/HeaderTest.php new file mode 100644 index 00000000..e8c31ecf --- /dev/null +++ b/tests/PhpWord/Tests/Writer/Word2007/Part/HeaderTest.php @@ -0,0 +1,54 @@ +addText('Test'); + $container->addPreserveText(''); + $container->addTextBreak(); + $container->addTextRun(); + $container->addTable()->addRow()->addCell()->addText(''); + $container->addImage($imageSrc); + $container->addWatermark($imageSrc); + + $writer = new Word2007(); + $writer->setUseDiskCaching(true); + $object = new Header(); + $object->setParentWriter($writer); + $object->setElement($container); + $xml = simplexml_load_string($object->write()); + + $this->assertInstanceOf('SimpleXMLElement', $xml); + } +} diff --git a/tests/PhpWord/Tests/Writer/Word2007/Part/NumberingTest.php b/tests/PhpWord/Tests/Writer/Word2007/Part/NumberingTest.php new file mode 100644 index 00000000..ebc3aa2e --- /dev/null +++ b/tests/PhpWord/Tests/Writer/Word2007/Part/NumberingTest.php @@ -0,0 +1,73 @@ +addNumberingStyle( + 'numStyle', + array( + 'type' => 'multilevel', + 'levels' => array( + array( + 'start' => 1, + 'format' => 'decimal', + 'restart' => 1, + 'suffix' => 'space', + 'text' => '%1.', + 'align' => 'left', + 'left' => 360, + 'hanging' => 360, + 'tabPos' => 360, + 'font' => 'Arial', + 'hint' => 'default', + ), + ) + ) + ); + + $doc = TestHelperDOCX::getDocument($phpWord, 'Word2007'); + + $this->assertTrue($doc->elementExists('/w:numbering/w:abstractNum', $xmlFile)); + } +} diff --git a/tests/PhpWord/Tests/Writer/Word2007/Part/SettingsTest.php b/tests/PhpWord/Tests/Writer/Word2007/Part/SettingsTest.php new file mode 100644 index 00000000..7d4d1849 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/Word2007/Part/SettingsTest.php @@ -0,0 +1,68 @@ +getProtection()->setEditing('forms'); + + $doc = TestHelperDOCX::getDocument($phpWord); + + $file = 'word/settings.xml'; + + $path = '/w:settings/w:documentProtection'; + $this->assertTrue($doc->elementExists($path, $file)); + } + + /** + * Test compatibility + */ + public function testCompatibility() + { + $phpWord = new PhpWord(); + $phpWord->getCompatibility()->setOoxmlVersion(15); + + $doc = TestHelperDOCX::getDocument($phpWord); + + $file = 'word/settings.xml'; + + $path = '/w:settings/w:compat/w:compatSetting'; + $this->assertTrue($doc->elementExists($path, $file)); + } +} diff --git a/tests/PhpWord/Tests/Writer/Word2007/StylesTest.php b/tests/PhpWord/Tests/Writer/Word2007/Part/StylesTest.php similarity index 61% rename from tests/PhpWord/Tests/Writer/Word2007/StylesTest.php rename to tests/PhpWord/Tests/Writer/Word2007/Part/StylesTest.php index 70ebe7cf..103caa81 100644 --- a/tests/PhpWord/Tests/Writer/Word2007/StylesTest.php +++ b/tests/PhpWord/Tests/Writer/Word2007/Part/StylesTest.php @@ -1,20 +1,29 @@ 20); $tStyle = array( 'bgColor' => 'FF0000', - 'cellMarginTop' => 120, - 'cellMarginBottom' => 120, - 'cellMarginLeft' => 120, - 'cellMarginRight' => 120, - 'borderTopSize' => 120, - 'borderBottomSize' => 120, - 'borderLeftSize' => 120, - 'borderRightSize' => 120, - 'borderInsideHSize' => 120, - 'borderInsideVSize' => 120, + 'cellMargin' => 120, + 'borderSize' => 120, + ); + $firstRowStyle = array( + 'bgColor' => '0000FF', + 'borderSize' => 120, + 'borderColor' => '00FF00', ); $phpWord->setDefaultParagraphStyle($pStyle); $phpWord->addParagraphStyle('Base Style', $pBase); $phpWord->addParagraphStyle('New Style', $pNew); $phpWord->addFontStyle('New Style', $rStyle, $pStyle); - $phpWord->addTableStyle('Table Style', $tStyle, $tStyle); + $phpWord->addTableStyle('Table Style', $tStyle, $firstRowStyle); $phpWord->addTitleStyle(1, $rStyle, $pStyle); $doc = TestHelperDOCX::getDocument($phpWord); diff --git a/tests/PhpWord/Tests/Writer/Word2007/PartTest.php b/tests/PhpWord/Tests/Writer/Word2007/PartTest.php new file mode 100644 index 00000000..c3d29331 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/Word2007/PartTest.php @@ -0,0 +1,41 @@ +setMedia(array(array('type' => '', 'target' => ''))); + $object->write(); + } +} diff --git a/tests/PhpWord/Tests/Writer/Word2007/Style/FontTest.php b/tests/PhpWord/Tests/Writer/Word2007/Style/FontTest.php new file mode 100644 index 00000000..af11c054 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/Word2007/Style/FontTest.php @@ -0,0 +1,54 @@ +addSection(); + $textrun = $section->addTextRun(); + $textrun->addText('سلام این یک پاراگراف راست به چپ است', array('rtl' => true)); + $doc = TestHelperDOCX::getDocument($phpWord, 'Word2007'); + + $file = 'word/document.xml'; + $path = '/w:document/w:body/w:p/w:r/w:rPr/w:rtl'; + $this->assertTrue($doc->elementExists($path, $file)); + } +} diff --git a/tests/PhpWord/Tests/Writer/Word2007/StyleTest.php b/tests/PhpWord/Tests/Writer/Word2007/StyleTest.php new file mode 100644 index 00000000..8dd229c3 --- /dev/null +++ b/tests/PhpWord/Tests/Writer/Word2007/StyleTest.php @@ -0,0 +1,65 @@ +write(); + + $this->assertEquals('', $xmlWriter->getData()); + } + } + + /** + * Test method exceptions + */ + public function testMethodExceptions() + { + $styles = array( + 'Frame' => 'writeAlignment', + 'Line' => 'writeStroke', + 'TextBox' => 'writeBorder', + ); + foreach ($styles as $style => $method) { + $objectClass = 'PhpOffice\\PhpWord\\Writer\\Word2007\\Style\\' . $style; + $xmlWriter = new XMLWriter(); + $object = new $objectClass($xmlWriter); + $object->$method(); + + $this->assertEquals('', $xmlWriter->getData()); + } + } +} diff --git a/tests/PhpWord/Tests/Writer/Word2007Test.php b/tests/PhpWord/Tests/Writer/Word2007Test.php index 5e990615..db6e5cad 100644 --- a/tests/PhpWord/Tests/Writer/Word2007Test.php +++ b/tests/PhpWord/Tests/Writer/Word2007Test.php @@ -1,16 +1,24 @@ 'ContentTypes', 'Rels' => 'Rels', - 'DocProps' => 'DocProps', + 'DocPropsApp' => 'DocPropsApp', 'Document' => 'Document', 'Styles' => 'Styles', + 'Numbering' => 'Numbering', + 'Settings' => 'Settings', + 'WebSettings' => 'WebSettings', 'Header' => 'Header', 'Footer' => 'Footer', - 'Footnotes' => 'Notes', - 'Endnotes' => 'Notes', + 'Footnotes' => 'Footnotes', + 'Endnotes' => 'Footnotes', ); foreach ($writerParts as $part => $type) { $this->assertInstanceOf( - "PhpOffice\\PhpWord\\Writer\\Word2007\\{$type}", + "PhpOffice\\PhpWord\\Writer\\Word2007\\Part\\{$type}", $object->getWriterPart($part) ); $this->assertInstanceOf( @@ -111,18 +122,6 @@ class Word2007Test extends \PHPUnit_Framework_TestCase unlink($file); } - /** - * Save with no PhpWord object assigned - * - * @expectedException \PhpOffice\PhpWord\Exception\Exception - * @expectedExceptionMessage PhpWord object unassigned. - */ - public function testSaveException() - { - $writer = new Word2007(); - $writer->save(); - } - /** * Check content types */ @@ -168,13 +167,13 @@ class Word2007Test extends \PHPUnit_Framework_TestCase public function testSetGetUseDiskCaching() { $phpWord = new PhpWord(); - $section = $phpWord->addSection(); + $phpWord->addSection(); $object = new Word2007($phpWord); $object->setUseDiskCaching(true, PHPWORD_TESTS_BASE_DIR); $writer = new Word2007($phpWord); $writer->save('php://output'); - $this->assertTrue($object->getUseDiskCaching()); + $this->assertTrue($object->isUseDiskCaching()); } /** diff --git a/tests/PhpWord/Tests/_files/documents/reader.docx b/tests/PhpWord/Tests/_files/documents/reader.docx index 5f37ef4b..d09091b1 100644 Binary files a/tests/PhpWord/Tests/_files/documents/reader.docx and b/tests/PhpWord/Tests/_files/documents/reader.docx differ diff --git a/tests/PhpWord/Tests/_files/documents/reader.html b/tests/PhpWord/Tests/_files/documents/reader.html new file mode 100644 index 00000000..5593298b --- /dev/null +++ b/tests/PhpWord/Tests/_files/documents/reader.html @@ -0,0 +1,15 @@ + + + +PHPWord + + +

Adding element via HTML

+

Some well formed HTML snippet needs to be used

+

With for example some1 inline formatting1

+

Unordered (bulleted) list:

+
  • Item 1
  • Item 2
    • Item 2.1
    • Item 2.1
+

Ordered (numbered) list:

+
  1. Item 1
  2. Item 2
+ + diff --git a/tests/PhpWord/Tests/_files/documents/reader.odt b/tests/PhpWord/Tests/_files/documents/reader.odt new file mode 100644 index 00000000..d37c4e66 Binary files /dev/null and b/tests/PhpWord/Tests/_files/documents/reader.odt differ diff --git a/tests/PhpWord/Tests/_files/documents/reader.rtf b/tests/PhpWord/Tests/_files/documents/reader.rtf new file mode 100644 index 00000000..400f43a5 --- /dev/null +++ b/tests/PhpWord/Tests/_files/documents/reader.rtf @@ -0,0 +1,21 @@ +{\rtf1 +\ansi\ansicpg1252 +\deff0 +{\fonttbl{\f0\fnil\fcharset0 Arial;}{\f1\fnil\fcharset0 Times New Roman;}} +{\colortbl;\red255\green0\blue0;\red14\green0\blue0} +{\*\generator PhpWord;} + +{\info{\title }{\subject }{\category }{\keywords }{\comment }{\author }{\operator }{\creatim \yr2014\mo05\dy27\hr23\min36\sec45}{\revtim \yr2014\mo05\dy27\hr23\min36\sec45}{\company }{\manager }} +\deftab720\viewkind1\uc1\pard\nowidctlpar\lang1036\kerning1\fs20 +{Welcome to PhpWord}\par +\pard\nowidctlpar{\cf0\f0 Hello World!}\par +\par +\par +\pard\nowidctlpar{\cf0\f0\fs32\b\i I am styled by a definition.}\par +\pard\nowidctlpar{\cf0\f0 I am styled by a paragraph style definition.}\par +\pard\nowidctlpar\qc\sa100{\cf0\f0\fs32\b\i I am styled by both font and paragraph style.}\par +\pard\nowidctlpar{\cf1\f1\fs40\b\i\ul\strike\super I am inline styled.}\par +\par +{\field {\*\fldinst {HYPERLINK "http://www.google.com"}}{\fldrslt {Google}}}\par +\par +} \ No newline at end of file diff --git a/tests/PhpWord/Tests/_files/images/angela_merkel.tif b/tests/PhpWord/Tests/_files/images/angela_merkel.tif index 236dedd1..50629970 100644 Binary files a/tests/PhpWord/Tests/_files/images/angela_merkel.tif and b/tests/PhpWord/Tests/_files/images/angela_merkel.tif differ diff --git a/tests/PhpWord/Tests/_files/images/duke_nukem.bmp b/tests/PhpWord/Tests/_files/images/duke_nukem.bmp index b78975d0..123b96f7 100644 Binary files a/tests/PhpWord/Tests/_files/images/duke_nukem.bmp and b/tests/PhpWord/Tests/_files/images/duke_nukem.bmp differ diff --git a/tests/PhpWord/Tests/_files/images/firefox.png b/tests/PhpWord/Tests/_files/images/firefox.png index 588afbfa..fb72cedd 100644 Binary files a/tests/PhpWord/Tests/_files/images/firefox.png and b/tests/PhpWord/Tests/_files/images/firefox.png differ diff --git a/tests/PhpWord/Tests/_includes/TestHelperDOCX.php b/tests/PhpWord/Tests/_includes/TestHelperDOCX.php index bea0d037..2a0043d5 100644 --- a/tests/PhpWord/Tests/_includes/TestHelperDOCX.php +++ b/tests/PhpWord/Tests/_includes/TestHelperDOCX.php @@ -1,16 +1,26 @@ open(self::$file); if ($res === true) { - $zip->extractTo(sys_get_temp_dir() . '/PhpWord_Unit_Test/'); + $zip->extractTo(Settings::getTempDir() . '/PhpWord_Unit_Test/'); $zip->close(); } - return new XmlDocument(sys_get_temp_dir() . '/PhpWord_Unit_Test/'); + return new XmlDocument(Settings::getTempDir() . '/PhpWord_Unit_Test/'); } /** @@ -59,8 +76,8 @@ class TestHelperDOCX if (file_exists(self::$file)) { unlink(self::$file); } - if (is_dir(sys_get_temp_dir() . '/PhpWord_Unit_Test/')) { - self::deleteDir(sys_get_temp_dir() . '/PhpWord_Unit_Test/'); + if (is_dir(Settings::getTempDir() . '/PhpWord_Unit_Test/')) { + self::deleteDir(Settings::getTempDir() . '/PhpWord_Unit_Test/'); } } diff --git a/tests/PhpWord/Tests/_includes/XmlDocument.php b/tests/PhpWord/Tests/_includes/XmlDocument.php index a08227ba..2e161bb1 100644 --- a/tests/PhpWord/Tests/_includes/XmlDocument.php +++ b/tests/PhpWord/Tests/_includes/XmlDocument.php @@ -1,10 +1,18 @@