recreate project

This commit is contained in:
root
2026-02-10 22:11:06 -05:00
commit 663c0cdbda
10149 changed files with 1379710 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
user=PHPOffice
project=PHPWord
since-tag=0.18.1
future-release=0.18.2
issues=false
pulls=true
+227
View File
@@ -0,0 +1,227 @@
<?php
$finder = PhpCsFixer\Finder::create()
->notName('pclzip.lib.php')
->notName('OLERead.php')
->in('samples')
->in('src')
->in('tests');
$config = new PhpCsFixer\Config();
$config
->setRiskyAllowed(true)
->setFinder($finder)
->setCacheFile(sys_get_temp_dir() . '/php-cs-fixer' . preg_replace('~\W~', '-', __DIR__))
->setRules([
'align_multiline_comment' => true,
'array_indentation' => true,
'array_syntax' => ['syntax' => 'short'],
'backtick_to_shell_exec' => true,
'binary_operator_spaces' => true,
'blank_line_after_namespace' => true,
'blank_line_after_opening_tag' => true,
'blank_line_before_statement' => true,
'braces' => true,
'cast_spaces' => true,
'class_attributes_separation' => ['elements' => ['method' => 'one', 'property' => 'one']], // const are often grouped with other related const
'class_definition' => false,
'class_keyword_remove' => false, // ::class keyword gives us better support in IDE
'combine_consecutive_issets' => true,
'combine_consecutive_unsets' => true,
'combine_nested_dirname' => true,
'comment_to_phpdoc' => false, // interferes with annotations
'compact_nullable_typehint' => true,
'concat_space' => ['spacing' => 'one'],
'constant_case' => true,
'date_time_immutable' => false, // Break our unit tests
'declare_equal_normalize' => true,
'declare_strict_types' => false, // Too early to adopt strict types
'dir_constant' => true,
'doctrine_annotation_array_assignment' => true,
'doctrine_annotation_braces' => true,
'doctrine_annotation_indentation' => true,
'doctrine_annotation_spaces' => true,
'elseif' => true,
'encoding' => true,
'ereg_to_preg' => true,
'escape_implicit_backslashes' => true,
'explicit_indirect_variable' => false, // I feel it makes the code actually harder to read
'explicit_string_variable' => false, // I feel it makes the code actually harder to read
'final_class' => false, // We need non-final classes
'final_internal_class' => true,
'final_public_method_for_abstract_class' => false, // We need non-final methods
'fopen_flag_order' => true,
'fopen_flags' => true,
'full_opening_tag' => true,
'fully_qualified_strict_types' => true,
'function_declaration' => true,
'function_to_constant' => true,
'function_typehint_space' => true,
'general_phpdoc_annotation_remove' => ['annotations' => ['access', 'category', 'copyright', 'throws']],
'global_namespace_import' => true,
'header_comment' => false, // We don't use common header in all our files
'heredoc_indentation' => false, // Requires PHP >= 7.3
'heredoc_to_nowdoc' => false, // Not sure about this one
'implode_call' => true,
'include' => true,
'increment_style' => true,
'indentation_type' => true,
'is_null' => true,
'line_ending' => true,
'linebreak_after_opening_tag' => true,
'list_syntax' => ['syntax' => 'short'],
'logical_operators' => true,
'lowercase_cast' => true,
'lowercase_keywords' => true,
'lowercase_static_reference' => true,
'magic_constant_casing' => true,
'magic_method_casing' => true,
'mb_str_functions' => false, // No, too dangerous to change that
'method_argument_space' => true,
'method_chaining_indentation' => true,
'modernize_types_casting' => true,
'multiline_comment_opening_closing' => true,
'multiline_whitespace_before_semicolons' => true,
'native_constant_invocation' => false, // Micro optimization that look messy
'native_function_casing' => true,
'native_function_invocation' => false, // I suppose this would be best, but I am still unconvinced about the visual aspect of it
'native_function_type_declaration_casing' => true,
'new_with_braces' => true,
'no_alias_functions' => true,
'no_alternative_syntax' => true,
'no_binary_string' => true,
'no_blank_lines_after_class_opening' => true,
'no_blank_lines_after_phpdoc' => true,
'no_blank_lines_before_namespace' => false, // we want 1 blank line before namespace
'no_break_comment' => true,
'no_closing_tag' => true,
'no_empty_comment' => true,
'no_empty_phpdoc' => true,
'no_empty_statement' => true,
'no_extra_blank_lines' => true,
'no_homoglyph_names' => true,
'no_leading_import_slash' => true,
'no_leading_namespace_whitespace' => true,
'no_mixed_echo_print' => true,
'no_multiline_whitespace_around_double_arrow' => true,
'no_null_property_initialization' => true,
'no_php4_constructor' => true,
'no_short_bool_cast' => true,
'echo_tag_syntax' => ['format' => 'long'],
'no_singleline_whitespace_before_semicolons' => true,
'no_spaces_after_function_name' => true,
'no_spaces_around_offset' => true,
'no_spaces_inside_parenthesis' => true,
'no_superfluous_elseif' => false, // Might be risky on a huge code base
'no_superfluous_phpdoc_tags' => ['allow_mixed' => true],
'no_trailing_comma_in_list_call' => true,
'no_trailing_comma_in_singleline_array' => true,
'no_trailing_whitespace' => true,
'no_trailing_whitespace_in_comment' => true,
'no_unneeded_control_parentheses' => true,
'no_unneeded_curly_braces' => true,
'no_unneeded_final_method' => true,
'no_unreachable_default_argument_value' => true,
'no_unset_cast' => true,
'no_unset_on_property' => true,
'no_unused_imports' => true,
'no_useless_else' => true,
'no_useless_return' => true,
'no_whitespace_before_comma_in_array' => true,
'no_whitespace_in_blank_line' => true,
'non_printable_character' => true,
'normalize_index_brace' => true,
'not_operator_with_space' => false, // No we prefer to keep '!' without spaces
'not_operator_with_successor_space' => false, // idem
'nullable_type_declaration_for_default_null_value' => true,
'object_operator_without_whitespace' => true,
'ordered_class_elements' => false, // We prefer to keep some freedom
'ordered_imports' => true,
'ordered_interfaces' => true,
'php_unit_construct' => true,
'php_unit_dedicate_assert' => true,
'php_unit_dedicate_assert_internal_type' => true,
'php_unit_expectation' => true,
'php_unit_fqcn_annotation' => true,
'php_unit_internal_class' => false, // Because tests are excluded from package
'php_unit_method_casing' => true,
'php_unit_mock' => true,
'php_unit_mock_short_will_return' => true,
'php_unit_namespaced' => true,
'php_unit_no_expectation_annotation' => true,
'phpdoc_order_by_value' => ['annotations' => ['covers']],
'php_unit_set_up_tear_down_visibility' => true,
'php_unit_size_class' => false, // That seems extra work to maintain for little benefits
'php_unit_strict' => false, // We sometime actually need assertEquals
'php_unit_test_annotation' => true,
'php_unit_test_case_static_method_calls' => ['call_type' => 'self'],
'php_unit_test_class_requires_covers' => false, // We don't care as much as we should about coverage
'phpdoc_add_missing_param_annotation' => false, // Don't add things that bring no value
'phpdoc_align' => false, // Waste of time
'phpdoc_annotation_without_dot' => true,
'phpdoc_indent' => true,
//'phpdoc_inline_tag' => true,
'phpdoc_line_span' => false, // Unfortunately our old comments turn even uglier with this
'phpdoc_no_access' => true,
'phpdoc_no_alias_tag' => true,
'phpdoc_no_empty_return' => true,
'phpdoc_no_package' => true,
'phpdoc_no_useless_inheritdoc' => true,
'phpdoc_order' => true,
'phpdoc_return_self_reference' => true,
'phpdoc_scalar' => true,
'phpdoc_separation' => true,
'phpdoc_single_line_var_spacing' => true,
'phpdoc_summary' => true,
'phpdoc_to_comment' => false, // interferes with annotations
'phpdoc_to_param_type' => false, // Because experimental, but interesting for one shot use
'phpdoc_to_return_type' => false, // idem
'phpdoc_trim' => true,
'phpdoc_trim_consecutive_blank_line_separation' => true,
'phpdoc_types' => true,
'phpdoc_types_order' => true,
'phpdoc_var_annotation_correct_order' => true,
'phpdoc_var_without_name' => true,
'pow_to_exponentiation' => true,
'protected_to_private' => true,
'psr_autoloading' => true,
'random_api_migration' => true,
'return_assignment' => false, // Sometimes useful for clarity or debug
'return_type_declaration' => true,
'self_accessor' => true,
'self_static_accessor' => true,
'semicolon_after_instruction' => false, // Buggy in `samples/index.php`
'set_type_to_cast' => true,
'short_scalar_cast' => true,
'simple_to_complex_string_variable' => false, // Would differ from TypeScript without obvious advantages
'simplified_null_return' => false, // Even if technically correct we prefer to be explicit
'single_blank_line_at_eof' => true,
'single_blank_line_before_namespace' => true,
'single_class_element_per_statement' => true,
'single_import_per_statement' => true,
'single_line_after_imports' => true,
'single_line_comment_style' => true,
'single_line_throw' => false, // I don't see any reason for having a special case for Exception
'single_quote' => true,
'single_trait_insert_per_statement' => true,
'space_after_semicolon' => true,
'standardize_increment' => true,
'standardize_not_equals' => true,
'static_lambda' => false, // Risky if we can't guarantee nobody use `bindTo()`
'strict_comparison' => false, // No, too dangerous to change that
'strict_param' => false, // No, too dangerous to change that
'string_line_ending' => true,
'switch_case_semicolon_to_colon' => true,
'switch_case_space' => true,
'ternary_operator_spaces' => true,
'ternary_to_null_coalescing' => true,
'trailing_comma_in_multiline' => true,
'trim_array_spaces' => true,
'unary_operator_spaces' => true,
'visibility_required' => ['elements' => ['property', 'method']], // not const
'void_return' => true,
'whitespace_after_comma_in_array' => true,
'yoda_style' => false,
]);
return $config;
+31
View File
@@ -0,0 +1,31 @@
# Contributing to PHPWord
PHPWord is built by the crowd and for the crowd. Every contribution is welcome; either by [reporting a bug](https://github.com/PHPOffice/PHPWord/issues/new?labels=Bug+Report&template=bug_report.md) or [suggesting improvements](https://github.com/PHPOffice/PHPWord/issues/new?labels=Change+Request&template=feature_request.md), or in a more active form like [requesting a pull](https://github.com/PHPOffice/PHPWord/pulls).
We want to create a high quality document writer and reader library that people can use with more confidence and fewer bugs. We want to collaborate happily, code joyfully, and live merrily. Thus, below are some guidelines that we expect to be followed by each contributor:
- **Be brief, but be bold**. State your issues briefly. But speak out your ideas loudly, even if you can't or don't know how to implement them right away. The world will be better with limitless innovations.
- **Follow PHP-FIG standards**. We follow PHP Standards Recommendations (PSRs) by [PHP Framework Interoperability Group](http://www.php-fig.org/). If you're not familiar with these standards, [familiarize yourself now](https://github.com/php-fig/fig-standards). Also, please run `composer fix` to automatically fix your code to match these recommendations.
- **Test your code**. No one knows your code better than you, so we depend on you to test the changes you make before pull request submission. We use [PHPUnit](https://phpunit.de/) for our testing purposes and request that you use this tool too. Tests can be ran with `composer test`. [Documentation for writing tests with PHPUnit is available on Read the Docs.](https://phpunit.readthedocs.io)
- **Use best practices when submitting pull requests**. Create a separate branch named specifically for the issue that you are addressing. Read the [GitHub manual](https://help.github.com/articles/about-pull-requests) to learn more about pull requests and GitHub. If you are new to GitHub, read [this short manual](https://help.github.com/articles/fork-a-repo) to get yourself familiar with forks and how git works in general. [This video](http://www.youtube.com/watch?v=-zvHQXnBO6c) explains how to synchronize your fork on GitHub with the upstream branch from PHPWord.
## Getting Started
1. [Clone](https://help.github.com/en/articles/cloning-a-repository) [PHPWord](https://github.com/PHPOffice/PHPWord/)
2. [Install Composer](https://getcomposer.org/download/) if you don't already have it
3. Open your terminal and:
1. Switch to the directory PHPWord was cloned to (e.g., `cd ~/Projects/PHPWord/`)
2. Run `composer install` to install the dependencies
You're ready to start working on PHPWord! Tests belong in the `/tests/PhpWord/` directory, the source code is in `/src/PhpWord/`, and any documentation should go in `/docs/`. Familiarize yourself with the codebase and try your hand at fixing [one of our outstanding issues](https://github.com/PHPOffice/PHPWord/issues). Before you get started, check the [existing pull requests](https://github.com/PHPOffice/PHPWord/pulls) to make sure no one else is already working on it.
Once you have an issue you want to start working on, you'll need to write tests for it, and then you can start implementing the changes necessary to pass the new tests. To run the tests, you can run one of the following commands in your terminal:
- `composer test-no-coverage` to run all of the tests
- `composer test` to run all of the tests and generate test coverage reports
When you're ready to submit your new (and fully tested) feature, ensure `composer check` passes and [submit a pull request to PHPWord](https://github.com/PHPOffice/PHPWord/issues/new).
That's it. Thank you for your interest in PHPWord, and welcome!
May the Force be with you.
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<http://www.gnu.org/licenses/>.
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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+165
View File
@@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
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.
+15
View File
@@ -0,0 +1,15 @@
PHPWord, a pure PHP library for reading and writing word processing documents.
Copyright (c) 2010-2016 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 <http://www.gnu.org/licenses/>.
+162
View File
@@ -0,0 +1,162 @@
# ![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)
[![Coverage Status](https://coveralls.io/repos/github/PHPOffice/PHPWord/badge.svg?branch=master)](https://coveralls.io/github/PHPOffice/PHPWord?branch=master)
[![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)
[![CI](https://github.com/PHPOffice/PHPWord/actions/workflows/ci.yml/badge.svg)](https://github.com/PHPOffice/PHPWord/actions/workflows/ci.yml)
[![Join the chat at https://gitter.im/PHPOffice/PHPWord](https://img.shields.io/badge/GITTER-join%20chat-green.svg)](https://gitter.im/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](COPYING.LESSER). PHPWord is aimed to be a high quality software product by incorporating [continuous integration](https://github.com/PHPOffice/PHPWord/actions) and unit testing. You can learn more about PHPWord by reading the [Developers' Documentation](https://phpoffice.github.io/PHPWord/).
If you have any questions, please ask on [StackOverFlow](https://stackoverflow.com/questions/tagged/phpword)
Read more about PHPWord:
- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Getting started](#getting-started)
- [Contributing](#contributing)
- [Developers' Documentation](https://phpoffice.github.io/PHPWord/)
## Features
With PHPWord, you can create OOXML, ODF, or RTF documents dynamically using your PHP 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 headers, main document part, and footers of an OOXML template
- ... and many more features on progress
## Requirements
PHPWord requires the following:
- PHP 7.1+
- [XML Parser extension](http://www.php.net/manual/en/xml.installation.php)
- [Laminas Escaper component](https://docs.laminas.dev/laminas-escaper/intro/)
- [Zip extension](http://php.net/manual/en/book.zip.php) (optional, used to write OOXML and ODF)
- [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 OOXML and ODF)
- [XSL extension](http://php.net/manual/en/book.xsl.php) (optional, used to apply XSL style sheet to template )
- [dompdf library](https://github.com/dompdf/dompdf) (optional, used to write PDF)
## Installation
PHPWord is installed via [Composer](https://getcomposer.org/).
To [add a dependency](https://getcomposer.org/doc/04-schema.md#package-links) to PHPWord in your project, either
Run the following to use the latest stable version
```sh
composer require phpoffice/phpword
```
or if you want the latest unreleased version
```sh
composer require phpoffice/phpword:dev-master
```
## Getting started
The following is a basic usage example of the PHPWord library.
```php
<?php
require_once 'bootstrap.php';
// Creating the new document...
$phpWord = new \PhpOffice\PhpWord\PhpWord();
/* Note: any element you append to a document must reside inside of a Section. */
// Adding an empty Section to the document...
$section = $phpWord->addSection();
// Adding Text element to the Section having font styled by default...
$section->addText(
'"Learn from yesterday, live for today, hope for tomorrow. '
. 'The important thing is not to stop questioning." '
. '(Albert Einstein)'
);
/*
* Note: it's possible to customize font style of the Text element you add in three ways:
* - inline;
* - using named font style (new font style object will be implicitly created);
* - using explicitly created font style object.
*/
// Adding Text element with font customized inline...
$section->addText(
'"Great achievement is usually born of great sacrifice, '
. 'and is never the result of selfishness." '
. '(Napoleon Hill)',
array('name' => 'Tahoma', 'size' => 10)
);
// Adding Text element with font customized using named font style...
$fontStyleName = 'oneUserDefinedStyle';
$phpWord->addFontStyle(
$fontStyleName,
array('name' => 'Tahoma', 'size' => 10, 'color' => '1B2232', 'bold' => true)
);
$section->addText(
'"The greatest accomplishment is not in never falling, '
. 'but in rising again after you fall." '
. '(Vince Lombardi)',
$fontStyleName
);
// Adding Text element with font customized using explicitly created font style object...
$fontStyle = new \PhpOffice\PhpWord\Style\Font();
$fontStyle->setBold(true);
$fontStyle->setName('Tahoma');
$fontStyle->setSize(13);
$myTextElement = $section->addText('"Believe you can and you\'re halfway there." (Theodor Roosevelt)');
$myTextElement->setFontStyle($fontStyle);
// Saving the document as OOXML file...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('helloWorld.docx');
// Saving the document as ODF file...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'ODText');
$objWriter->save('helloWorld.odt');
// Saving the document as HTML file...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML');
$objWriter->save('helloWorld.html');
/* Note: we skip RTF, because it's not XML-based and requires a different example. */
/* Note: we skip PDF, because "HTML-to-PDF" approach is used to create PDF documents. */
```
More examples are provided in the [samples folder](samples/). For an easy access to those samples launch `php -S localhost:8000` in the samples directory then browse to [http://localhost:8000](http://localhost:8000) to view the samples.
You can also read the [Developers' Documentation](https://phpoffice.github.io/PHPWord/) for more detail.
## Contributing
We welcome everyone to contribute to PHPWord. Below are some of the things that you can do to contribute.
- Read [our contributing guide](CONTRIBUTING.md).
- [Fork us](https://github.com/PHPOffice/PHPWord/fork) and [request a pull](https://github.com/PHPOffice/PHPWord/pulls) to the [master](https://github.com/PHPOffice/PHPWord/tree/master) branch.
- Submit [bug reports or feature requests](https://github.com/PHPOffice/PHPWord/issues) to GitHub.
- Follow [@PHPOffice](https://twitter.com/PHPOffice) on Twitter.
+28
View File
@@ -0,0 +1,28 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors. test bootstrap
*
* @see https://github.com/PHPOffice/PHPWord
* @copyright 2010-2018 PHPWord contributors
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
$vendorDirPath = realpath(__DIR__ . '/vendor');
if (file_exists($vendorDirPath . '/autoload.php')) {
require $vendorDirPath . '/autoload.php';
} else {
throw new Exception(
sprintf(
'Could not find file \'%s\'. It is generated by Composer. Use \'install --prefer-source\' or \'update --prefer-source\' Composer commands to move forward.',
$vendorDirPath . '/autoload.php'
)
);
}
+103
View File
@@ -0,0 +1,103 @@
{
"name": "phpoffice/phpword",
"description": "PHPWord - A pure PHP library for reading and writing word processing documents (OOXML, ODF, RTF, HTML, PDF)",
"keywords": [
"PHP", "PHPOffice", "office", "PHPWord", "word", "template", "template processor", "reader", "writer",
"docx", "OOXML", "OpenXML", "Office Open XML", "ISO IEC 29500", "WordprocessingML",
"RTF", "Rich Text Format", "doc", "odt", "ODF", "OpenDocument", "PDF", "HTML"
],
"homepage": "https://phpoffice.github.io/PHPWord/",
"type": "library",
"license": "LGPL-3.0",
"authors": [
{
"name": "Mark Baker"
},
{
"name": "Gabriel Bull",
"email": "me@gabrielbull.com",
"homepage": "http://gabrielbull.com/"
},
{
"name": "Franck Lefevre",
"homepage": "https://rootslabs.net/blog/"
},
{
"name": "Ivan Lanin",
"homepage": "http://ivan.lanin.org"
},
{
"name": "Roman Syroeshko",
"homepage": "http://ru.linkedin.com/pub/roman-syroeshko/34/a53/994/"
},
{
"name": "Antoine de Troostembergh"
}
],
"scripts": {
"test": [
"phpunit --color=always"
],
"test-no-coverage": [
"phpunit --color=always --no-coverage"
],
"check": [
"php-cs-fixer fix --ansi --dry-run --diff",
"phpcs --report-width=200 --report-summary --report-full samples/ src/ tests/ --ignore=src/PhpWord/Shared/PCLZip --standard=PSR2 -n",
"phpmd src/,tests/ text ./phpmd.xml.dist --exclude pclzip.lib.php",
"@test-no-coverage",
"phpstan analyse --ansi"
],
"fix": [
"php-cs-fixer fix --ansi"
]
},
"scripts-descriptions": {
"test": "Runs all unit tests",
"test-no-coverage": "Runs all unit tests, without code coverage",
"check": "Runs PHP CheckStyle and PHP Mess detector",
"fix": "Fixes issues found by PHP-CS"
},
"config": {
"platform": {
"php": "8.0"
}
},
"require": {
"php": "^7.1|^8.0",
"ext-dom": "*",
"ext-json": "*",
"ext-xml": "*",
"phpoffice/math": "^0.2"
},
"require-dev": {
"ext-zip": "*",
"ext-gd": "*",
"ext-libxml": "*",
"dompdf/dompdf": "^2.0",
"mpdf/mpdf": "^8.1",
"phpmd/phpmd": "^2.13",
"phpunit/phpunit": ">=7.0",
"tecnickcom/tcpdf": "^6.5",
"symfony/process": "^4.4 || ^5.0",
"friendsofphp/php-cs-fixer": "^3.3",
"phpstan/phpstan-phpunit": "@stable"
},
"suggest": {
"ext-zip": "Allows writing OOXML and ODF",
"ext-gd2": "Allows adding images",
"ext-xmlwriter": "Allows writing OOXML and ODF",
"ext-xsl": "Allows applying XSL style sheet to headers, to main document part, and to footers of an OOXML template",
"dompdf/dompdf": "Allows writing PDF"
},
"autoload": {
"psr-4": {
"PhpOffice\\PhpWord\\": "src/PhpWord"
}
},
"autoload-dev": {
"psr-4": {
"PhpOffice\\PhpWordTests\\": "tests/PhpWordTests"
}
}
}
+118
View File
@@ -0,0 +1,118 @@
site_name: PHPWord
site_url: https://phpoffice.github.io/PHPWord
repo_url: https://github.com/PHPOffice/PHPWord
repo_name: PHPOffice/PHPWord
edit_uri: edit/develop/docs/
## Theme
theme:
name: material
palette:
primary: indigo
features:
- search.highlight
- search.suggest
## Plugins
plugins:
- search
- autolink_references:
autolinks:
- reference_prefix: GP-
target_url: https://github.com/<num>
- reference_prefix: GH-
target_url: https://github.com/PHPOffice/PHPWord/issues/<num>
- reference_prefix: CP-
target_url: https://archive.codeplex.com/?p=phpword&<num>
## Config
extra:
generator: false
markdown_extensions:
## Syntax highlighting
- pymdownx.highlight
- pymdownx.superfences
## Support for emojis
- pymdownx.emoji:
emoji_index: !!python/name:materialx.emoji.twemoji
emoji_generator: !!python/name:materialx.emoji.to_svg
## Support for call-outs
- admonition
- pymdownx.details
use_directory_urls: false
## Navigation
nav:
- Introduction: 'index.md'
- Install: 'install.md'
- Usage:
- Introduction: 'usage/introduction.md'
- Containers: 'usage/containers.md'
- Elements:
- Introduction: 'usage/elements/index.md'
- Chart: 'usage/elements/chart.md'
- Checkbox: 'usage/elements/checkbox.md'
- Comment: 'usage/elements/comment.md'
- Field: 'usage/elements/field.md'
- Footnote & Endnote: 'usage/elements/note.md'
- Formula: 'usage/elements/formula.md'
- Image: 'usage/elements/image.md'
- Line: 'usage/elements/line.md'
- Link: 'usage/elements/link.md'
- List: 'usage/elements/list.md'
- OLE Object: 'usage/elements/oleobject.md'
- Page Break: 'usage/elements/pagebreak.md'
- Preserve Text: 'usage/elements/preservetext.md'
- Text: 'usage/elements/text.md'
- TextBox: 'usage/elements/textbox.md'
- Text Break: 'usage/elements/textbreak.md'
- Table: 'usage/elements/table.md'
- Table of contents: 'usage/elements/toc.md'
- Title: 'usage/elements/title.md'
- Track Changes: 'usage/elements/trackchanges.md'
- Watermark: 'usage/elements/watermark.md'
- Styles:
- Chart: 'usage/styles/chart.md'
- Font: 'usage/styles/font.md'
- Image: 'usage/styles/image.md'
- Numbering Level: 'usage/styles/numberinglevel.md'
- Paragraph: 'usage/styles/paragraph.md'
- Section: 'usage/styles/section.md'
- Table: 'usage/styles/table.md'
- Template Processing: 'usage/template.md'
- Readers: 'usage/readers.md'
- Writers: 'usage/writers.md'
- FAQ: 'faq.md'
- How to: 'howto.md'
- Credits: 'credits.md'
- Releases:
- '1.x':
- '1.3.0 (WIP)': 'changes/1.x/1.3.0.md'
- '1.2.0': 'changes/1.x/1.2.0.md'
- '1.1.0': 'changes/1.x/1.1.0.md'
- '1.0.0': 'changes/1.x/1.0.0.md'
- '0.x':
- '0.18.3': 'changes/0.x/0.18.3.md'
- '0.18.2': 'changes/0.x/0.18.2.md'
- '0.18.1': 'changes/0.x/0.18.1.md'
- '0.18.0': 'changes/0.x/0.18.0.md'
- '0.17.0': 'changes/0.x/0.17.0.md'
- '0.16.0': 'changes/0.x/0.16.0.md'
- '0.15.0': 'changes/0.x/0.15.0.md'
- '0.14.0': 'changes/0.x/0.14.0.md'
- '0.13.0': 'changes/0.x/0.13.0.md'
- '0.12.1': 'changes/0.x/0.12.1.md'
- '0.12.0': 'changes/0.x/0.12.0.md'
- '0.11.1': 'changes/0.x/0.11.1.md'
- '0.11.0': 'changes/0.x/0.11.0.md'
- '0.10.1': 'changes/0.x/0.10.1.md'
- '0.10.0': 'changes/0.x/0.10.0.md'
- '0.9.1': 'changes/0.x/0.9.1.md'
- '0.9.0': 'changes/0.x/0.9.0.md'
- '0.8.1': 'changes/0.x/0.8.1.md'
- '0.8.0': 'changes/0.x/0.8.0.md'
- '0.7.0': 'changes/0.x/0.7.0.md'
- Developers:
- 'Coveralls': 'https://coveralls.io/github/PHPOffice/PHPWord'
- 'Code Coverage': 'coverage/index.html'
- 'PHPDoc': 'docs/index.html'
File diff suppressed because it is too large Load Diff
+20
View File
@@ -0,0 +1,20 @@
; 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"
outputEscapingEnabled = false
[Font]
defaultFontName = Arial
defaultFontSize = 10
[Paper]
defaultPaper = "A4"
@@ -0,0 +1,91 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Collection;
/**
* Collection abstract class.
*
* @since 0.10.0
* @template T
*/
abstract class AbstractCollection
{
/**
* Items.
*
* @var T[]
*/
private $items = [];
/**
* Get items.
*
* @return T[]
*/
public function getItems(): array
{
return $this->items;
}
/**
* Get item by index.
*
* @return ?T
*/
public function getItem(int $index)
{
if (array_key_exists($index, $this->items)) {
return $this->items[$index];
}
return null;
}
/**
* Set item.
*
* @param ?T $item
*/
public function setItem(int $index, $item): void
{
if (array_key_exists($index, $this->items)) {
$this->items[$index] = $item;
}
}
/**
* Add new item.
*
* @param T $item
*/
public function addItem($item): int
{
$index = $this->countItems();
$this->items[$index] = $item;
return $index;
}
/**
* Get item count.
*/
public function countItems(): int
{
return count($this->items);
}
}
@@ -0,0 +1,30 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Collection;
use PhpOffice\PhpWord\Element\Bookmark;
/**
* Bookmarks collection.
*
* @since 0.12.0
* @extends AbstractCollection<Bookmark>
*/
class Bookmarks extends AbstractCollection
{
}
@@ -0,0 +1,30 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Collection;
use PhpOffice\PhpWord\Element\Chart;
/**
* Charts collection.
*
* @since 0.12.0
* @extends AbstractCollection<Chart>
*/
class Charts extends AbstractCollection
{
}
@@ -0,0 +1,30 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Collection;
use PhpOffice\PhpWord\Element\Comment;
/**
* Comments collection.
*
* @since 0.12.0
* @extends AbstractCollection<Comment>
*/
class Comments extends AbstractCollection
{
}
@@ -0,0 +1,30 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Collection;
use PhpOffice\PhpWord\Element\Endnote;
/**
* Endnotes collection.
*
* @since 0.10.0
* @extends AbstractCollection<Endnote>
*/
class Endnotes extends AbstractCollection
{
}
@@ -0,0 +1,30 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Collection;
use PhpOffice\PhpWord\Element\Footnote;
/**
* Footnotes collection.
*
* @since 0.10.0
* @extends AbstractCollection<Footnote>
*/
class Footnotes extends AbstractCollection
{
}
@@ -0,0 +1,30 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Collection;
use PhpOffice\PhpWord\Element\Title;
/**
* Titles collection.
*
* @since 0.10.0
* @extends AbstractCollection<Title>
*/
class Titles extends AbstractCollection
{
}
@@ -0,0 +1,184 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\ComplexType;
use InvalidArgumentException;
use PhpOffice\PhpWord\SimpleType\NumberFormat;
/**
* Footnote properties.
*
* @see http://www.datypic.com/sc/ooxml/e-w_footnotePr-1.html
*/
final class FootnoteProperties
{
const RESTART_NUMBER_CONTINUOUS = 'continuous';
const RESTART_NUMBER_EACH_SECTION = 'eachSect';
const RESTART_NUMBER_EACH_PAGE = 'eachPage';
const POSITION_PAGE_BOTTOM = 'pageBottom';
const POSITION_BENEATH_TEXT = 'beneathText';
const POSITION_SECTION_END = 'sectEnd';
const POSITION_DOC_END = 'docEnd';
/**
* Footnote Positioning Location.
*
* @var string
*/
private $pos;
/**
* Footnote Numbering Format w:numFmt, one of PhpOffice\PhpWord\SimpleType\NumberFormat.
*
* @var string
*/
private $numFmt;
/**
* Footnote and Endnote Numbering Starting Value.
*
* @var float
*/
private $numStart;
/**
* Footnote and Endnote Numbering Restart Location.
*
* @var string
*/
private $numRestart;
/**
* Get the Footnote Positioning Location.
*
* @return string
*/
public function getPos()
{
return $this->pos;
}
/**
* Set the Footnote Positioning Location (pageBottom, beneathText, sectEnd, docEnd).
*
* @param string $pos
*
* @return self
*/
public function setPos($pos)
{
$position = [
self::POSITION_PAGE_BOTTOM,
self::POSITION_BENEATH_TEXT,
self::POSITION_SECTION_END,
self::POSITION_DOC_END,
];
if (in_array($pos, $position)) {
$this->pos = $pos;
} else {
throw new InvalidArgumentException('Invalid value, on of ' . implode(', ', $position) . ' possible');
}
return $this;
}
/**
* Get the Footnote Numbering Format.
*
* @return string
*/
public function getNumFmt()
{
return $this->numFmt;
}
/**
* Set the Footnote Numbering Format.
*
* @param string $numFmt One of NumberFormat
*
* @return self
*/
public function setNumFmt($numFmt)
{
NumberFormat::validate($numFmt);
$this->numFmt = $numFmt;
return $this;
}
/**
* Get the Footnote Numbering Format.
*
* @return float
*/
public function getNumStart()
{
return $this->numStart;
}
/**
* Set the Footnote Numbering Format.
*
* @param float $numStart
*
* @return self
*/
public function setNumStart($numStart)
{
$this->numStart = $numStart;
return $this;
}
/**
* Get the Footnote and Endnote Numbering Starting Value.
*
* @return string
*/
public function getNumRestart()
{
return $this->numRestart;
}
/**
* Set the Footnote and Endnote Numbering Starting Value (continuous, eachSect, eachPage).
*
* @param string $numRestart
*
* @return self
*/
public function setNumRestart($numRestart)
{
$restartNumbers = [
self::RESTART_NUMBER_CONTINUOUS,
self::RESTART_NUMBER_EACH_SECTION,
self::RESTART_NUMBER_EACH_PAGE,
];
if (in_array($numRestart, $restartNumbers)) {
$this->numRestart = $numRestart;
} else {
throw new InvalidArgumentException('Invalid value, on of ' . implode(', ', $restartNumbers) . ' possible');
}
return $this;
}
}
@@ -0,0 +1,108 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\ComplexType;
use InvalidArgumentException;
/**
* Spelling and Grammatical Checking State.
*
* @see http://www.datypic.com/sc/ooxml/e-w_proofState-1.html
*/
final class ProofState
{
/**
* Check Completed.
*/
const CLEAN = 'clean';
/**
* Check Not Completed.
*/
const DIRTY = 'dirty';
/**
* Spell Checking State.
*
* @var string
*/
private $spelling;
/**
* Grammatical Checking State.
*
* @var string
*/
private $grammar;
/**
* Set the Spell Checking State (dirty or clean).
*
* @param string $spelling
*
* @return self
*/
public function setSpelling($spelling)
{
if ($spelling == self::CLEAN || $spelling == self::DIRTY) {
$this->spelling = $spelling;
} else {
throw new InvalidArgumentException('Invalid value, dirty or clean possible');
}
return $this;
}
/**
* Get the Spell Checking State.
*
* @return string
*/
public function getSpelling()
{
return $this->spelling;
}
/**
* Set the Grammatical Checking State (dirty or clean).
*
* @param string $grammar
*
* @return self
*/
public function setGrammar($grammar)
{
if ($grammar == self::CLEAN || $grammar == self::DIRTY) {
$this->grammar = $grammar;
} else {
throw new InvalidArgumentException('Invalid value, dirty or clean possible');
}
return $this;
}
/**
* Get the Grammatical Checking State.
*
* @return string
*/
public function getGrammar()
{
return $this->grammar;
}
}
@@ -0,0 +1,59 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\ComplexType;
use PhpOffice\PhpWord\SimpleType\TblWidth as TblWidthSimpleType;
/**
* @see http://www.datypic.com/sc/ooxml/t-w_CT_TblWidth.html
*/
final class TblWidth
{
/** @var string */
private $type;
/** @var int */
private $value;
/**
* @param int $value If omitted, then its value shall be assumed to be 0
* @param string $type If omitted, then its value shall be assumed to be dxa
*/
public function __construct($value = 0, $type = TblWidthSimpleType::TWIP)
{
$this->value = $value;
TblWidthSimpleType::validate($type);
$this->type = $type;
}
/**
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* @return int
*/
public function getValue()
{
return $this->value;
}
}
@@ -0,0 +1,166 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\ComplexType;
/**
* Visibility of Annotation Types.
*
* @see http://www.datypic.com/sc/ooxml/e-w_revisionView-1.html
*/
final class TrackChangesView
{
/**
* Display Visual Indicator Of Markup Area.
*
* @var bool
*/
private $markup;
/**
* Display Comments.
*
* @var bool
*/
private $comments;
/**
* Display Content Revisions.
*
* @var bool
*/
private $insDel;
/**
* Display Formatting Revisions.
*
* @var bool
*/
private $formatting;
/**
* Display Ink Annotations.
*
* @var bool
*/
private $inkAnnotations;
/**
* Get Display Visual Indicator Of Markup Area.
*
* @return bool True if markup is shown
*/
public function hasMarkup()
{
return $this->markup;
}
/**
* Set Display Visual Indicator Of Markup Area.
*
* @param ?bool $markup
* Set to true to show markup
*/
public function setMarkup($markup): void
{
$this->markup = $markup === null ? true : $markup;
}
/**
* Get Display Comments.
*
* @return bool True if comments are shown
*/
public function hasComments()
{
return $this->comments;
}
/**
* Set Display Comments.
*
* @param ?bool $comments
* Set to true to show comments
*/
public function setComments($comments): void
{
$this->comments = $comments === null ? true : $comments;
}
/**
* Get Display Content Revisions.
*
* @return bool True if content revisions are shown
*/
public function hasInsDel()
{
return $this->insDel;
}
/**
* Set Display Content Revisions.
*
* @param ?bool $insDel
* Set to true to show content revisions
*/
public function setInsDel($insDel): void
{
$this->insDel = $insDel === null ? true : $insDel;
}
/**
* Get Display Formatting Revisions.
*
* @return bool True if formatting revisions are shown
*/
public function hasFormatting()
{
return $this->formatting;
}
/**
* Set Display Formatting Revisions.
*
* @param null|bool $formatting
* Set to true to show formatting revisions
*/
public function setFormatting($formatting = null): void
{
$this->formatting = $formatting === null ? true : $formatting;
}
/**
* Get Display Ink Annotations.
*
* @return bool True if ink annotations are shown
*/
public function hasInkAnnotations()
{
return $this->inkAnnotations;
}
/**
* Set Display Ink Annotations.
*
* @param ?bool $inkAnnotations
* Set to true to show ink annotations
*/
public function setInkAnnotations($inkAnnotations): void
{
$this->inkAnnotations = $inkAnnotations === null ? true : $inkAnnotations;
}
}
@@ -0,0 +1,291 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use BadMethodCallException;
use PhpOffice\Math\Math;
use ReflectionClass;
/**
* Container abstract class.
*
* @method Text addText(string $text, mixed $fStyle = null, mixed $pStyle = null)
* @method TextRun addTextRun(mixed $pStyle = null)
* @method Bookmark addBookmark(string $name)
* @method Link addLink(string $target, string $text = null, mixed $fStyle = null, mixed $pStyle = null, boolean $internal = false)
* @method PreserveText addPreserveText(string $text, mixed $fStyle = null, mixed $pStyle = null)
* @method void addTextBreak(int $count = 1, mixed $fStyle = null, mixed $pStyle = null)
* @method ListItem addListItem(string $txt, int $depth = 0, mixed $font = null, mixed $list = null, mixed $para = null)
* @method ListItemRun addListItemRun(int $depth = 0, mixed $listStyle = null, mixed $pStyle = null)
* @method Footnote addFootnote(mixed $pStyle = null)
* @method Endnote addEndnote(mixed $pStyle = null)
* @method CheckBox addCheckBox(string $name, $text, mixed $fStyle = null, mixed $pStyle = null)
* @method Title addTitle(mixed $text, int $depth = 1, int $pageNumber = null)
* @method TOC addTOC(mixed $fontStyle = null, mixed $tocStyle = null, int $minDepth = 1, int $maxDepth = 9)
* @method PageBreak addPageBreak()
* @method Table addTable(mixed $style = null)
* @method Image addImage(string $source, mixed $style = null, bool $isWatermark = false, $name = null)
* @method OLEObject addOLEObject(string $source, mixed $style = null)
* @method TextBox addTextBox(mixed $style = null)
* @method Field addField(string $type = null, array $properties = array(), array $options = array(), mixed $text = null)
* @method Line addLine(mixed $lineStyle = null)
* @method Shape addShape(string $type, mixed $style = null)
* @method Chart addChart(string $type, array $categories, array $values, array $style = null, $seriesName = null)
* @method FormField addFormField(string $type, mixed $fStyle = null, mixed $pStyle = null)
* @method SDT addSDT(string $type)
* @method Formula addFormula(Math $math)
* @method \PhpOffice\PhpWord\Element\OLEObject addObject(string $source, mixed $style = null) deprecated, use addOLEObject instead
*
* @since 0.10.0
*/
abstract class AbstractContainer extends AbstractElement
{
/**
* Elements collection.
*
* @var \PhpOffice\PhpWord\Element\AbstractElement[]
*/
protected $elements = [];
/**
* Container type Section|Header|Footer|Footnote|Endnote|Cell|TextRun|TextBox|ListItemRun|TrackChange.
*
* @var string
*/
protected $container;
/**
* Magic method to catch all 'addElement' variation.
*
* This removes addText, addTextRun, etc. When adding new element, we have to
* add the model in the class docblock with `@method`.
*
* Warning: This makes capitalization matters, e.g. addCheckbox or addcheckbox won't work.
*
* @param mixed $function
* @param mixed $args
*
* @return \PhpOffice\PhpWord\Element\AbstractElement
*/
public function __call($function, $args)
{
$elements = [
'Text', 'TextRun', 'Bookmark', 'Link', 'PreserveText', 'TextBreak',
'ListItem', 'ListItemRun', 'Table', 'Image', 'Object', 'OLEObject',
'Footnote', 'Endnote', 'CheckBox', 'TextBox', 'Field',
'Line', 'Shape', 'Title', 'TOC', 'PageBreak',
'Chart', 'FormField', 'SDT', 'Comment',
'Formula',
];
$functions = [];
foreach ($elements as $element) {
$functions['add' . strtolower($element)] = $element == 'Object' ? 'OLEObject' : $element;
}
// Run valid `add` command
$function = strtolower($function);
if (isset($functions[$function])) {
$element = $functions[$function];
// Special case for TextBreak
// @todo Remove the `$count` parameter in 1.0.0 to make this element similiar to other elements?
if ($element == 'TextBreak') {
[$count, $fontStyle, $paragraphStyle] = array_pad($args, 3, null);
if ($count === null) {
$count = 1;
}
for ($i = 1; $i <= $count; ++$i) {
$this->addElement($element, $fontStyle, $paragraphStyle);
}
} else {
// All other elements
array_unshift($args, $element); // Prepend element name to the beginning of args array
return call_user_func_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, ['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 \PhpOffice\PhpWord\Element\AbstractElement[]
*/
public function getElements()
{
return $this->elements;
}
/**
* Returns the element at the requested position.
*
* @param int $index
*
* @return null|\PhpOffice\PhpWord\Element\AbstractElement
*/
public function getElement($index)
{
if (array_key_exists($index, $this->elements)) {
return $this->elements[$index];
}
return null;
}
/**
* Removes the element at requested index.
*
* @param int|\PhpOffice\PhpWord\Element\AbstractElement $toRemove
*/
public function removeElement($toRemove): void
{
if (is_int($toRemove) && array_key_exists($toRemove, $this->elements)) {
unset($this->elements[$toRemove]);
} elseif ($toRemove instanceof \PhpOffice\PhpWord\Element\AbstractElement) {
foreach ($this->elements as $key => $element) {
if ($element->getElementId() === $toRemove->getElementId()) {
unset($this->elements[$key]);
return;
}
}
}
}
/**
* 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
*/
private function checkValidity($method)
{
$generalContainers = [
'Section', 'Header', 'Footer', 'Footnote', 'Endnote', 'Cell', 'TextRun', 'TextBox', 'ListItemRun', 'TrackChange',
];
$validContainers = [
'Text' => $generalContainers,
'Bookmark' => $generalContainers,
'Link' => $generalContainers,
'TextBreak' => $generalContainers,
'Image' => $generalContainers,
'OLEObject' => $generalContainers,
'Field' => $generalContainers,
'Line' => $generalContainers,
'Shape' => $generalContainers,
'FormField' => $generalContainers,
'SDT' => $generalContainers,
'TrackChange' => $generalContainers,
'TextRun' => ['Section', 'Header', 'Footer', 'Cell', 'TextBox', 'TrackChange', 'ListItemRun'],
'ListItem' => ['Section', 'Header', 'Footer', 'Cell', 'TextBox'],
'ListItemRun' => ['Section', 'Header', 'Footer', 'Cell', 'TextBox'],
'Table' => ['Section', 'Header', 'Footer', 'Cell', 'TextBox'],
'CheckBox' => ['Section', 'Header', 'Footer', 'Cell', 'TextRun'],
'TextBox' => ['Section', 'Header', 'Footer', 'Cell'],
'Footnote' => ['Section', 'TextRun', 'Cell', 'ListItemRun'],
'Endnote' => ['Section', 'TextRun', 'Cell'],
'PreserveText' => ['Section', 'Header', 'Footer', 'Cell'],
'Title' => ['Section', 'Cell'],
'TOC' => ['Section'],
'PageBreak' => ['Section'],
'Chart' => ['Section', 'Cell'],
];
// Special condition, e.g. preservetext can only exists in cell when
// the cell is located in header or footer
$validSubcontainers = [
'PreserveText' => [['Cell'], ['Header', 'Footer', 'Section']],
'Footnote' => [['Cell', 'TextRun'], ['Section']],
'Endnote' => [['Cell', 'TextRun'], ['Section']],
];
// Check if a method is valid for current container
if (isset($validContainers[$method])) {
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 (isset($validSubcontainers[$method])) {
$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;
}
}
@@ -0,0 +1,553 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use DateTime;
use InvalidArgumentException;
use PhpOffice\PhpWord\Collection\Comments;
use PhpOffice\PhpWord\Media;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Style;
/**
* Element abstract class.
*
* @since 0.10.0
*/
abstract class AbstractElement
{
/**
* PhpWord object.
*
* @var ?PhpWord
*/
protected $phpWord;
/**
* Section Id.
*
* @var int
*/
protected $sectionId;
/**
* Document part type: Section|Header|Footer|Footnote|Endnote.
*
* Used by textrun and cell container to determine where the element is
* located because it will affect the availability of other element,
* e.g. footnote will not be available when $docPart is header or footer.
*
* @var string
*/
protected $docPart = 'Section';
/**
* Document part Id.
*
* For header and footer, this will be = ($sectionId - 1) * 3 + $index
* because the max number of header/footer in every page is 3, i.e.
* AUTO, FIRST, and EVEN (AUTO = ODD)
*
* @var int
*/
protected $docPartId = 1;
/**
* Index of element in the elements collection (start with 1).
*
* @var int
*/
protected $elementIndex = 1;
/**
* Unique Id for element.
*
* @var string
*/
protected $elementId;
/**
* Relation Id.
*
* @var int
*/
protected $relationId;
/**
* Depth of table container nested level; Primarily used for RTF writer/reader.
*
* 0 = Not in a table; 1 = in a table; 2 = in a table inside another table, etc.
*
* @var int
*/
private $nestedLevel = 0;
/**
* A reference to the parent.
*
* @var null|AbstractElement
*/
private $parent;
/**
* changed element info.
*
* @var TrackChange
*/
private $trackChange;
/**
* Parent container type.
*
* @var string
*/
private $parentContainer;
/**
* Has media relation flag; true for Link, Image, and Object.
*
* @var bool
*/
protected $mediaRelation = false;
/**
* Is part of collection; true for Title, Footnote, Endnote, Chart, and Comment.
*
* @var bool
*/
protected $collectionRelation = false;
/**
* The start position for the linked comments.
*
* @var Comments
*/
protected $commentsRangeStart;
/**
* The end position for the linked comments.
*
* @var Comments
*/
protected $commentsRangeEnd;
/**
* Get PhpWord.
*
* @return ?PhpWord
*/
public function getPhpWord(): ?PhpWord
{
return $this->phpWord;
}
/**
* Set PhpWord as reference.
*/
public function setPhpWord(?PhpWord $phpWord = null): void
{
$this->phpWord = $phpWord;
}
/**
* Get section number.
*
* @return int
*/
public function getSectionId()
{
return $this->sectionId;
}
/**
* Set doc part.
*
* @param string $docPart
* @param int $docPartId
*/
public function setDocPart($docPart, $docPartId = 1): void
{
$this->docPart = $docPart;
$this->docPartId = $docPartId;
}
/**
* Get doc part.
*
* @return string
*/
public function getDocPart()
{
return $this->docPart;
}
/**
* Get doc part Id.
*
* @return int
*/
public function getDocPartId()
{
return $this->docPartId;
}
/**
* Return media element (image, object, link) container name.
*
* @return string section|headerx|footerx|footnote|endnote
*/
private function getMediaPart()
{
$mediaPart = $this->docPart;
if ($mediaPart == 'Header' || $mediaPart == 'Footer') {
$mediaPart .= $this->docPartId;
}
return strtolower($mediaPart);
}
/**
* Get element index.
*
* @return int
*/
public function getElementIndex()
{
return $this->elementIndex;
}
/**
* Set element index.
*
* @param int $value
*/
public function setElementIndex($value): void
{
$this->elementIndex = $value;
}
/**
* Get element unique ID.
*
* @return string
*/
public function getElementId()
{
return $this->elementId;
}
/**
* Set element unique ID from 6 first digit of md5.
*/
public function setElementId(): void
{
$this->elementId = substr(md5(mt_rand()), 0, 6);
}
/**
* Get relation Id.
*
* @return int
*/
public function getRelationId()
{
return $this->relationId;
}
/**
* Set relation Id.
*
* @param int $value
*/
public function setRelationId($value): void
{
$this->relationId = $value;
}
/**
* Get nested level.
*
* @return int
*/
public function getNestedLevel()
{
return $this->nestedLevel;
}
/**
* Get comments start.
*
* @return Comments
*/
public function getCommentsRangeStart(): ?Comments
{
return $this->commentsRangeStart;
}
/**
* Get comment start.
*
* @return Comment
*/
public function getCommentRangeStart(): ?Comment
{
if ($this->commentsRangeStart != null) {
return $this->commentsRangeStart->getItem($this->commentsRangeStart->countItems());
}
return null;
}
/**
* Set comment start.
*/
public function setCommentRangeStart(Comment $value): void
{
if ($this instanceof Comment) {
throw new InvalidArgumentException('Cannot set a Comment on a Comment');
}
if ($this->commentsRangeStart == null) {
$this->commentsRangeStart = new Comments();
}
// Set ID early to avoid duplicates.
if ($value->getElementId() == null) {
$value->setElementId();
}
foreach ($this->commentsRangeStart->getItems() as $comment) {
if ($value->getElementId() == $comment->getElementId()) {
return;
}
}
$idxItem = $this->commentsRangeStart->addItem($value);
$this->commentsRangeStart->getItem($idxItem)->setStartElement($this);
}
/**
* Get comments end.
*
* @return Comments
*/
public function getCommentsRangeEnd(): ?Comments
{
return $this->commentsRangeEnd;
}
/**
* Get comment end.
*
* @return Comment
*/
public function getCommentRangeEnd(): ?Comment
{
if ($this->commentsRangeEnd != null) {
return $this->commentsRangeEnd->getItem($this->commentsRangeEnd->countItems());
}
return null;
}
/**
* Set comment end.
*/
public function setCommentRangeEnd(Comment $value): void
{
if ($this instanceof Comment) {
throw new InvalidArgumentException('Cannot set a Comment on a Comment');
}
if ($this->commentsRangeEnd == null) {
$this->commentsRangeEnd = new Comments();
}
// Set ID early to avoid duplicates.
if ($value->getElementId() == null) {
$value->setElementId();
}
foreach ($this->commentsRangeEnd->getItems() as $comment) {
if ($value->getElementId() == $comment->getElementId()) {
return;
}
}
$idxItem = $this->commentsRangeEnd->addItem($value);
$this->commentsRangeEnd->getItem($idxItem)->setEndElement($this);
}
/**
* Get parent element.
*
* @return null|AbstractElement
*/
public function getParent()
{
return $this->parent;
}
/**
* Set parent container.
*
* Passed parameter should be a container, except for Table (contain Row) and Row (contain Cell)
*/
public function setParentContainer(self $container): void
{
$this->parentContainer = substr(get_class($container), strrpos(get_class($container), '\\') + 1);
$this->parent = $container;
// 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
*/
private function setMediaRelation(): void
{
if (!$this instanceof Link && !$this instanceof Image && !$this instanceof OLEObject) {
return;
}
$elementName = substr(static::class, strrpos(static::class, '\\') + 1);
if ($elementName == 'OLEObject') {
$elementName = 'Object';
}
$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 OLEObject) {
$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.
*/
private function setCollectionRelation(): void
{
if ($this->collectionRelation === true && $this->phpWord instanceof PhpWord) {
$elementName = substr(static::class, strrpos(static::class, '\\') + 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';
}
/**
* Set new style value.
*
* @param mixed $styleObject Style object
* @param null|array|string|Style $styleValue Style value
* @param bool $returnObject Always return object
*
* @return mixed
*/
protected function setNewStyle($styleObject, $styleValue = null, $returnObject = false)
{
if (null !== $styleValue && is_array($styleValue)) {
$styleObject->setStyleByArray($styleValue);
$style = $styleObject;
} else {
$style = $returnObject ? $styleObject : $styleValue;
}
return $style;
}
/**
* Sets the trackChange information.
*/
public function setTrackChange(TrackChange $trackChange): void
{
$this->trackChange = $trackChange;
}
/**
* Gets the trackChange information.
*
* @return TrackChange
*/
public function getTrackChange()
{
return $this->trackChange;
}
/**
* Set changed.
*
* @param string $type INSERTED|DELETED
* @param string $author
* @param null|DateTime|int $date allways in UTC
*/
public function setChangeInfo($type, $author, $date = null): void
{
$this->trackChange = new TrackChange($type, $author, $date);
}
/**
* Set enum value.
*
* @param null|string $value
* @param string[] $enum
* @param null|string $default
*
* @return null|string
*
* @todo Merge with the same method in AbstractStyle
*/
protected function setEnumVal($value = null, $enum = [], $default = null)
{
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;
}
}
@@ -0,0 +1,60 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Shared\Text as SharedText;
/**
* Bookmark element.
*/
class Bookmark extends AbstractElement
{
/**
* Bookmark Name.
*
* @var string
*/
private $name;
/**
* Is part of collection.
*
* @var bool
*/
protected $collectionRelation = true;
/**
* Create a new Bookmark Element.
*
* @param string $name
*/
public function __construct($name = '')
{
$this->name = SharedText::toUTF8($name);
}
/**
* Get Bookmark name.
*
* @return string
*/
public function getName()
{
return $this->name;
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Style\Cell as CellStyle;
/**
* Table cell element.
*/
class Cell extends AbstractContainer
{
/**
* @var string Container type
*/
protected $container = 'Cell';
/**
* Cell width.
*
* @var ?int
*/
private $width;
/**
* Cell style.
*
* @var ?\PhpOffice\PhpWord\Style\Cell
*/
private $style;
/**
* Create new instance.
*
* @param null|int $width
* @param array|\PhpOffice\PhpWord\Style\Cell $style
*/
public function __construct($width = null, $style = null)
{
$this->width = $width;
$this->style = $this->setNewStyle(new CellStyle(), $style, true);
}
/**
* Get cell style.
*
* @return ?\PhpOffice\PhpWord\Style\Cell
*/
public function getStyle()
{
return $this->style;
}
/**
* Get cell width.
*
* @return ?int
*/
public function getWidth()
{
return $this->width;
}
}
+129
View File
@@ -0,0 +1,129 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Style\Chart as ChartStyle;
/**
* Chart element.
*
* @since 0.12.0
*/
class Chart extends AbstractElement
{
/**
* Is part of collection.
*
* @var bool
*/
protected $collectionRelation = true;
/**
* Type.
*
* @var string
*/
private $type = 'pie';
/**
* Series.
*
* @var array
*/
private $series = [];
/**
* Chart style.
*
* @var ?\PhpOffice\PhpWord\Style\Chart
*/
private $style;
/**
* Create new instance.
*
* @param string $type
* @param array $categories
* @param array $values
* @param array $style
* @param null|mixed $seriesName
*/
public function __construct($type, $categories, $values, $style = null, $seriesName = null)
{
$this->setType($type);
$this->addSeries($categories, $values, $seriesName);
$this->style = $this->setNewStyle(new ChartStyle(), $style, true);
}
/**
* Get type.
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* Set type.
*
* @param string $value
*/
public function setType($value): void
{
$enum = ['pie', 'doughnut', 'line', 'bar', 'stacked_bar', 'percent_stacked_bar', 'column', 'stacked_column', 'percent_stacked_column', 'area', 'radar', 'scatter'];
$this->type = $this->setEnumVal($value, $enum, 'pie');
}
/**
* Add series.
*
* @param array $categories
* @param array $values
* @param null|mixed $name
*/
public function addSeries($categories, $values, $name = null): void
{
$this->series[] = [
'categories' => $categories,
'values' => $values,
'name' => $name,
];
}
/**
* Get series.
*
* @return array
*/
public function getSeries()
{
return $this->series;
}
/**
* Get chart style.
*
* @return ?\PhpOffice\PhpWord\Style\Chart
*/
public function getStyle()
{
return $this->style;
}
}
@@ -0,0 +1,73 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Shared\Text as SharedText;
/**
* Check box element.
*
* @since 0.10.0
*/
class CheckBox extends Text
{
/**
* Name content.
*
* @var string
*/
private $name;
/**
* Create new instance.
*
* @param string $name
* @param string $text
* @param mixed $fontStyle
* @param mixed $paragraphStyle
*/
public function __construct($name = null, $text = null, $fontStyle = null, $paragraphStyle = null)
{
$this->setName($name);
parent::__construct($text, $fontStyle, $paragraphStyle);
}
/**
* Set name content.
*
* @param string $name
*
* @return self
*/
public function setName($name)
{
$this->name = SharedText::toUTF8($name);
return $this;
}
/**
* Get name content.
*
* @return string
*/
public function getName()
{
return $this->name;
}
}
+117
View File
@@ -0,0 +1,117 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use DateTime;
/**
* Comment element.
*
* @see http://datypic.com/sc/ooxml/t-w_CT_Comment.html
*/
class Comment extends TrackChange
{
/**
* Initials.
*
* @var string
*/
private $initials;
/**
* The Element where this comment starts.
*
* @var AbstractElement
*/
private $startElement;
/**
* The Element where this comment ends.
*
* @var AbstractElement
*/
private $endElement;
/**
* Is part of collection.
*
* @var bool
*/
protected $collectionRelation = true;
/**
* Create a new Comment Element.
*
* @param string $author
* @param null|DateTime $date
* @param string $initials
*/
public function __construct($author, $date = null, $initials = null)
{
parent::__construct(null, $author, $date);
$this->initials = $initials;
}
/**
* Get Initials.
*
* @return string
*/
public function getInitials()
{
return $this->initials;
}
/**
* Sets the element where this comment starts.
*/
public function setStartElement(AbstractElement $value): void
{
$this->startElement = $value;
$value->setCommentRangeStart($this);
}
/**
* Get the element where this comment starts.
*
* @return \PhpOffice\PhpWord\Element\AbstractElement
*/
public function getStartElement()
{
return $this->startElement;
}
/**
* Sets the element where this comment ends.
*/
public function setEndElement(AbstractElement $value): void
{
$this->endElement = $value;
$value->setCommentRangeEnd($this);
}
/**
* Get the element where this comment ends.
*
* @return \PhpOffice\PhpWord\Element\AbstractElement
*/
public function getEndElement()
{
return $this->endElement;
}
}
@@ -0,0 +1,41 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
/**
* Endnote element.
*
* @since 0.10.0
*/
class Endnote extends Footnote
{
/**
* @var string Container type
*/
protected $container = 'Endnote';
/**
* Create new instance.
*
* @param array|\PhpOffice\PhpWord\Style\Paragraph|string $paragraphStyle
*/
public function __construct($paragraphStyle = null)
{
parent::__construct($paragraphStyle);
}
}
+307
View File
@@ -0,0 +1,307 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use InvalidArgumentException;
use PhpOffice\PhpWord\Style\Font;
/**
* Field element.
*
* @since 0.11.0
* @see http://www.schemacentral.com/sc/ooxml/t-w_CT_SimpleField.html
*/
class Field extends AbstractElement
{
/**
* Field properties and options. Depending on type, a field can have different properties
* and options.
*
* @var array
*/
protected $fieldsArray = [
'PAGE' => [
'properties' => [
'format' => ['Arabic', 'ArabicDash', 'alphabetic', 'ALPHABETIC', 'roman', 'ROMAN'],
],
'options' => ['PreserveFormat'],
],
'NUMPAGES' => [
'properties' => [
'format' => ['Arabic', 'ArabicDash', 'CardText', 'DollarText', 'Ordinal', 'OrdText',
'alphabetic', 'ALPHABETIC', 'roman', 'ROMAN', 'Caps', 'FirstCap', 'Lower', 'Upper', ],
'numformat' => ['0', '0,00', '#.##0', '#.##0,00', '€ #.##0,00(€ #.##0,00)', '0%', '0,00%'],
],
'options' => ['PreserveFormat'],
],
'DATE' => [
'properties' => [
'dateformat' => [
// Generic formats
'yyyy-MM-dd', 'yyyy-MM', 'MMM-yy', 'MMM-yyyy', 'h:mm am/pm', 'h:mm:ss am/pm', 'HH:mm', 'HH:mm:ss',
// Day-Month-Year formats
'dddd d MMMM yyyy', 'd MMMM yyyy', 'd-MMM-yy', 'd MMM. yy',
'd-M-yy', 'd-M-yy h:mm', 'd-M-yy h:mm:ss', 'd-M-yy h:mm am/pm', 'd-M-yy h:mm:ss am/pm', 'd-M-yy HH:mm', 'd-M-yy HH:mm:ss',
'd/M/yy', 'd/M/yy h:mm', 'd/M/yy h:mm:ss', 'd/M/yy h:mm am/pm', 'd/M/yy h:mm:ss am/pm', 'd/M/yy HH:mm', 'd/M/yy HH:mm:ss',
'd-M-yyyy', 'd-M-yyyy h:mm', 'd-M-yyyy h:mm:ss', 'd-M-yyyy h:mm am/pm', 'd-M-yyyy h:mm:ss am/pm', 'd-M-yyyy HH:mm', 'd-M-yyyy HH:mm:ss',
'd/M/yyyy', 'd/M/yyyy h:mm', 'd/M/yyyy h:mm:ss', 'd/M/yyyy h:mm am/pm', 'd/M/yyyy h:mm:ss am/pm', 'd/M/yyyy HH:mm', 'd/M/yyyy HH:mm:ss',
// Month-Day-Year formats
'dddd, MMMM d yyyy', 'MMMM d yyyy', 'MMM-d-yy', 'MMM. d yy',
'M-d-yy', 'M-d-yy h:mm', 'M-d-yy h:mm:ss', 'M-d-yy h:mm am/pm', 'M-d-yy h:mm:ss am/pm', 'M-d-yy HH:mm', 'M-d-yy HH:mm:ss',
'M/d/yy', 'M/d/yy h:mm', 'M/d/yy h:mm:ss', 'M/d/yy h:mm am/pm', 'M/d/yy h:mm:ss am/pm', 'M/d/yy HH:mm', 'M/d/yy HH:mm:ss',
'M-d-yyyy', 'M-d-yyyy h:mm', 'M-d-yyyy h:mm:ss', 'M-d-yyyy h:mm am/pm', 'M-d-yyyy h:mm:ss am/pm', 'M-d-yyyy HH:mm', 'M-d-yyyy HH:mm:ss',
'M/d/yyyy', 'M/d/yyyy h:mm', 'M/d/yyyy h:mm:ss', 'M/d/yyyy h:mm am/pm', 'M/d/yyyy h:mm:ss am/pm', 'M/d/yyyy HH:mm', 'M/d/yyyy HH:mm:ss',
],
],
'options' => ['PreserveFormat', 'LunarCalendar', 'SakaEraCalendar', 'LastUsedFormat'],
],
'MACROBUTTON' => [
'properties' => ['macroname' => ''],
],
'XE' => [
'properties' => [],
'options' => ['Bold', 'Italic'],
],
'INDEX' => [
'properties' => [],
'options' => ['PreserveFormat'],
],
'STYLEREF' => [
'properties' => ['StyleIdentifier' => ''],
'options' => ['PreserveFormat'],
],
'FILENAME' => [
'properties' => [
'format' => ['Upper', 'Lower', 'FirstCap', 'Caps'],
],
'options' => ['Path', 'PreserveFormat'],
],
'REF' => [
'properties' => ['name' => ''],
'options' => ['f', 'h', 'n', 'p', 'r', 't', 'w'],
],
];
/**
* Field type.
*
* @var string
*/
protected $type;
/**
* Field text.
*
* @var string|TextRun
*/
protected $text;
/**
* Field properties.
*
* @var array
*/
protected $properties = [];
/**
* Field options.
*
* @var array
*/
protected $options = [];
/**
* Font style.
*
* @var \PhpOffice\PhpWord\Style\Font|string
*/
protected $fontStyle;
/**
* Set Font style.
*
* @param array|\PhpOffice\PhpWord\Style\Font|string $style
*
* @return \PhpOffice\PhpWord\Style\Font|string
*/
public function setFontStyle($style = null)
{
if ($style instanceof Font) {
$this->fontStyle = $style;
} elseif (is_array($style)) {
$this->fontStyle = new Font('text');
$this->fontStyle->setStyleByArray($style);
} elseif (null === $style) {
$this->fontStyle = null;
} else {
$this->fontStyle = $style;
}
return $this->fontStyle;
}
/**
* Get Font style.
*
* @return \PhpOffice\PhpWord\Style\Font|string
*/
public function getFontStyle()
{
return $this->fontStyle;
}
/**
* Create a new Field Element.
*
* @param string $type
* @param array $properties
* @param array $options
* @param null|string|TextRun $text
* @param array|\PhpOffice\PhpWord\Style\Font|string $fontStyle
*/
public function __construct($type = null, $properties = [], $options = [], $text = null, $fontStyle = null)
{
$this->setType($type);
$this->setProperties($properties);
$this->setOptions($options);
$this->setText($text);
$this->setFontStyle($fontStyle);
}
/**
* Set Field type.
*
* @param string $type
*
* @return string
*/
public function setType($type = null)
{
if (isset($type)) {
if (isset($this->fieldsArray[$type])) {
$this->type = $type;
} else {
throw new InvalidArgumentException("Invalid type '$type'");
}
}
return $this->type;
}
/**
* Get Field type.
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* Set Field properties.
*
* @param array $properties
*
* @return self
*/
public function setProperties($properties = [])
{
if (is_array($properties)) {
foreach (array_keys($properties) as $propkey) {
if (!(isset($this->fieldsArray[$this->type]['properties'][$propkey]))) {
throw new InvalidArgumentException("Invalid property '$propkey'");
}
}
$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
*/
public function setOptions($options = [])
{
if (is_array($options)) {
foreach (array_keys($options) as $optionkey) {
if (!(isset($this->fieldsArray[$this->type]['options'][$optionkey])) && substr($optionkey, 0, 1) !== '\\') {
throw new InvalidArgumentException("Invalid option '$optionkey', possible values are " . implode(', ', $this->fieldsArray[$this->type]['options']));
}
}
$this->options = array_merge($this->options, $options);
}
return $this->options;
}
/**
* Get Field properties.
*
* @return array
*/
public function getOptions()
{
return $this->options;
}
/**
* Set Field text.
*
* @param null|string|TextRun $text
*
* @return null|string|TextRun
*/
public function setText($text = null)
{
if (isset($text)) {
if (is_string($text) || $text instanceof TextRun) {
$this->text = $text;
} else {
throw new InvalidArgumentException('Invalid text');
}
}
return $this->text;
}
/**
* Get Field text.
*
* @return string|TextRun
*/
public function getText()
{
return $this->text;
}
}
+118
View File
@@ -0,0 +1,118 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
/**
* Footer element.
*/
class Footer extends AbstractContainer
{
/**
* Header/footer types constants.
*
* @var string
*
* @see http://www.datypic.com/sc/ooxml/t-w_ST_HdrFtr.html Header or Footer Type
*/
const AUTO = 'default'; // default and odd pages
const FIRST = 'first';
const EVEN = 'even';
/**
* @var string Container type
*/
protected $container = 'Footer';
/**
* Header type.
*
* @var string
*/
protected $type = self::AUTO;
/**
* Create new instance.
*
* @param int $sectionId
* @param int $containerId
* @param string $type
*/
public function __construct($sectionId, $containerId = 1, $type = self::AUTO)
{
$this->sectionId = $sectionId;
$this->setType($type);
$this->setDocPart($this->container, ($sectionId - 1) * 3 + $containerId);
}
/**
* Set type.
*
* @since 0.10.0
*
* @param string $value
*/
public function setType($value = self::AUTO): void
{
if (!in_array($value, [self::AUTO, self::FIRST, self::EVEN])) {
$value = self::AUTO;
}
$this->type = $value;
}
/**
* Get type.
*
* @return string
*
* @since 0.10.0
*/
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;
}
}
@@ -0,0 +1,63 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Style\Paragraph;
class Footnote extends AbstractContainer
{
/**
* @var string Container type
*/
protected $container = 'Footnote';
/**
* Paragraph style.
*
* @var null|\PhpOffice\PhpWord\Style\Paragraph|string
*/
protected $paragraphStyle;
/**
* Is part of collection.
*
* @var bool
*/
protected $collectionRelation = true;
/**
* Create new instance.
*
* @param array|\PhpOffice\PhpWord\Style\Paragraph|string $paragraphStyle
*/
public function __construct($paragraphStyle = null)
{
$this->paragraphStyle = $this->setNewStyle(new Paragraph(), $paragraphStyle);
$this->setDocPart($this->container);
}
/**
* Get paragraph style.
*
* @return null|\PhpOffice\PhpWord\Style\Paragraph|string
*/
public function getParagraphStyle()
{
return $this->paragraphStyle;
}
}
@@ -0,0 +1,200 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
/**
* Form field element.
*
* @since 0.12.0
* @see http://www.datypic.com/sc/ooxml/t-w_CT_FFData.html
*/
class FormField extends Text
{
/**
* Form field type: textinput|checkbox|dropdown.
*
* @var string
*/
private $type = 'textinput';
/**
* Form field name.
*
* @var ?string
*/
private $name;
/**
* Default value.
*
* - TextInput: string
* - CheckBox: bool
* - DropDown: int Index of entries (zero based)
*
* @var bool|int|string
*/
private $default;
/**
* Value.
*
* @var null|bool|int|string
*/
private $value;
/**
* Dropdown entries.
*
* @var array
*/
private $entries = [];
/**
* Create new instance.
*
* @param string $type
* @param mixed $fontStyle
* @param mixed $paragraphStyle
*/
public function __construct($type, $fontStyle = null, $paragraphStyle = null)
{
parent::__construct(null, $fontStyle, $paragraphStyle);
$this->setType($type);
}
/**
* Get type.
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* Set type.
*
* @param string $value
*
* @return self
*/
public function setType($value)
{
$enum = ['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 $value
*
* @return self
*/
public function setName($value)
{
$this->name = $value;
return $this;
}
/**
* Get default.
*
* @return bool|int|string
*/
public function getDefault()
{
return $this->default;
}
/**
* Set default.
*
* @param bool|int|string $value
*
* @return self
*/
public function setDefault($value)
{
$this->default = $value;
return $this;
}
/**
* Get value.
*
* @return null|bool|int|string
*/
public function getValue()
{
return $this->value;
}
/**
* Set value.
*
* @param null|bool|int|string $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;
}
}
@@ -0,0 +1,53 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
declare(strict_types=1);
namespace PhpOffice\PhpWord\Element;
use PhpOffice\Math\Math;
/**
* Formula element.
*/
class Formula extends AbstractElement
{
/**
* @var Math
*/
protected $math;
/**
* Create a new Formula Element.
*/
public function __construct(Math $math)
{
$this->setMath($math);
}
public function setMath(Math $math): self
{
$this->math = $math;
return $this;
}
public function getMath(): Math
{
return $this->math;
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
/**
* Header element.
*/
class Header extends Footer
{
/**
* @var string Container type
*/
protected $container = 'Header';
/**
* Add a Watermark Element.
*
* @param string $src
* @param mixed $style
*
* @return Image
*/
public function addWatermark($src, $style = null)
{
return $this->addImage($src, $style, true);
}
}
+600
View File
@@ -0,0 +1,600 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Exception\CreateTemporaryFileException;
use PhpOffice\PhpWord\Exception\InvalidImageException;
use PhpOffice\PhpWord\Exception\UnsupportedImageTypeException;
use PhpOffice\PhpWord\Settings;
use PhpOffice\PhpWord\Shared\ZipArchive;
use PhpOffice\PhpWord\Style\Image as ImageStyle;
/**
* Image element.
*/
class Image extends AbstractElement
{
/**
* Image source type constants.
*/
const SOURCE_LOCAL = 'local'; // Local images
const SOURCE_GD = 'gd'; // Generated using GD
const SOURCE_ARCHIVE = 'archive'; // Image in archives zip://$archive#$image
const SOURCE_STRING = 'string'; // Image from string
/**
* Image source.
*
* @var string
*/
private $source;
/**
* Source type: local|gd|archive.
*
* @var string
*/
private $sourceType;
/**
* Image style.
*
* @var ?ImageStyle
*/
private $style;
/**
* Is watermark.
*
* @var bool
*/
private $watermark;
/**
* Name of image.
*
* @var string
*/
private $name;
/**
* Image type.
*
* @var string
*/
private $imageType;
/**
* Image create function.
*
* @var string
*/
private $imageCreateFunc;
/**
* Image function.
*
* @var null|callable(resource): void
*/
private $imageFunc;
/**
* Image extension.
*
* @var string
*/
private $imageExtension;
/**
* Image quality.
*
* Functions imagepng() and imagejpeg() have an optional parameter for
* quality.
*
* @var null|int
*/
private $imageQuality;
/**
* Is memory image.
*
* @var bool
*/
private $memoryImage;
/**
* Image target file name.
*
* @var string
*/
private $target;
/**
* Image media index.
*
* @var int
*/
private $mediaIndex;
/**
* Has media relation flag; true for Link, Image, and Object.
*
* @var bool
*/
protected $mediaRelation = true;
/**
* Create new image element.
*
* @param string $source
* @param mixed $style
* @param bool $watermark
* @param string $name
*/
public function __construct($source, $style = null, $watermark = false, $name = null)
{
$this->source = $source;
$this->style = $this->setNewStyle(new ImageStyle(), $style, true);
$this->setIsWatermark($watermark);
$this->setName($name);
$this->checkImage();
}
/**
* Get Image style.
*
* @return ?ImageStyle
*/
public function getStyle()
{
return $this->style;
}
/**
* Get image source.
*
* @return string
*/
public function getSource()
{
return $this->source;
}
/**
* Get image source type.
*
* @return string
*/
public function getSourceType()
{
return $this->sourceType;
}
/**
* Sets the image name.
*
* @param string $value
*/
public function setName($value): void
{
$this->name = $value;
}
/**
* Get image name.
*
* @return null|string
*/
public function getName()
{
return $this->name;
}
/**
* Get image media ID.
*
* @return string
*/
public function getMediaId()
{
return md5($this->source);
}
/**
* Get is watermark.
*
* @return bool
*/
public function isWatermark()
{
return $this->watermark;
}
/**
* Set is watermark.
*
* @param bool $value
*/
public function setIsWatermark($value): void
{
$this->watermark = $value;
}
/**
* Get image type.
*
* @return string
*/
public function getImageType()
{
return $this->imageType;
}
/**
* Get image create function.
*
* @return string
*/
public function getImageCreateFunction()
{
return $this->imageCreateFunc;
}
/**
* Get image function.
*
* @return null|callable(resource): void
*/
public function getImageFunction(): ?callable
{
return $this->imageFunc;
}
/**
* Get image quality.
*/
public function getImageQuality(): ?int
{
return $this->imageQuality;
}
/**
* Get image extension.
*
* @return string
*/
public function getImageExtension()
{
return $this->imageExtension;
}
/**
* Get is memory image.
*
* @return bool
*/
public function isMemImage()
{
return $this->memoryImage;
}
/**
* Get target file name.
*
* @return string
*/
public function getTarget()
{
return $this->target;
}
/**
* Set target file name.
*
* @param string $value
*/
public function setTarget($value): void
{
$this->target = $value;
}
/**
* Get media index.
*
* @return int
*/
public function getMediaIndex()
{
return $this->mediaIndex;
}
/**
* Set media index.
*
* @param int $value
*/
public function setMediaIndex($value): void
{
$this->mediaIndex = $value;
}
/**
* Get image string.
*/
public function getImageString(): ?string
{
$source = $this->source;
$actualSource = null;
$imageBinary = 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);
[$zipFilename, $imageFilename] = explode('#', $source);
$zip = new ZipArchive();
if ($zip->open($zipFilename) !== false) {
if ($zip->locateName($imageFilename) !== false) {
$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);
if ($this->imageType === 'image/png') {
// PNG images need to preserve alpha channel information
imagesavealpha($imageResource, true);
}
ob_start();
$callback = $this->imageFunc;
$callback($imageResource);
$imageBinary = ob_get_contents();
ob_end_clean();
} elseif ($this->sourceType == self::SOURCE_STRING) {
$imageBinary = $this->source;
} else {
$fileHandle = fopen($actualSource, 'rb', false);
$fileSize = filesize($actualSource);
if ($fileHandle !== false && $fileSize > 0) {
$imageBinary = fread($fileHandle, $fileSize);
fclose($fileHandle);
}
}
// Delete temporary file if necessary
if ($isTemp === true) {
@unlink($actualSource);
}
return $imageBinary;
}
/**
* Get image string data.
*
* @param bool $base64
*
* @return null|string
*
* @since 0.11.0
*/
public function getImageStringData($base64 = false)
{
$imageBinary = $this->getImageString();
if ($imageBinary === null) {
return null;
}
if ($base64) {
return base64_encode($imageBinary);
}
return bin2hex($imageBinary);
}
/**
* Check memory image, supported type, image functions, and proportional width/height.
*/
private function checkImage(): void
{
$this->setSourceType();
// Check image data
if ($this->sourceType == self::SOURCE_ARCHIVE) {
$imageData = $this->getArchiveImageSize($this->source);
} elseif ($this->sourceType == self::SOURCE_STRING) {
$imageData = @getimagesizefromstring($this->source);
} else {
$imageData = @getimagesize($this->source);
}
if (!is_array($imageData)) {
throw new InvalidImageException(sprintf('Invalid image: %s', $this->source));
}
[$actualWidth, $actualHeight, $imageType] = $imageData;
// Check image type support
$supportedTypes = [IMAGETYPE_JPEG, IMAGETYPE_GIF, IMAGETYPE_PNG];
if ($this->sourceType != self::SOURCE_GD && $this->sourceType != self::SOURCE_STRING) {
$supportedTypes = array_merge($supportedTypes, [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.
*/
private function setSourceType(): void
{
if (stripos(strrev($this->source), strrev('.php')) === 0) {
$this->memoryImage = true;
$this->sourceType = self::SOURCE_GD;
} elseif (strpos($this->source, 'zip://') !== false) {
$this->memoryImage = false;
$this->sourceType = self::SOURCE_ARCHIVE;
} elseif (filter_var($this->source, FILTER_VALIDATE_URL) !== false) {
$this->memoryImage = true;
if (strpos($this->source, 'https') === 0) {
$fileContent = file_get_contents($this->source);
$this->source = $fileContent;
$this->sourceType = self::SOURCE_STRING;
} else {
$this->sourceType = self::SOURCE_GD;
}
} elseif ((strpos($this->source, chr(0)) === false) && @file_exists($this->source)) {
$this->memoryImage = false;
$this->sourceType = self::SOURCE_LOCAL;
} else {
$this->memoryImage = true;
$this->sourceType = self::SOURCE_STRING;
}
}
/**
* Get image size from archive.
*
* @since 0.12.0 Throws CreateTemporaryFileException.
*
* @param string $source
*
* @return null|array
*/
private function getArchiveImageSize($source)
{
$imageData = null;
$source = substr($source, 6);
[$zipFilename, $imageFilename] = explode('#', $source);
$tempFilename = tempnam(Settings::getTempDir(), 'PHPWordImage');
if (false === $tempFilename) {
throw new CreateTemporaryFileException(); // @codeCoverageIgnore
}
$zip = new ZipArchive();
if ($zip->open($zipFilename) !== false) {
if ($zip->locateName($imageFilename) !== false) {
$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.
*/
private function setFunctions(): void
{
switch ($this->imageType) {
case 'image/png':
$this->imageCreateFunc = $this->sourceType == self::SOURCE_STRING ? 'imagecreatefromstring' : 'imagecreatefrompng';
$this->imageFunc = function ($resource): void {
imagepng($resource, null, $this->imageQuality);
};
$this->imageExtension = 'png';
$this->imageQuality = -1;
break;
case 'image/gif':
$this->imageCreateFunc = $this->sourceType == self::SOURCE_STRING ? 'imagecreatefromstring' : 'imagecreatefromgif';
$this->imageFunc = function ($resource): void {
imagegif($resource);
};
$this->imageExtension = 'gif';
$this->imageQuality = null;
break;
case 'image/jpeg':
case 'image/jpg':
$this->imageCreateFunc = $this->sourceType == self::SOURCE_STRING ? 'imagecreatefromstring' : 'imagecreatefromjpeg';
$this->imageFunc = function ($resource): void {
imagejpeg($resource, null, $this->imageQuality);
};
$this->imageExtension = 'jpg';
$this->imageQuality = 100;
break;
case 'image/bmp':
case 'image/x-ms-bmp':
$this->imageType = 'image/bmp';
$this->imageFunc = null;
$this->imageExtension = 'bmp';
$this->imageQuality = null;
break;
case 'image/tiff':
$this->imageType = 'image/tiff';
$this->imageFunc = null;
$this->imageExtension = 'tif';
$this->imageQuality = null;
break;
}
}
/**
* Set proportional width/height if one dimension not available.
*
* @param int $actualWidth
* @param int $actualHeight
*/
private function setProportionalSize($actualWidth, $actualHeight): void
{
$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));
}
}
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Style\Line as LineStyle;
/**
* Line element.
*/
class Line extends AbstractElement
{
/**
* Line style.
*
* @var ?\PhpOffice\PhpWord\Style\Line
*/
private $style;
/**
* Create new line element.
*
* @param mixed $style
*/
public function __construct($style = null)
{
$this->style = $this->setNewStyle(new LineStyle(), $style);
}
/**
* Get line style.
*
* @return ?\PhpOffice\PhpWord\Style\Line
*/
public function getStyle()
{
return $this->style;
}
}
+138
View File
@@ -0,0 +1,138 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Shared\Text as SharedText;
use PhpOffice\PhpWord\Style\Font;
use PhpOffice\PhpWord\Style\Paragraph;
/**
* Link element.
*/
class Link extends AbstractElement
{
/**
* Link source.
*
* @var string
*/
private $source;
/**
* Link text.
*
* @var string
*/
private $text;
/**
* Font style.
*
* @var null|\PhpOffice\PhpWord\Style\Font|string
*/
private $fontStyle;
/**
* Paragraph style.
*
* @var null|\PhpOffice\PhpWord\Style\Paragraph|string
*/
private $paragraphStyle;
/**
* Has media relation flag; true for Link, Image, and Object.
*
* @var bool
*/
protected $mediaRelation = true;
/**
* Has internal flag - anchor to internal bookmark.
*
* @var bool
*/
protected $internal = false;
/**
* Create a new Link Element.
*
* @param string $source
* @param string $text
* @param mixed $fontStyle
* @param mixed $paragraphStyle
* @param bool $internal
*/
public function __construct($source, $text = null, $fontStyle = null, $paragraphStyle = null, $internal = false)
{
$this->source = SharedText::toUTF8($source);
$this->text = null === $text ? $this->source : SharedText::toUTF8($text);
$this->fontStyle = $this->setNewStyle(new Font('text'), $fontStyle);
$this->paragraphStyle = $this->setNewStyle(new Paragraph(), $paragraphStyle);
$this->internal = $internal;
}
/**
* Get link source.
*
* @return string
*/
public function getSource()
{
return $this->source;
}
/**
* Get link text.
*
* @return string
*/
public function getText()
{
return $this->text;
}
/**
* Get Text style.
*
* @return null|\PhpOffice\PhpWord\Style\Font|string
*/
public function getFontStyle()
{
return $this->fontStyle;
}
/**
* Get Paragraph style.
*
* @return null|\PhpOffice\PhpWord\Style\Paragraph|string
*/
public function getParagraphStyle()
{
return $this->paragraphStyle;
}
/**
* is internal.
*
* @return bool
*/
public function isInternal()
{
return $this->internal;
}
}
@@ -0,0 +1,112 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Shared\Text as SharedText;
use PhpOffice\PhpWord\Style\ListItem as ListItemStyle;
/**
* List item element.
*/
class ListItem extends AbstractElement
{
/**
* Element style.
*
* @var ?\PhpOffice\PhpWord\Style\ListItem
*/
private $style;
/**
* Text object.
*
* @var \PhpOffice\PhpWord\Element\Text
*/
private $textObject;
/**
* Depth.
*
* @var int
*/
private $depth;
/**
* Create a new ListItem.
*
* @param string $text
* @param int $depth
* @param mixed $fontStyle
* @param null|array|string $listStyle
* @param mixed $paragraphStyle
*/
public function __construct($text, $depth = 0, $fontStyle = null, $listStyle = null, $paragraphStyle = null)
{
$this->textObject = new Text(SharedText::toUTF8($text), $fontStyle, $paragraphStyle);
$this->depth = $depth;
// Version >= 0.10.0 will pass numbering style name. Older version will use old method
if (null !== $listStyle && is_string($listStyle)) {
$this->style = new ListItemStyle($listStyle); // @codeCoverageIgnore
} else {
$this->style = $this->setNewStyle(new ListItemStyle(), $listStyle, true);
}
}
/**
* Get style.
*
* @return ?\PhpOffice\PhpWord\Style\ListItem
*/
public function getStyle()
{
return $this->style;
}
/**
* Get Text object.
*
* @return \PhpOffice\PhpWord\Element\Text
*/
public function getTextObject()
{
return $this->textObject;
}
/**
* 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();
}
}
@@ -0,0 +1,85 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Style\ListItem as ListItemStyle;
/**
* List item element.
*/
class ListItemRun extends TextRun
{
/**
* @var string Container type
*/
protected $container = 'ListItemRun';
/**
* ListItem Style.
*
* @var ?\PhpOffice\PhpWord\Style\ListItem
*/
private $style;
/**
* ListItem Depth.
*
* @var int
*/
private $depth;
/**
* Create a new ListItem.
*
* @param int $depth
* @param null|array|string $listStyle
* @param mixed $paragraphStyle
*/
public function __construct($depth = 0, $listStyle = null, $paragraphStyle = null)
{
$this->depth = $depth;
// Version >= 0.10.0 will pass numbering style name. Older version will use old method
if (null !== $listStyle && is_string($listStyle)) {
$this->style = new ListItemStyle($listStyle);
} else {
$this->style = $this->setNewStyle(new ListItemStyle(), $listStyle, true);
}
parent::__construct($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;
}
}
@@ -0,0 +1,139 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Exception\InvalidObjectException;
use PhpOffice\PhpWord\Style\Image as ImageStyle;
/**
* OLEObject element.
*/
class OLEObject extends AbstractElement
{
/**
* Ole-Object Src.
*
* @var string
*/
private $source;
/**
* Image Style.
*
* @var ?\PhpOffice\PhpWord\Style\Image
*/
private $style;
/**
* Icon.
*
* @var string
*/
private $icon;
/**
* Image Relation ID.
*
* @var int
*/
private $imageRelationId;
/**
* Has media relation flag; true for Link, Image, and Object.
*
* @var bool
*/
protected $mediaRelation = true;
/**
* Create a new Ole-Object Element.
*
* @param string $source
* @param mixed $style
*/
public function __construct($source, $style = null)
{
$supportedTypes = ['xls', 'doc', 'ppt', 'xlsx', 'docx', 'pptx'];
$pathInfo = pathinfo($source);
if (file_exists($source) && in_array($pathInfo['extension'], $supportedTypes)) {
$ext = $pathInfo['extension'];
if (strlen($ext) == 4 && strtolower(substr($ext, -1)) == 'x') {
$ext = substr($ext, 0, -1);
}
$this->source = $source;
$this->style = $this->setNewStyle(new ImageStyle(), $style, true);
$this->icon = realpath(__DIR__ . "/../resources/{$ext}.png");
return;
}
throw new InvalidObjectException();
}
/**
* Get object source.
*
* @return string
*/
public function getSource()
{
return $this->source;
}
/**
* 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
*/
public function getImageRelationId()
{
return $this->imageRelationId;
}
/**
* Set Image Relation ID.
*
* @param int $rId
*/
public function setImageRelationId($rId): void
{
$this->imageRelationId = $rId;
}
}
@@ -0,0 +1,31 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
/**
* Page break element.
*/
class PageBreak extends AbstractElement
{
/**
* Create new page break.
*/
public function __construct()
{
}
}
@@ -0,0 +1,98 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Shared\Text as SharedText;
use PhpOffice\PhpWord\Style\Font;
use PhpOffice\PhpWord\Style\Paragraph;
/**
* Preserve text/field element.
*/
class PreserveText extends AbstractElement
{
/**
* Text content.
*
* @var null|array|string
*/
private $text;
/**
* Text style.
*
* @var null|\PhpOffice\PhpWord\Style\Font|string
*/
private $fontStyle;
/**
* Paragraph style.
*
* @var null|\PhpOffice\PhpWord\Style\Paragraph|string
*/
private $paragraphStyle;
/**
* Create a new Preserve Text Element.
*
* @param string $text
* @param mixed $fontStyle
* @param mixed $paragraphStyle
*/
public function __construct($text = null, $fontStyle = null, $paragraphStyle = null)
{
$this->fontStyle = $this->setNewStyle(new Font('text'), $fontStyle);
$this->paragraphStyle = $this->setNewStyle(new Paragraph(), $paragraphStyle);
$this->text = SharedText::toUTF8($text);
$matches = preg_split('/({.*?})/', $this->text ?? '', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
if (isset($matches[0])) {
$this->text = $matches;
}
}
/**
* Get Text style.
*
* @return null|\PhpOffice\PhpWord\Style\Font|string
*/
public function getFontStyle()
{
return $this->fontStyle;
}
/**
* Get Paragraph style.
*
* @return null|\PhpOffice\PhpWord\Style\Paragraph|string
*/
public function getParagraphStyle()
{
return $this->paragraphStyle;
}
/**
* Get Text content.
*
* @return null|array|string
*/
public function getText()
{
return $this->text;
}
}
+108
View File
@@ -0,0 +1,108 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Style\Row as RowStyle;
/**
* Table row element.
*
* @since 0.8.0
*/
class Row extends AbstractElement
{
/**
* Row height.
*
* @var ?int
*/
private $height;
/**
* Row style.
*
* @var ?\PhpOffice\PhpWord\Style\Row
*/
private $style;
/**
* Row cells.
*
* @var \PhpOffice\PhpWord\Element\Cell[]
*/
private $cells = [];
/**
* Create a new table row.
*
* @param int $height
* @param mixed $style
*/
public function __construct($height = null, $style = null)
{
$this->height = $height;
$this->style = $this->setNewStyle(new RowStyle(), $style, true);
}
/**
* Add a cell.
*
* @param int $width
* @param mixed $style
*
* @return \PhpOffice\PhpWord\Element\Cell
*/
public function addCell($width = null, $style = null)
{
$cell = new Cell($width, $style);
$cell->setParentContainer($this);
$this->cells[] = $cell;
return $cell;
}
/**
* Get all cells.
*
* @return \PhpOffice\PhpWord\Element\Cell[]
*/
public function getCells()
{
return $this->cells;
}
/**
* Get row style.
*
* @return ?\PhpOffice\PhpWord\Style\Row
*/
public function getStyle()
{
return $this->style;
}
/**
* Get row height.
*
* @return ?int
*/
public function getHeight()
{
return $this->height;
}
}
+195
View File
@@ -0,0 +1,195 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
/**
* Structured document tag (SDT) element.
*
* @since 0.12.0
*/
class SDT extends Text
{
/**
* Form field type: comboBox|dropDownList|date.
*
* @var string
*/
private $type;
/**
* Value.
*
* @var null|bool|int|string
*/
private $value;
/**
* CheckBox/DropDown list entries.
*
* @var array
*/
private $listItems = [];
/**
* Alias.
*
* @var string
*/
private $alias;
/**
* Tag.
*
* @var string
*/
private $tag;
/**
* Create new instance.
*
* @param string $type
* @param mixed $fontStyle
* @param mixed $paragraphStyle
*/
public function __construct($type, $fontStyle = null, $paragraphStyle = null)
{
parent::__construct(null, $fontStyle, $paragraphStyle);
$this->setType($type);
}
/**
* Get type.
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* Set type.
*
* @param string $value
*
* @return self
*/
public function setType($value)
{
$enum = ['plainText', 'comboBox', 'dropDownList', 'date'];
$this->type = $this->setEnumVal($value, $enum, 'comboBox');
return $this;
}
/**
* Get value.
*
* @return null|bool|int|string
*/
public function getValue()
{
return $this->value;
}
/**
* Set value.
*
* @param null|bool|int|string $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;
}
/**
* Get tag.
*
* @return string
*/
public function getTag()
{
return $this->tag;
}
/**
* Set tag.
*
* @param string $tag
*
* @return self
*/
public function setTag($tag)
{
$this->tag = $tag;
return $this;
}
/**
* Get alias.
*
* @return string
*/
public function getAlias()
{
return $this->alias;
}
/**
* Set alias.
*
* @param string $alias
*
* @return self
*/
public function setAlias($alias)
{
$this->alias = $alias;
return $this;
}
}
+217
View File
@@ -0,0 +1,217 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use Exception;
use PhpOffice\PhpWord\ComplexType\FootnoteProperties;
use PhpOffice\PhpWord\Style\Section as SectionStyle;
class Section extends AbstractContainer
{
/**
* @var string Container type
*/
protected $container = 'Section';
/**
* Section style.
*
* @var ?\PhpOffice\PhpWord\Style\Section
*/
private $style;
/**
* Section headers, indexed from 1, not zero.
*
* @var Header[]
*/
private $headers = [];
/**
* Section footers, indexed from 1, not zero.
*
* @var Footer[]
*/
private $footers = [];
/**
* The properties for the footnote of this section.
*
* @var FootnoteProperties
*/
private $footnoteProperties;
/**
* Create new instance.
*
* @param int $sectionCount
* @param null|array|\PhpOffice\PhpWord\Style|string $style
*/
public function __construct($sectionCount, $style = null)
{
$this->sectionId = $sectionCount;
$this->setDocPart($this->container, $this->sectionId);
if (null === $style) {
$style = new SectionStyle();
}
$this->style = $this->setNewStyle(new SectionStyle(), $style);
}
/**
* Set section style.
*
* @param array $style
*/
public function setStyle($style = null): void
{
if (null !== $style && is_array($style)) {
$this->style->setStyleByArray($style);
}
}
/**
* Get section style.
*
* @return ?\PhpOffice\PhpWord\Style\Section
*/
public function getStyle()
{
return $this->style;
}
/**
* Add header.
*
* @since 0.10.0
*
* @param string $type
*
* @return Header
*/
public function addHeader($type = Header::AUTO)
{
return $this->addHeaderFooter($type, true);
}
/**
* Add footer.
*
* @since 0.10.0
*
* @param string $type
*
* @return Footer
*/
public function addFooter($type = Header::AUTO)
{
return $this->addHeaderFooter($type, false);
}
/**
* Get header elements.
*
* @return Header[]
*/
public function getHeaders()
{
return $this->headers;
}
/**
* Get footer elements.
*
* @return Footer[]
*/
public function getFooters()
{
return $this->footers;
}
/**
* Get the footnote properties.
*
* @return FootnoteProperties
*/
public function getFootnoteProperties()
{
return $this->footnoteProperties;
}
/**
* Set the footnote properties.
*/
public function setFootnoteProperties(?FootnoteProperties $footnoteProperties = null): void
{
$this->footnoteProperties = $footnoteProperties;
}
/**
* Is there a header for this section that is for the first page only?
*
* If any of the Header instances have a type of Header::FIRST then this method returns true.
* False otherwise.
*
* @return bool
*/
public function hasDifferentFirstPage()
{
foreach ($this->headers as $header) {
if ($header->getType() == Header::FIRST) {
return true;
}
}
foreach ($this->footers as $footer) {
if ($footer->getType() == Header::FIRST) {
return true;
}
}
return false;
}
/**
* Add header/footer.
*
* @since 0.10.0
*
* @param string $type
* @param bool $header
*
* @return Footer|Header
*/
private function addHeaderFooter($type = Header::AUTO, $header = true)
{
$containerClass = substr(static::class, 0, strrpos(static::class, '\\')) . '\\' .
($header ? 'Header' : 'Footer');
$collectionArray = $header ? 'headers' : 'footers';
$collection = &$this->$collectionArray;
if (in_array($type, [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;
}
throw new Exception('Invalid header/footer type.');
}
}
+89
View File
@@ -0,0 +1,89 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Style\Shape as ShapeStyle;
/**
* Shape element.
*
* @since 0.12.0
*/
class Shape extends AbstractElement
{
/**
* Shape type arc|curve|line|polyline|rect|oval.
*
* @var string
*/
private $type;
/**
* Shape style.
*
* @var ?\PhpOffice\PhpWord\Style\Shape
*/
private $style;
/**
* Create new instance.
*
* @param string $type
* @param mixed $style
*/
public function __construct($type, $style = null)
{
$this->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 = ['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;
}
}
+169
View File
@@ -0,0 +1,169 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Style\Font;
use PhpOffice\PhpWord\Style\TOC as TOCStyle;
/**
* Table of contents.
*/
class TOC extends AbstractElement
{
/**
* TOC style.
*
* @var \PhpOffice\PhpWord\Style\TOC
*/
private $tocStyle;
/**
* Font style.
*
* @var \PhpOffice\PhpWord\Style\Font|string
*/
private $fontStyle;
/**
* Min title depth to show.
*
* @var int
*/
private $minDepth = 1;
/**
* Max title depth to show.
*
* @var int
*/
private $maxDepth = 9;
/**
* Create a new Table-of-Contents Element.
*
* @param mixed $fontStyle
* @param array $tocStyle
* @param int $minDepth
* @param int $maxDepth
*/
public function __construct($fontStyle = null, $tocStyle = null, $minDepth = 1, $maxDepth = 9)
{
$this->tocStyle = new TOCStyle();
if (null !== $tocStyle && is_array($tocStyle)) {
$this->tocStyle->setStyleByArray($tocStyle);
}
if (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 [];
}
$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|string
*/
public function getStyleFont()
{
return $this->fontStyle;
}
/**
* Set max depth.
*
* @param int $value
*/
public function setMaxDepth($value): void
{
$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): void
{
$this->minDepth = $value;
}
/**
* Get Min Depth.
*
* @return int Min depth of titles
*/
public function getMinDepth()
{
return $this->minDepth;
}
}
+176
View File
@@ -0,0 +1,176 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Style\Table as TableStyle;
/**
* Table element.
*/
class Table extends AbstractElement
{
/**
* Table style.
*
* @var ?\PhpOffice\PhpWord\Style\Table
*/
private $style;
/**
* Table rows.
*
* @var \PhpOffice\PhpWord\Element\Row[]
*/
private $rows = [];
/**
* Table width.
*
* @var ?int
*/
private $width;
/**
* Create a new table.
*
* @param mixed $style
*/
public function __construct($style = null)
{
$this->style = $this->setNewStyle(new TableStyle(), $style);
}
/**
* Add a row.
*
* @param int $height
* @param mixed $style
*
* @return \PhpOffice\PhpWord\Element\Row
*/
public function addRow($height = null, $style = null)
{
$row = new Row($height, $style);
$row->setParentContainer($this);
$this->rows[] = $row;
return $row;
}
/**
* Add a cell.
*
* @param int $width
* @param mixed $style
*
* @return \PhpOffice\PhpWord\Element\Cell
*/
public function addCell($width = null, $style = null)
{
$index = count($this->rows) - 1;
$row = $this->rows[$index];
$cell = $row->addCell($width, $style);
return $cell;
}
/**
* Get all rows.
*
* @return \PhpOffice\PhpWord\Element\Row[]
*/
public function getRows()
{
return $this->rows;
}
/**
* Get table style.
*
* @return null|\PhpOffice\PhpWord\Style\Table|string
*/
public function getStyle()
{
return $this->style;
}
/**
* Get table width.
*
* @return ?int
*/
public function getWidth()
{
return $this->width;
}
/**
* Set table width.
*
* @param int $width
*/
public function setWidth($width): void
{
$this->width = $width;
}
/**
* Get column count.
*
* @return int
*/
public function countColumns()
{
$columnCount = 0;
$rowCount = count($this->rows);
for ($i = 0; $i < $rowCount; ++$i) {
/** @var \PhpOffice\PhpWord\Element\Row $row Type hint */
$row = $this->rows[$i];
$cellCount = count($row->getCells());
if ($columnCount < $cellCount) {
$columnCount = $cellCount;
}
}
return $columnCount;
}
/**
* The first declared cell width for each column.
*
* @return int[]
*/
public function findFirstDefinedCellWidths()
{
$cellWidths = [];
foreach ($this->rows as $row) {
$cells = $row->getCells();
if (count($cells) <= count($cellWidths)) {
continue;
}
$cellWidths = [];
foreach ($cells as $cell) {
$cellWidths[] = $cell->getWidth();
}
}
return $cellWidths;
}
}
+156
View File
@@ -0,0 +1,156 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Shared\Text as SharedText;
use PhpOffice\PhpWord\Style\Font;
use PhpOffice\PhpWord\Style\Paragraph;
/**
* Text element.
*/
class Text extends AbstractElement
{
/**
* Text content.
*
* @var ?string
*/
protected $text;
/**
* Text style.
*
* @var \PhpOffice\PhpWord\Style\Font|string
*/
protected $fontStyle;
/**
* Paragraph style.
*
* @var \PhpOffice\PhpWord\Style\Paragraph|string
*/
protected $paragraphStyle;
/**
* Create a new Text Element.
*
* @param string $text
* @param mixed $fontStyle
* @param mixed $paragraphStyle
*/
public function __construct($text = null, $fontStyle = null, $paragraphStyle = null)
{
$this->setText($text);
$paragraphStyle = $this->setParagraphStyle($paragraphStyle);
$this->setFontStyle($fontStyle, $paragraphStyle);
}
/**
* Set Text style.
*
* @param array|\PhpOffice\PhpWord\Style\Font|string $style
* @param array|\PhpOffice\PhpWord\Style\Paragraph|string $paragraphStyle
*
* @return \PhpOffice\PhpWord\Style\Font|string
*/
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->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 \PhpOffice\PhpWord\Style\Font|string
*/
public function getFontStyle()
{
return $this->fontStyle;
}
/**
* Set Paragraph style.
*
* @param array|\PhpOffice\PhpWord\Style\Paragraph|string $style
*
* @return \PhpOffice\PhpWord\Style\Paragraph|string
*/
public function setParagraphStyle($style = null)
{
if (is_array($style)) {
$this->paragraphStyle = new Paragraph();
$this->paragraphStyle->setStyleByArray($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 \PhpOffice\PhpWord\Style\Paragraph|string
*/
public function getParagraphStyle()
{
return $this->paragraphStyle;
}
/**
* Set text content.
*
* @param string $text
*
* @return self
*/
public function setText($text)
{
$this->text = SharedText::toUTF8($text);
return $this;
}
/**
* Get Text content.
*
* @return ?string
*/
public function getText()
{
return $this->text;
}
}
@@ -0,0 +1,60 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Style\TextBox as TextBoxStyle;
/**
* TextBox element.
*
* @since 0.11.0
*/
class TextBox extends AbstractContainer
{
/**
* @var string Container type
*/
protected $container = 'TextBox';
/**
* TextBox style.
*
* @var ?\PhpOffice\PhpWord\Style\TextBox
*/
private $style;
/**
* Create a new textbox.
*
* @param mixed $style
*/
public function __construct($style = null)
{
$this->style = $this->setNewStyle(new TextBoxStyle(), $style);
}
/**
* Get textbox style.
*
* @return ?\PhpOffice\PhpWord\Style\TextBox
*/
public function getStyle()
{
return $this->style;
}
}
@@ -0,0 +1,132 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Style\Font;
use PhpOffice\PhpWord\Style\Paragraph;
/**
* Text break element.
*/
class TextBreak extends AbstractElement
{
/**
* Paragraph style.
*
* @var null|\PhpOffice\PhpWord\Style\Paragraph|string
*/
private $paragraphStyle;
/**
* Text style.
*
* @var null|\PhpOffice\PhpWord\Style\Font|string
*/
private $fontStyle;
/**
* Create a new TextBreak Element.
*
* @param mixed $fontStyle
* @param mixed $paragraphStyle
*/
public function __construct($fontStyle = null, $paragraphStyle = null)
{
if (null !== $paragraphStyle) {
$paragraphStyle = $this->setParagraphStyle($paragraphStyle);
}
if (null !== $fontStyle) {
$this->setFontStyle($fontStyle, $paragraphStyle);
}
}
/**
* Set Text style.
*
* @param mixed $style
* @param mixed $paragraphStyle
*
* @return \PhpOffice\PhpWord\Style\Font|string
*/
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->setStyleByArray($style);
} else {
$this->fontStyle = $style;
$this->setParagraphStyle($paragraphStyle);
}
return $this->fontStyle;
}
/**
* Get Text style.
*
* @return null|\PhpOffice\PhpWord\Style\Font|string
*/
public function getFontStyle()
{
return $this->fontStyle;
}
/**
* Set Paragraph style.
*
* @param array|\PhpOffice\PhpWord\Style\Paragraph|string $style
*
* @return \PhpOffice\PhpWord\Style\Paragraph|string
*/
public function setParagraphStyle($style = null)
{
if (is_array($style)) {
$this->paragraphStyle = new Paragraph();
$this->paragraphStyle->setStyleByArray($style);
} elseif ($style instanceof Paragraph) {
$this->paragraphStyle = $style;
} else {
$this->paragraphStyle = $style;
}
return $this->paragraphStyle;
}
/**
* Get Paragraph style.
*
* @return null|\PhpOffice\PhpWord\Style\Paragraph|string
*/
public function getParagraphStyle()
{
return $this->paragraphStyle;
}
/**
* Has font/paragraph style defined.
*
* @return bool
*/
public function hasStyle()
{
return null !== $this->fontStyle || null !== $this->paragraphStyle;
}
}
@@ -0,0 +1,93 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use PhpOffice\PhpWord\Style\Paragraph;
/**
* Textrun/paragraph element.
*/
class TextRun extends AbstractContainer
{
/**
* @var string Container type
*/
protected $container = 'TextRun';
/**
* Paragraph style.
*
* @var Paragraph|string
*/
protected $paragraphStyle;
/**
* Create new instance.
*
* @param array|Paragraph|string $paragraphStyle
*/
public function __construct($paragraphStyle = null)
{
$this->paragraphStyle = $this->setParagraphStyle($paragraphStyle);
}
/**
* Get Paragraph style.
*
* @return Paragraph|string
*/
public function getParagraphStyle()
{
return $this->paragraphStyle;
}
/**
* Set Paragraph style.
*
* @param array|Paragraph|string $style
*
* @return Paragraph|string
*/
public function setParagraphStyle($style = null)
{
if (is_array($style)) {
$this->paragraphStyle = new Paragraph();
$this->paragraphStyle->setStyleByArray($style);
} elseif ($style instanceof Paragraph) {
$this->paragraphStyle = $style;
} elseif (null === $style) {
$this->paragraphStyle = new Paragraph();
} else {
$this->paragraphStyle = $style;
}
return $this->paragraphStyle;
}
public function getText(): string
{
$outstr = '';
foreach ($this->getElements() as $element) {
if ($element instanceof Text) {
$outstr .= $element->getText();
}
}
return $outstr;
}
}
+128
View File
@@ -0,0 +1,128 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use InvalidArgumentException;
use PhpOffice\PhpWord\Shared\Text as SharedText;
use PhpOffice\PhpWord\Style;
/**
* Title element.
*/
class Title extends AbstractElement
{
/**
* Title Text content.
*
* @var string|TextRun
*/
private $text;
/**
* Title depth.
*
* @var int
*/
private $depth = 1;
/**
* Name of the heading style, e.g. 'Heading1'.
*
* @var ?string
*/
private $style;
/**
* Is part of collection.
*
* @var bool
*/
protected $collectionRelation = true;
/**
* Page number.
*
* @var int
*/
private $pageNumber;
/**
* Create a new Title Element.
*
* @param string|TextRun $text
* @param int $depth
*/
public function __construct($text, $depth = 1, ?int $pageNumber = null)
{
if (is_string($text)) {
$this->text = SharedText::toUTF8($text);
} elseif ($text instanceof TextRun) {
$this->text = $text;
} else {
throw new InvalidArgumentException('Invalid text, should be a string or a TextRun');
}
$this->depth = $depth;
$styleName = $depth === 0 ? 'Title' : "Heading_{$this->depth}";
if (array_key_exists($styleName, Style::getStyles())) {
$this->style = str_replace('_', '', $styleName);
}
if ($pageNumber !== null) {
$this->pageNumber = $pageNumber;
}
}
/**
* Get Title Text content.
*
* @return string|TextRun
*/
public function getText()
{
return $this->text;
}
/**
* Get depth.
*
* @return int
*/
public function getDepth()
{
return $this->depth;
}
/**
* Get Title style.
*
* @return ?string
*/
public function getStyle()
{
return $this->style;
}
/**
* Get page number.
*/
public function getPageNumber(): ?int
{
return $this->pageNumber;
}
}
@@ -0,0 +1,104 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
use DateTime;
/**
* TrackChange element.
*
* @see http://datypic.com/sc/ooxml/t-w_CT_TrackChange.html
* @see http://datypic.com/sc/ooxml/t-w_CT_RunTrackChange.html
*/
class TrackChange extends AbstractContainer
{
const INSERTED = 'INSERTED';
const DELETED = 'DELETED';
/**
* @var string Container type
*/
protected $container = 'TrackChange';
/**
* The type of change, (insert or delete), not applicable for PhpOffice\PhpWord\Element\Comment.
*
* @var string
*/
private $changeType;
/**
* Author.
*
* @var string
*/
private $author;
/**
* Date.
*
* @var DateTime
*/
private $date;
/**
* Create a new TrackChange Element.
*
* @param string $changeType
* @param string $author
* @param null|bool|DateTime|int $date
*/
public function __construct($changeType = null, $author = null, $date = null)
{
$this->changeType = $changeType;
$this->author = $author;
if ($date !== null && $date !== false) {
$this->date = ($date instanceof DateTime) ? $date : new DateTime('@' . $date);
}
}
/**
* Get TrackChange Author.
*
* @return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* Get TrackChange Date.
*
* @return DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* Get the Change type.
*
* @return string
*/
public function getChangeType()
{
return $this->changeType;
}
}
@@ -0,0 +1,46 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Escaper;
/**
* @since 0.13.0
*
* @codeCoverageIgnore
*/
abstract class AbstractEscaper implements EscaperInterface
{
/**
* @param ?string $input
*
* @return string
*/
abstract protected function escapeSingleValue($input);
public function escape($input)
{
if (is_array($input)) {
foreach ($input as &$item) {
$item = $this->escapeSingleValue($item);
}
} else {
$input = $this->escapeSingleValue($input);
}
return $input;
}
}
@@ -0,0 +1,33 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Escaper;
/**
* @since 0.13.0
*
* @codeCoverageIgnore
*/
interface EscaperInterface
{
/**
* @param mixed $input
*
* @return mixed
*/
public function escape($input);
}
+33
View File
@@ -0,0 +1,33 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Escaper;
/**
* @since 0.13.0
*
* @codeCoverageIgnore
*/
class RegExp extends AbstractEscaper
{
const REG_EXP_DELIMITER = '/';
protected function escapeSingleValue($input)
{
return self::REG_EXP_DELIMITER . preg_quote($input, self::REG_EXP_DELIMITER) . self::REG_EXP_DELIMITER . 'u';
}
}
+98
View File
@@ -0,0 +1,98 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Escaper;
/**
* @since 0.13.0
*
* @codeCoverageIgnore
*/
class Rtf extends AbstractEscaper
{
protected function escapeAsciiCharacter($code)
{
if ($code == 9) {
return '{\\tab}';
}
if (0x20 > $code || $code >= 0x80) {
return '{\\u' . $code . '}';
}
if ($code == 123 || $code == 125 || $code == 92) { // open or close brace or backslash
return '\\' . chr($code);
}
return chr($code);
}
protected function escapeMultibyteCharacter($code)
{
return '\\uc0{\\u' . $code . '}';
}
/**
* @see http://www.randomchaos.com/documents/?source=php_and_unicode
*
* @param ?string $input
*/
protected function escapeSingleValue($input)
{
$escapedValue = '';
$numberOfBytes = 1;
$bytes = [];
for ($i = 0; $i < strlen($input); ++$i) {
$character = $input[$i];
$asciiCode = ord($character);
if ($asciiCode < 128) {
$escapedValue .= $this->escapeAsciiCharacter($asciiCode);
} else {
if (0 == count($bytes)) {
if ($asciiCode < 224) {
$numberOfBytes = 2;
} elseif ($asciiCode < 240) {
$numberOfBytes = 3;
} elseif ($asciiCode < 248) {
$numberOfBytes = 4;
}
}
$bytes[] = $asciiCode;
if ($numberOfBytes == count($bytes)) {
if (4 == $numberOfBytes) {
$multibyteCode = ($bytes[0] % 8) * 262144 + ($bytes[1] % 64) * 4096 + ($bytes[2] % 64) * 64 + ($bytes[3] % 64);
} elseif (3 == $numberOfBytes) {
$multibyteCode = ($bytes[0] % 16) * 4096 + ($bytes[1] % 64) * 64 + ($bytes[2] % 64);
} else {
$multibyteCode = ($bytes[0] % 32) * 64 + ($bytes[1] % 64);
}
if (65279 != $multibyteCode) {
$escapedValue .= $multibyteCode < 128 ? $this->escapeAsciiCharacter($multibyteCode) : $this->escapeMultibyteCharacter($multibyteCode);
}
$numberOfBytes = 1;
$bytes = [];
}
}
}
return $escapedValue;
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Escaper;
/**
* @since 0.13.0
*
* @codeCoverageIgnore
*/
class Xml extends AbstractEscaper
{
protected function escapeSingleValue($input)
{
return (null !== $input) ? htmlspecialchars($input, ENT_QUOTES) : '';
}
}
@@ -0,0 +1,39 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Exception;
/**
* @since 0.12.0
*/
final class CopyFileException extends Exception
{
/**
* @param string $source The fully qualified source file name
* @param string $destination The fully qualified destination file name
* @param int $code The user defined exception code
* @param \Exception $previous The previous exception used for the exception chaining
*/
public function __construct($source, $destination, $code = 0, ?\Exception $previous = null)
{
parent::__construct(
sprintf('Could not copy \'%s\' file to \'%s\'.', $source, $destination),
$code,
$previous
);
}
}
@@ -0,0 +1,37 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Exception;
/**
* @since 0.12.0
*/
final class CreateTemporaryFileException extends Exception
{
/**
* @param int $code The user defined exception code
* @param \Exception $previous The previous exception used for the exception chaining
*/
public function __construct($code = 0, ?\Exception $previous = null)
{
parent::__construct(
'Could not create a temporary file with unique name in the specified directory.',
$code,
$previous
);
}
}
@@ -0,0 +1,25 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Exception;
/**
* General exception.
*/
class Exception extends \Exception
{
}
@@ -0,0 +1,25 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Exception;
/**
* Exception used for when an image is not found.
*/
class InvalidImageException extends Exception
{
}
@@ -0,0 +1,25 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Exception;
/**
* Exception used for when an image is not found.
*/
class InvalidObjectException extends Exception
{
}
@@ -0,0 +1,27 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Exception;
use InvalidArgumentException;
/**
* Exception used for when a style value is invalid.
*/
class InvalidStyleException extends InvalidArgumentException
{
}
@@ -0,0 +1,25 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Exception;
/**
* Exception used for when an image type is unsupported.
*/
class UnsupportedImageTypeException extends Exception
{
}
+144
View File
@@ -0,0 +1,144 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord;
use PhpOffice\PhpWord\Element\Text;
use PhpOffice\PhpWord\Element\TextRun;
use PhpOffice\PhpWord\Exception\Exception;
use PhpOffice\PhpWord\Reader\ReaderInterface;
use PhpOffice\PhpWord\Writer\WriterInterface;
use ReflectionClass;
abstract class IOFactory
{
/**
* Create new writer.
*
* @param string $name
*
* @return WriterInterface
*/
public static function createWriter(PhpWord $phpWord, $name = 'Word2007')
{
if ($name !== 'WriterInterface' && !in_array($name, ['ODText', 'RTF', 'Word2007', 'HTML', 'PDF'], true)) {
throw new Exception("\"{$name}\" is not a valid writer.");
}
$fqName = "PhpOffice\\PhpWord\\Writer\\{$name}";
return new $fqName($phpWord);
}
/**
* Create new reader.
*
* @param string $name
*
* @return ReaderInterface
*/
public static function createReader($name = 'Word2007')
{
return self::createObject('Reader', $name);
}
/**
* Create new object.
*
* @param string $type
* @param string $name
* @param \PhpOffice\PhpWord\PhpWord $phpWord
*
* @return \PhpOffice\PhpWord\Reader\ReaderInterface|\PhpOffice\PhpWord\Writer\WriterInterface
*/
private static function createObject($type, $name, $phpWord = null)
{
$class = "PhpOffice\\PhpWord\\{$type}\\{$name}";
if (class_exists($class) && self::isConcreteClass($class)) {
return new $class($phpWord);
}
throw new Exception("\"{$name}\" is not a valid {$type}.");
}
/**
* Loads PhpWord from file.
*
* @param string $filename The name of the file
* @param string $readerName
*
* @return \PhpOffice\PhpWord\PhpWord $phpWord
*/
public static function load($filename, $readerName = 'Word2007')
{
/** @var \PhpOffice\PhpWord\Reader\ReaderInterface $reader */
$reader = self::createReader($readerName);
return $reader->load($filename);
}
/**
* Loads PhpWord ${variable} from file.
*
* @param string $filename The name of the file
*
* @return array The extracted variables
*/
public static function extractVariables(string $filename, string $readerName = 'Word2007'): array
{
/** @var \PhpOffice\PhpWord\Reader\ReaderInterface $reader */
$reader = self::createReader($readerName);
$document = $reader->load($filename);
$extractedVariables = [];
foreach ($document->getSections() as $section) {
$concatenatedText = '';
foreach ($section->getElements() as $element) {
if ($element instanceof TextRun) {
foreach ($element->getElements() as $textElement) {
if ($textElement instanceof Text) {
$text = $textElement->getText();
$concatenatedText .= $text;
}
}
}
}
preg_match_all('/\$\{([^}]+)\}/', $concatenatedText, $matches);
if (!empty($matches[1])) {
foreach ($matches[1] as $match) {
$trimmedMatch = trim($match);
$extractedVariables[] = $trimmedMatch;
}
}
}
return $extractedVariables;
}
/**
* Check if it's a concrete class (not abstract nor interface).
*
* @param string $class
*
* @return bool
*/
private static function isConcreteClass($class)
{
$reflection = new ReflectionClass($class);
return !$reflection->isAbstract() && !$reflection->isInterface();
}
}
+208
View File
@@ -0,0 +1,208 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord;
use PhpOffice\PhpWord\Element\Image;
use PhpOffice\PhpWord\Exception\Exception;
/**
* Media collection.
*/
class Media
{
/**
* Media elements.
*
* @var array
*/
private static $elements = [];
/**
* Add new media element.
*
* @since 0.10.0
* @since 0.9.2
*
* @param string $container section|headerx|footerx|footnote|endnote
* @param string $mediaType image|object|link
* @param string $source
*
* @return int
*/
public static function addElement($container, $mediaType, $source, ?Image $image = null)
{
// Assign unique media Id and initiate media container if none exists
$mediaId = md5($container . $source);
if (!isset(self::$elements[$container])) {
self::$elements[$container] = [];
}
// Add media if not exists or point to existing media
if (!isset(self::$elements[$container][$mediaId])) {
$mediaCount = self::countElements($container);
$mediaTypeCount = self::countElements($container, $mediaType);
++$mediaTypeCount;
$rId = ++$mediaCount;
$target = null;
$mediaData = ['mediaIndex' => $mediaTypeCount];
switch ($mediaType) {
// Images
case 'image':
if (null === $image) {
throw new Exception('Image object not assigned.');
}
$isMemImage = $image->isMemImage();
$extension = $image->getImageExtension();
$mediaData['imageExtension'] = $extension;
$mediaData['imageType'] = $image->getImageType();
if ($isMemImage) {
$mediaData['isMemImage'] = true;
$mediaData['imageString'] = $image->getImageString();
}
$target = "{$container}_image{$mediaTypeCount}.{$extension}";
$image->setTarget($target);
$image->setMediaIndex($mediaTypeCount);
break;
// Objects
case 'object':
$target = "{$container}_oleObject{$mediaTypeCount}.bin";
break;
// Links
case 'link':
$target = $source;
break;
}
$mediaData['source'] = $source;
$mediaData['target'] = $target;
$mediaData['type'] = $mediaType;
$mediaData['rID'] = $rId;
self::$elements[$container][$mediaId] = $mediaData;
return $rId;
}
$mediaData = self::$elements[$container][$mediaId];
if (null !== $image) {
$image->setTarget($mediaData['target']);
$image->setMediaIndex($mediaData['mediaIndex']);
}
return $mediaData['rID'];
}
/**
* Get media elements count.
*
* @param string $container section|headerx|footerx|footnote|endnote
* @param string $mediaType image|object|link
*
* @return int
*
* @since 0.10.0
*/
public static function countElements($container, $mediaType = null)
{
$mediaCount = 0;
if (isset(self::$elements[$container])) {
foreach (self::$elements[$container] as $mediaData) {
if (null !== $mediaType) {
if ($mediaType == $mediaData['type']) {
++$mediaCount;
}
} else {
++$mediaCount;
}
}
}
return $mediaCount;
}
/**
* Get media elements.
*
* @param string $container section|headerx|footerx|footnote|endnote
* @param string $type image|object|link
*
* @return array
*
* @since 0.10.0
*/
public static function getElements($container, $type = null)
{
$elements = [];
// 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) {
$elements[$key] = $val;
}
}
return $elements;
}
if (!isset(self::$elements[$container])) {
return $elements;
}
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 = [];
foreach (self::$elements[$container] as $key => $data) {
if ($type !== null) {
if ($type == $data['type']) {
$elements[$key] = $data;
}
} else {
$elements[$key] = $data;
}
}
return $elements;
}
/**
* Reset media elements.
*/
public static function resetElements(): void
{
self::$elements = [];
}
}
@@ -0,0 +1,64 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Metadata;
/**
* Compatibility setting class.
*
* @since 0.12.0
* @see http://www.datypic.com/sc/ooxml/t-w_CT_Compat.html
*/
class Compatibility
{
/**
* OOXML version.
*
* 12 = 2007
* 14 = 2010
* 15 = 2013
*
* @var int
*
* @see http://msdn.microsoft.com/en-us/library/dd909048%28v=office.12%29.aspx
*/
private $ooxmlVersion = 12;
/**
* Get OOXML version.
*
* @return int
*/
public function getOoxmlVersion()
{
return $this->ooxmlVersion;
}
/**
* Set OOXML version.
*
* @param int $value
*
* @return self
*/
public function setOoxmlVersion($value)
{
$this->ooxmlVersion = $value;
return $this;
}
}
@@ -0,0 +1,602 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Metadata;
use DateTime;
/**
* Document information.
*/
class DocInfo
{
/** @const string Property type constants */
const PROPERTY_TYPE_BOOLEAN = 'b';
const PROPERTY_TYPE_INTEGER = 'i';
const PROPERTY_TYPE_FLOAT = 'f';
const PROPERTY_TYPE_DATE = 'd';
const PROPERTY_TYPE_STRING = 's';
const PROPERTY_TYPE_UNKNOWN = 'u';
/**
* Creator.
*
* @var string
*/
private $creator;
/**
* LastModifiedBy.
*
* @var string
*/
private $lastModifiedBy;
/**
* Created.
*
* @var int
*/
private $created;
/**
* Modified.
*
* @var int
*/
private $modified;
/**
* Title.
*
* @var string
*/
private $title;
/**
* Description.
*
* @var string
*/
private $description;
/**
* Subject.
*
* @var string
*/
private $subject;
/**
* Keywords.
*
* @var string
*/
private $keywords;
/**
* Category.
*
* @var string
*/
private $category;
/**
* Company.
*
* @var string
*/
private $company;
/**
* Manager.
*
* @var string
*/
private $manager;
/**
* Custom Properties.
*
* @var array
*/
private $customProperties = [];
/**
* Create new instance.
*/
public function __construct()
{
$this->creator = '';
$this->lastModifiedBy = $this->creator;
$this->created = time();
$this->modified = time();
$this->title = '';
$this->subject = '';
$this->description = '';
$this->keywords = '';
$this->category = '';
$this->company = '';
$this->manager = '';
}
/**
* Get Creator.
*
* @return string
*/
public function getCreator()
{
return $this->creator;
}
/**
* Set Creator.
*
* @param string $value
*
* @return self
*/
public function setCreator($value = '')
{
$this->creator = $this->setValue($value, '');
return $this;
}
/**
* Get Last Modified By.
*
* @return string
*/
public function getLastModifiedBy()
{
return $this->lastModifiedBy;
}
/**
* Set Last Modified By.
*
* @param string $value
*
* @return self
*/
public function setLastModifiedBy($value = '')
{
$this->lastModifiedBy = $this->setValue($value, $this->creator);
return $this;
}
/**
* Get Created.
*
* @return int
*/
public function getCreated()
{
return $this->created;
}
/**
* Set Created.
*
* @param int $value
*
* @return self
*/
public function setCreated($value = null)
{
$this->created = $this->setValue($value, time());
return $this;
}
/**
* Get Modified.
*
* @return int
*/
public function getModified()
{
return $this->modified;
}
/**
* Set Modified.
*
* @param int $value
*
* @return self
*/
public function setModified($value = null)
{
$this->modified = $this->setValue($value, time());
return $this;
}
/**
* Get Title.
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set Title.
*
* @param string $value
*
* @return self
*/
public function setTitle($value = '')
{
$this->title = $this->setValue($value, '');
return $this;
}
/**
* Get Description.
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set Description.
*
* @param string $value
*
* @return self
*/
public function setDescription($value = '')
{
$this->description = $this->setValue($value, '');
return $this;
}
/**
* Get Subject.
*
* @return string
*/
public function getSubject()
{
return $this->subject;
}
/**
* Set Subject.
*
* @param string $value
*
* @return self
*/
public function setSubject($value = '')
{
$this->subject = $this->setValue($value, '');
return $this;
}
/**
* Get Keywords.
*
* @return string
*/
public function getKeywords()
{
return $this->keywords;
}
/**
* Set Keywords.
*
* @param string $value
*
* @return self
*/
public function setKeywords($value = '')
{
$this->keywords = $this->setValue($value, '');
return $this;
}
/**
* Get Category.
*
* @return string
*/
public function getCategory()
{
return $this->category;
}
/**
* Set Category.
*
* @param string $value
*
* @return self
*/
public function setCategory($value = '')
{
$this->category = $this->setValue($value, '');
return $this;
}
/**
* Get Company.
*
* @return string
*/
public function getCompany()
{
return $this->company;
}
/**
* Set Company.
*
* @param string $value
*
* @return self
*/
public function setCompany($value = '')
{
$this->company = $this->setValue($value, '');
return $this;
}
/**
* Get Manager.
*
* @return string
*/
public function getManager()
{
return $this->manager;
}
/**
* Set Manager.
*
* @param string $value
*
* @return self
*/
public function setManager($value = '')
{
$this->manager = $this->setValue($value, '');
return $this;
}
/**
* Get a List of Custom Property Names.
*
* @return array of string
*/
public function getCustomProperties()
{
return array_keys($this->customProperties);
}
/**
* Check if a Custom Property is defined.
*
* @param string $propertyName
*
* @return bool
*/
public function isCustomPropertySet($propertyName)
{
return isset($this->customProperties[$propertyName]);
}
/**
* Get a Custom Property Value.
*
* @param string $propertyName
*
* @return mixed
*/
public function getCustomPropertyValue($propertyName)
{
if ($this->isCustomPropertySet($propertyName)) {
return $this->customProperties[$propertyName]['value'];
}
return null;
}
/**
* Get a Custom Property Type.
*
* @param string $propertyName
*
* @return ?string
*/
public function getCustomPropertyType($propertyName)
{
if ($this->isCustomPropertySet($propertyName)) {
return $this->customProperties[$propertyName]['type'];
}
return null;
}
/**
* Set a Custom Property.
*
* @param string $propertyName
* @param mixed $propertyValue
* @param string $propertyType
* 'i': Integer
* 'f': Floating Point
* 's': String
* 'd': Date/Time
* 'b': Boolean
*
* @return self
*/
public function setCustomProperty($propertyName, $propertyValue = '', $propertyType = null)
{
$propertyTypes = [
self::PROPERTY_TYPE_INTEGER,
self::PROPERTY_TYPE_FLOAT,
self::PROPERTY_TYPE_STRING,
self::PROPERTY_TYPE_DATE,
self::PROPERTY_TYPE_BOOLEAN,
];
if (($propertyType === null) || (!in_array($propertyType, $propertyTypes))) {
if ($propertyValue === null) {
$propertyType = self::PROPERTY_TYPE_STRING;
} elseif (is_float($propertyValue)) {
$propertyType = self::PROPERTY_TYPE_FLOAT;
} elseif (is_int($propertyValue)) {
$propertyType = self::PROPERTY_TYPE_INTEGER;
} elseif (is_bool($propertyValue)) {
$propertyType = self::PROPERTY_TYPE_BOOLEAN;
} elseif ($propertyValue instanceof DateTime) {
$propertyType = self::PROPERTY_TYPE_DATE;
} else {
$propertyType = self::PROPERTY_TYPE_STRING;
}
}
$this->customProperties[$propertyName] = [
'value' => $propertyValue,
'type' => $propertyType,
];
return $this;
}
/**
* Convert document property based on type.
*
* @param string $propertyValue
* @param string $propertyType
*
* @return mixed
*/
public static function convertProperty($propertyValue, $propertyType)
{
$conversion = self::getConversion($propertyType);
switch ($conversion) {
case 'empty': // Empty
return '';
case 'null': // Null
return null;
case 'int': // Signed integer
return (int) $propertyValue;
case 'uint': // Unsigned integer
return abs((int) $propertyValue);
case 'float': // Float
return (float) $propertyValue;
case 'date': // Date
return strtotime($propertyValue);
case 'bool': // Boolean
return $propertyValue == 'true';
}
return $propertyValue;
}
/**
* Convert document property type.
*
* @param string $propertyType
*
* @return string
*/
public static function convertPropertyType($propertyType)
{
$typeGroups = [
self::PROPERTY_TYPE_INTEGER => ['i1', 'i2', 'i4', 'i8', 'int', 'ui1', 'ui2', 'ui4', 'ui8', 'uint'],
self::PROPERTY_TYPE_FLOAT => ['r4', 'r8', 'decimal'],
self::PROPERTY_TYPE_STRING => ['empty', 'null', 'lpstr', 'lpwstr', 'bstr'],
self::PROPERTY_TYPE_DATE => ['date', 'filetime'],
self::PROPERTY_TYPE_BOOLEAN => ['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 = [
'empty' => ['empty'],
'null' => ['null'],
'int' => ['i1', 'i2', 'i4', 'i8', 'int'],
'uint' => ['ui1', 'ui2', 'ui4', 'ui8', 'uint'],
'float' => ['r4', 'r8', 'decimal'],
'bool' => ['bool'],
'date' => ['date', 'filetime'],
];
foreach ($conversions as $conversion => $types) {
if (in_array($propertyType, $types)) {
return $conversion;
}
}
return 'string';
}
}
@@ -0,0 +1,205 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Metadata;
use InvalidArgumentException;
use PhpOffice\PhpWord\Shared\Microsoft\PasswordEncoder;
use PhpOffice\PhpWord\SimpleType\DocProtect;
/**
* Document protection class.
*
* @since 0.12.0
* @see http://www.datypic.com/sc/ooxml/t-w_CT_DocProtect.html
*/
class Protection
{
/**
* Editing restriction none|readOnly|comments|trackedChanges|forms.
*
* @var string
*
* @see http://www.datypic.com/sc/ooxml/a-w_edit-1.html
*/
private $editing;
/**
* password.
*
* @var string
*/
private $password;
/**
* Iterations to Run Hashing Algorithm.
*
* @var int
*/
private $spinCount = 100000;
/**
* Cryptographic Hashing Algorithm (see constants defined in \PhpOffice\PhpWord\Shared\Microsoft\PasswordEncoder).
*
* @var string
*/
private $algorithm = PasswordEncoder::ALGORITHM_SHA_1;
/**
* Salt for Password Verifier.
*
* @var string
*/
private $salt;
/**
* Create a new instance.
*
* @param string $editing
*/
public function __construct($editing = null)
{
if ($editing != null) {
$this->setEditing($editing);
}
}
/**
* Get editing protection.
*
* @return string
*/
public function getEditing()
{
return $this->editing;
}
/**
* Set editing protection.
*
* @param string $editing Any value of \PhpOffice\PhpWord\SimpleType\DocProtect
*
* @return self
*/
public function setEditing($editing = null)
{
DocProtect::validate($editing);
$this->editing = $editing;
return $this;
}
/**
* Get password.
*
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set password.
*
* @param string $password
*
* @return self
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get count for hash iterations.
*
* @return int
*/
public function getSpinCount()
{
return $this->spinCount;
}
/**
* Set count for hash iterations.
*
* @param int $spinCount
*
* @return self
*/
public function setSpinCount($spinCount)
{
$this->spinCount = $spinCount;
return $this;
}
/**
* Get algorithm.
*
* @return string
*/
public function getAlgorithm()
{
return $this->algorithm;
}
/**
* Set algorithm.
*
* @param string $algorithm
*
* @return self
*/
public function setAlgorithm($algorithm)
{
$this->algorithm = $algorithm;
return $this;
}
/**
* Get salt.
*
* @return string
*/
public function getSalt()
{
return $this->salt;
}
/**
* Set salt. Salt HAS to be 16 characters, or an exception will be thrown.
*
* @param string $salt
*
* @return self
*/
public function setSalt($salt)
{
if ($salt !== null && strlen($salt) !== 16) {
throw new InvalidArgumentException('salt has to be of exactly 16 bytes length');
}
$this->salt = $salt;
return $this;
}
}
@@ -0,0 +1,499 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Metadata;
use PhpOffice\PhpWord\ComplexType\ProofState;
use PhpOffice\PhpWord\ComplexType\TrackChangesView;
use PhpOffice\PhpWord\SimpleType\Zoom;
use PhpOffice\PhpWord\Style\Language;
/**
* Setting class.
*
* @since 0.14.0
* @see http://www.datypic.com/sc/ooxml/t-w_CT_Settings.html
*/
class Settings
{
/**
* Magnification Setting.
*
* @see http://www.datypic.com/sc/ooxml/e-w_zoom-1.html
*
* @var mixed either integer, in which case it treated as a percent, or one of PhpOffice\PhpWord\SimpleType\Zoom
*/
private $zoom = 100;
/**
* Mirror Page Margins.
*
* @see http://www.datypic.com/sc/ooxml/e-w_mirrorMargins-1.html
*
* @var bool
*/
private $mirrorMargins;
/**
* Hide spelling errors.
*
* @var bool
*/
private $hideSpellingErrors = false;
/**
* Hide grammatical errors.
*
* @var bool
*/
private $hideGrammaticalErrors = false;
/**
* Visibility of Annotation Types.
*
* @var TrackChangesView
*/
private $revisionView;
/**
* Track Revisions to Document.
*
* @var bool
*/
private $trackRevisions = false;
/**
* Do Not Use Move Syntax When Tracking Revisions.
*
* @var bool
*/
private $doNotTrackMoves = false;
/**
* Do Not Track Formatting Revisions When Tracking Revisions.
*
* @var bool
*/
private $doNotTrackFormatting = false;
/**
* Spelling and Grammatical Checking State.
*
* @var \PhpOffice\PhpWord\ComplexType\ProofState
*/
private $proofState;
/**
* Document Editing Restrictions.
*
* @var \PhpOffice\PhpWord\Metadata\Protection
*/
private $documentProtection;
/**
* Enables different header for odd and even pages.
*
* @var bool
*/
private $evenAndOddHeaders = false;
/**
* Theme Font Languages.
*
* @var ?Language
*/
private $themeFontLang;
/**
* Automatically Recalculate Fields on Open.
*
* @var bool
*/
private $updateFields = false;
/**
* Radix Point for Field Code Evaluation.
*
* @var string
*/
private $decimalSymbol = '.';
/**
* Automatically hyphenate document contents when displayed.
*
* @var null|bool
*/
private $autoHyphenation;
/**
* Maximum number of consecutively hyphenated lines.
*
* @var null|int
*/
private $consecutiveHyphenLimit;
/**
* The allowed amount of whitespace before hyphenation is applied.
*
* @var null|float|int
*/
private $hyphenationZone;
/**
* Do not hyphenate words in all capital letters.
*
* @var null|bool
*/
private $doNotHyphenateCaps;
/**
* Enable or disable book-folded printing.
*
* @var bool
*/
private $bookFoldPrinting = false;
/**
* @return Protection
*/
public function getDocumentProtection()
{
if ($this->documentProtection == null) {
$this->documentProtection = new Protection();
}
return $this->documentProtection;
}
/**
* @param Protection $documentProtection
*/
public function setDocumentProtection($documentProtection): void
{
$this->documentProtection = $documentProtection;
}
/**
* @return ProofState
*/
public function getProofState()
{
if ($this->proofState == null) {
$this->proofState = new ProofState();
}
return $this->proofState;
}
/**
* @param ProofState $proofState
*/
public function setProofState($proofState): void
{
$this->proofState = $proofState;
}
/**
* Are spelling errors hidden.
*
* @return bool
*/
public function hasHideSpellingErrors()
{
return $this->hideSpellingErrors;
}
/**
* Hide spelling errors.
*
* @param ?bool $hideSpellingErrors
*/
public function setHideSpellingErrors($hideSpellingErrors): void
{
$this->hideSpellingErrors = $hideSpellingErrors === null ? true : $hideSpellingErrors;
}
/**
* Are grammatical errors hidden.
*
* @return bool
*/
public function hasHideGrammaticalErrors()
{
return $this->hideGrammaticalErrors;
}
/**
* Hide grammatical errors.
*
* @param ?bool $hideGrammaticalErrors
*/
public function setHideGrammaticalErrors($hideGrammaticalErrors): void
{
$this->hideGrammaticalErrors = $hideGrammaticalErrors === null ? true : $hideGrammaticalErrors;
}
/**
* @return bool
*/
public function hasEvenAndOddHeaders()
{
return $this->evenAndOddHeaders;
}
/**
* @param ?bool $evenAndOddHeaders
*/
public function setEvenAndOddHeaders($evenAndOddHeaders): void
{
$this->evenAndOddHeaders = $evenAndOddHeaders === null ? true : $evenAndOddHeaders;
}
/**
* Get the Visibility of Annotation Types.
*
* @return \PhpOffice\PhpWord\ComplexType\TrackChangesView
*/
public function getRevisionView()
{
return $this->revisionView;
}
/**
* Set the Visibility of Annotation Types.
*/
public function setRevisionView(?TrackChangesView $trackChangesView = null): void
{
$this->revisionView = $trackChangesView;
}
/**
* @return bool
*/
public function hasTrackRevisions()
{
return $this->trackRevisions;
}
/**
* @param ?bool $trackRevisions
*/
public function setTrackRevisions($trackRevisions): void
{
$this->trackRevisions = $trackRevisions === null ? true : $trackRevisions;
}
/**
* @return bool
*/
public function hasDoNotTrackMoves()
{
return $this->doNotTrackMoves;
}
/**
* @param ?bool $doNotTrackMoves
*/
public function setDoNotTrackMoves($doNotTrackMoves): void
{
$this->doNotTrackMoves = $doNotTrackMoves === null ? true : $doNotTrackMoves;
}
/**
* @return bool
*/
public function hasDoNotTrackFormatting()
{
return $this->doNotTrackFormatting;
}
/**
* @param ?bool $doNotTrackFormatting
*/
public function setDoNotTrackFormatting($doNotTrackFormatting): void
{
$this->doNotTrackFormatting = $doNotTrackFormatting === null ? true : $doNotTrackFormatting;
}
/**
* @return mixed
*/
public function getZoom()
{
return $this->zoom;
}
/**
* @param mixed $zoom
*/
public function setZoom($zoom): void
{
if (is_numeric($zoom)) {
// zoom is a percentage
$this->zoom = $zoom;
} else {
Zoom::validate($zoom);
$this->zoom = $zoom;
}
}
/**
* @return bool
*/
public function hasMirrorMargins()
{
return $this->mirrorMargins;
}
/**
* @param bool $mirrorMargins
*/
public function setMirrorMargins($mirrorMargins): void
{
$this->mirrorMargins = $mirrorMargins;
}
/**
* Returns the Language.
*/
public function getThemeFontLang(): ?Language
{
return $this->themeFontLang;
}
/**
* Sets the Language for this document.
*/
public function setThemeFontLang(Language $themeFontLang): self
{
$this->themeFontLang = $themeFontLang;
return $this;
}
/**
* @return bool
*/
public function hasUpdateFields()
{
return $this->updateFields;
}
/**
* @param ?bool $updateFields
*/
public function setUpdateFields($updateFields): void
{
$this->updateFields = $updateFields === null ? false : $updateFields;
}
/**
* Returns the Radix Point for Field Code Evaluation.
*
* @return string
*/
public function getDecimalSymbol()
{
return $this->decimalSymbol;
}
/**
* sets the Radix Point for Field Code Evaluation.
*
* @param string $decimalSymbol
*/
public function setDecimalSymbol($decimalSymbol): void
{
$this->decimalSymbol = $decimalSymbol;
}
/**
* @return null|bool
*/
public function hasAutoHyphenation()
{
return $this->autoHyphenation;
}
/**
* @param bool $autoHyphenation
*/
public function setAutoHyphenation($autoHyphenation): void
{
$this->autoHyphenation = (bool) $autoHyphenation;
}
/**
* @return null|int
*/
public function getConsecutiveHyphenLimit()
{
return $this->consecutiveHyphenLimit;
}
/**
* @param int $consecutiveHyphenLimit
*/
public function setConsecutiveHyphenLimit($consecutiveHyphenLimit): void
{
$this->consecutiveHyphenLimit = (int) $consecutiveHyphenLimit;
}
/**
* @return null|float|int
*/
public function getHyphenationZone()
{
return $this->hyphenationZone;
}
/**
* @param null|float|int $hyphenationZone Measurement unit is twip
*/
public function setHyphenationZone($hyphenationZone): void
{
$this->hyphenationZone = $hyphenationZone;
}
/**
* @return null|bool
*/
public function hasDoNotHyphenateCaps()
{
return $this->doNotHyphenateCaps;
}
/**
* @param bool $doNotHyphenateCaps
*/
public function setDoNotHyphenateCaps($doNotHyphenateCaps): void
{
$this->doNotHyphenateCaps = (bool) $doNotHyphenateCaps;
}
public function hasBookFoldPrinting(): bool
{
return $this->bookFoldPrinting;
}
public function setBookFoldPrinting(bool $bookFoldPrinting): self
{
$this->bookFoldPrinting = $bookFoldPrinting;
return $this;
}
}
+376
View File
@@ -0,0 +1,376 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord;
use BadMethodCallException;
use PhpOffice\PhpWord\Element\Section;
use PhpOffice\PhpWord\Exception\Exception;
/**
* PHPWord main class.
*
* @method Collection\Titles getTitles()
* @method Collection\Footnotes getFootnotes()
* @method Collection\Endnotes getEndnotes()
* @method Collection\Charts getCharts()
* @method Collection\Comments getComments()
* @method int addBookmark(Element\Bookmark $bookmark)
* @method int addTitle(Element\Title $title)
* @method int addFootnote(Element\Footnote $footnote)
* @method int addEndnote(Element\Endnote $endnote)
* @method int addChart(Element\Chart $chart)
* @method int addComment(Element\Comment $comment)
* @method Style\Paragraph addParagraphStyle(string $styleName, mixed $styles)
* @method Style\Font addFontStyle(string $styleName, mixed $fontStyle, mixed $paragraphStyle = null)
* @method Style\Font addLinkStyle(string $styleName, mixed $styles)
* @method Style\Font addTitleStyle(mixed $depth, mixed $fontStyle, mixed $paragraphStyle = null)
* @method Style\Table addTableStyle(string $styleName, mixed $styleTable, mixed $styleFirstRow = null)
* @method Style\Numbering addNumberingStyle(string $styleName, mixed $styles)
*/
class PhpWord
{
/**
* Collection of sections.
*
* @var \PhpOffice\PhpWord\Element\Section[]
*/
private $sections = [];
/**
* Collections.
*
* @var array
*/
private $collections = [];
/**
* Metadata.
*
* @var array
*
* @since 0.12.0
*/
private $metadata = [];
/**
* Create new instance.
*
* Collections are created dynamically
*/
public function __construct()
{
// Reset Media and styles
Media::resetElements();
Style::resetStyles();
Settings::setDefaultRtl(null);
// Collection
$collections = ['Bookmarks', 'Titles', 'Footnotes', 'Endnotes', 'Charts', 'Comments'];
foreach ($collections as $collection) {
$class = 'PhpOffice\\PhpWord\\Collection\\' . $collection;
$this->collections[$collection] = new $class();
}
// Metadata
$metadata = ['DocInfo', 'Settings', 'Compatibility'];
foreach ($metadata as $meta) {
$class = 'PhpOffice\\PhpWord\\Metadata\\' . $meta;
$this->metadata[$meta] = new $class();
}
}
/**
* Dynamic function call to reduce static dependency.
*
* @since 0.12.0
*
* @param mixed $function
* @param mixed $args
*
* @return mixed
*/
public function __call($function, $args)
{
$function = strtolower($function);
$getCollection = [];
$addCollection = [];
$addStyle = [];
$collections = ['Bookmark', 'Title', 'Footnote', 'Endnote', 'Chart', 'Comment'];
foreach ($collections as $collection) {
$getCollection[] = strtolower("get{$collection}s");
$addCollection[] = strtolower("add{$collection}");
}
$styles = ['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');
$collectionObject = $this->collections[$key];
return $collectionObject->addItem($args[0] ?? null);
}
// Run add style method
if (in_array($function, $addStyle)) {
return forward_static_call_array(['PhpOffice\\PhpWord\\Style', $function], $args);
}
// Exception
throw new BadMethodCallException("Method $function is not defined.");
}
/**
* Get document properties object.
*
* @return \PhpOffice\PhpWord\Metadata\DocInfo
*/
public function getDocInfo()
{
return $this->metadata['DocInfo'];
}
/**
* Get compatibility.
*
* @return \PhpOffice\PhpWord\Metadata\Compatibility
*
* @since 0.12.0
*/
public function getCompatibility()
{
return $this->metadata['Compatibility'];
}
/**
* Get compatibility.
*
* @return \PhpOffice\PhpWord\Metadata\Settings
*
* @since 0.14.0
*/
public function getSettings()
{
return $this->metadata['Settings'];
}
/**
* Get all sections.
*
* @return \PhpOffice\PhpWord\Element\Section[]
*/
public function getSections()
{
return $this->sections;
}
/**
* Returns the section at the requested position.
*
* @param int $index
*
* @return null|\PhpOffice\PhpWord\Element\Section
*/
public function getSection($index)
{
if (array_key_exists($index, $this->sections)) {
return $this->sections[$index];
}
return null;
}
/**
* Create new section.
*
* @param null|array|string $style
*
* @return \PhpOffice\PhpWord\Element\Section
*/
public function addSection($style = null)
{
$section = new Section(count($this->sections) + 1, $style);
$section->setPhpWord($this);
$this->sections[] = $section;
return $section;
}
/**
* Sorts the sections using the callable passed.
*
* @see http://php.net/manual/en/function.usort.php for usage
*
* @param callable $sorter
*/
public function sortSections($sorter): void
{
usort($this->sections, $sorter);
}
/**
* Get default font name.
*
* @return string
*/
public function getDefaultFontName()
{
return Settings::getDefaultFontName();
}
/**
* Set default font name.
*
* @param string $fontName
*/
public function setDefaultFontName($fontName): void
{
Settings::setDefaultFontName($fontName);
}
/**
* Get default font size.
*
* @return int
*/
public function getDefaultFontSize()
{
return Settings::getDefaultFontSize();
}
/**
* Set default font size.
*
* @param int $fontSize
*/
public function setDefaultFontSize($fontSize): void
{
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)
{
return Style::setDefaultParagraphStyle($styles);
}
/**
* 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 = [
'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.
*
* @deprecated 0.10.0
*
* @param array $settings
*
* @return \PhpOffice\PhpWord\Element\Section
*
* @codeCoverageIgnore
*/
public function createSection($settings = null)
{
return $this->addSection($settings);
}
/**
* Get document properties object.
*
* @deprecated 0.12.0
*
* @return \PhpOffice\PhpWord\Metadata\DocInfo
*
* @codeCoverageIgnore
*/
public function getDocumentProperties()
{
return $this->getDocInfo();
}
/**
* Set document properties object.
*
* @deprecated 0.12.0
*
* @param \PhpOffice\PhpWord\Metadata\DocInfo $documentProperties
*
* @return self
*
* @codeCoverageIgnore
*/
public function setDocumentProperties($documentProperties)
{
$this->metadata['Document'] = $documentProperties;
return $this;
}
}
@@ -0,0 +1,131 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader;
use PhpOffice\PhpWord\Exception\Exception;
/**
* Reader abstract class.
*
* @since 0.8.0
*
* @codeCoverageIgnore Abstract class
*/
abstract class AbstractReader implements ReaderInterface
{
/**
* Read data only?
*
* @var bool
*/
protected $readDataOnly = true;
/**
* File pointer.
*
* @var bool|resource
*/
protected $fileHandle;
/**
* Load images.
*
* @var bool
*/
protected $imageLoading = true;
/**
* Read data only?
*
* @return bool
*/
public function isReadDataOnly()
{
// return $this->readDataOnly;
return true;
}
/**
* Set read data only.
*
* @param bool $value
*
* @return self
*/
public function setReadDataOnly($value = true)
{
$this->readDataOnly = $value;
return $this;
}
public function hasImageLoading(): bool
{
return $this->imageLoading;
}
public function setImageLoading(bool $value): self
{
$this->imageLoading = $value;
return $this;
}
/**
* Open file for reading.
*
* @param string $filename
*
* @return resource
*/
protected function openFile($filename)
{
// Check if file exists
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($filename, 'rb');
if ($this->fileHandle === false) {
throw new Exception("Could not open file $filename for reading.");
}
}
/**
* Can the current ReaderInterface read the file?
*
* @param string $filename
*
* @return bool
*/
public function canRead($filename)
{
// Check if file exists
try {
$this->openFile($filename);
} catch (Exception $e) {
return false;
}
if (is_resource($this->fileHandle)) {
fclose($this->fileHandle);
}
return true;
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader;
use Exception;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\Html as HTMLParser;
/**
* HTML Reader class.
*
* @since 0.11.0
*/
class HTML extends AbstractReader implements ReaderInterface
{
/**
* Loads PhpWord from file.
*
* @param string $docFile
*
* @return \PhpOffice\PhpWord\PhpWord
*/
public function load($docFile)
{
$phpWord = new PhpWord();
if ($this->canRead($docFile)) {
$section = $phpWord->addSection();
HTMLParser::addHtml($section, file_get_contents($docFile), true);
} else {
throw new Exception("Cannot read {$docFile}.");
}
return $phpWord;
}
}
File diff suppressed because it is too large Load Diff
+86
View File
@@ -0,0 +1,86 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\XMLReader;
/**
* Reader for ODText.
*
* @since 0.10.0
*/
class ODText extends AbstractReader implements ReaderInterface
{
/**
* Loads PhpWord from file.
*
* @param string $docFile
*
* @return \PhpOffice\PhpWord\PhpWord
*/
public function load($docFile)
{
$phpWord = new PhpWord();
$relationships = $this->readRelationships($docFile);
$readerParts = [
'content.xml' => 'Content',
'meta.xml' => 'Meta',
];
foreach ($readerParts as $xmlFile => $partName) {
$this->readPart($phpWord, $relationships, $partName, $docFile, $xmlFile);
}
return $phpWord;
}
/**
* Read document part.
*/
private function readPart(PhpWord $phpWord, array $relationships, string $partName, string $docFile, string $xmlFile): void
{
$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.
*/
private function readRelationships(string $docFile): array
{
$rels = [];
$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[] = ['type' => $type, 'target' => $target];
}
return $rels;
}
}
@@ -0,0 +1,31 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader\ODText;
use PhpOffice\PhpWord\Reader\Word2007\AbstractPart as Word2007AbstractPart;
/**
* Abstract part reader.
*
* @since 0.10.0
*
* @codeCoverageIgnore
*/
abstract class AbstractPart extends Word2007AbstractPart
{
}
@@ -0,0 +1,206 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader\ODText;
use DateTime;
use DOMElement;
use DOMNodeList;
use PhpOffice\Math\Reader\MathML;
use PhpOffice\PhpWord\Element\Section;
use PhpOffice\PhpWord\Element\TrackChange;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\XMLReader;
/**
* Content reader.
*
* @since 0.10.0
*/
class Content extends AbstractPart
{
/** @var ?Section */
private $section;
/**
* Read content.xml.
*/
public function read(PhpWord $phpWord): void
{
$xmlReader = new XMLReader();
$xmlReader->getDomFromZip($this->docFile, $this->xmlFile);
$trackedChanges = [];
$nodes = $xmlReader->getElements('office:body/office:text/*');
$this->section = null;
$this->processNodes($nodes, $xmlReader, $phpWord);
$this->section = null;
}
/** @param DOMNodeList<DOMElement> $nodes */
public function processNodes(DOMNodeList $nodes, XMLReader $xmlReader, PhpWord $phpWord): void
{
if ($nodes->length > 0) {
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);
$this->getSection($phpWord)->addTitle($node->nodeValue, $depth);
break;
case 'text:p': // Paragraph
$styleName = $xmlReader->getAttribute('text:style-name', $node);
if (substr($styleName, 0, 2) === 'SB') {
break;
}
$element = $xmlReader->getElement('draw:frame/draw:object', $node);
if ($element) {
$mathFile = str_replace('./', '', $element->getAttribute('xlink:href')) . '/content.xml';
$xmlReaderObject = new XMLReader();
$mathElement = $xmlReaderObject->getDomFromZip($this->docFile, $mathFile);
if ($mathElement) {
$mathXML = $mathElement->saveXML($mathElement);
if (is_string($mathXML)) {
$reader = new MathML();
$math = $reader->read($mathXML);
$this->getSection($phpWord)->addFormula($math);
}
}
} else {
$children = $node->childNodes;
$spans = false;
/** @var DOMElement $child */
foreach ($children as $child) {
switch ($child->nodeName) {
case 'text:change-start':
$changeId = $child->getAttribute('text:change-id');
if (isset($trackedChanges[$changeId])) {
$changed = $trackedChanges[$changeId];
}
break;
case 'text:change-end':
unset($changed);
break;
case 'text:change':
$changeId = $child->getAttribute('text:change-id');
if (isset($trackedChanges[$changeId])) {
$changed = $trackedChanges[$changeId];
}
break;
case 'text:span':
$spans = true;
break;
}
}
if ($spans) {
$element = $this->getSection($phpWord)->addTextRun();
foreach ($children as $child) {
switch ($child->nodeName) {
case 'text:span':
/** @var DOMElement $child2 */
foreach ($child->childNodes as $child2) {
switch ($child2->nodeName) {
case '#text':
$element->addText($child2->nodeValue);
break;
case 'text:tab':
$element->addText("\t");
break;
case 'text:s':
$spaces = (int) $child2->getAttribute('text:c') ?: 1;
$element->addText(str_repeat(' ', $spaces));
break;
}
}
break;
}
}
} else {
$element = $this->getSection($phpWord)->addText($node->nodeValue);
}
if (isset($changed) && is_array($changed)) {
$element->setTrackChange($changed['changed']);
if (isset($changed['textNodes'])) {
foreach ($changed['textNodes'] as $changedNode) {
$element = $this->getSection($phpWord)->addText($changedNode->nodeValue);
$element->setTrackChange($changed['changed']);
}
}
}
}
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);
$this->getSection($phpWord)->addListItem($listItem->nodeValue, 0);
}
break;
case 'text:tracked-changes':
$changedRegions = $xmlReader->getElements('text:changed-region', $node);
foreach ($changedRegions as $changedRegion) {
$type = ($changedRegion->firstChild->nodeName == 'text:insertion') ? TrackChange::INSERTED : TrackChange::DELETED;
$creatorNode = $xmlReader->getElements('office:change-info/dc:creator', $changedRegion->firstChild);
$author = $creatorNode[0]->nodeValue;
$dateNode = $xmlReader->getElements('office:change-info/dc:date', $changedRegion->firstChild);
$date = $dateNode[0]->nodeValue;
$date = preg_replace('/\.\d+$/', '', $date);
$date = DateTime::createFromFormat('Y-m-d\TH:i:s', $date);
$changed = new TrackChange($type, $author, $date);
$textNodes = $xmlReader->getElements('text:deletion/text:p', $changedRegion);
$trackedChanges[$changedRegion->getAttribute('text:id')] = ['changed' => $changed, 'textNodes' => $textNodes];
}
break;
case 'text:section': // Section
// $sectionStyleName = $xmlReader->getAttribute('text:style-name', $listItem);
$this->section = $phpWord->addSection();
$children = $node->childNodes;
$this->processNodes($children, $xmlReader, $phpWord);
break;
}
}
}
}
private function getSection(PhpWord $phpWord): Section
{
$section = $this->section;
if ($section === null) {
$section = $this->section = $phpWord->addSection();
}
return $section;
}
}
@@ -0,0 +1,77 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader\ODText;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\XMLReader;
/**
* Meta reader.
*
* @since 0.11.0
*/
class Meta extends AbstractPart
{
/**
* Read meta.xml.
*
* @todo Process property type
*/
public function read(PhpWord $phpWord): void
{
$xmlReader = new XMLReader();
$xmlReader->getDomFromZip($this->docFile, $this->xmlFile);
$docProps = $phpWord->getDocInfo();
$metaNode = $xmlReader->getElement('office:meta');
// Standard properties
$properties = [
'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, ['Category', 'Company', 'Manager'])) {
$method = "set{$property}";
$docProps->$method($propertyNode->nodeValue);
} else {
// Set other custom properties
$docProps->setCustomProperty($property, $propertyNode->nodeValue);
}
}
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader;
use Exception;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Reader\RTF\Document;
/**
* RTF Reader class.
*
* @since 0.11.0
*/
class RTF extends AbstractReader implements ReaderInterface
{
/**
* Loads PhpWord from file.
*
* @param string $docFile
*
* @return \PhpOffice\PhpWord\PhpWord
*/
public function load($docFile)
{
$phpWord = new PhpWord();
if ($this->canRead($docFile)) {
$doc = new Document();
$doc->rtf = file_get_contents($docFile);
$doc->read($phpWord);
} else {
throw new Exception("Cannot read {$docFile}.");
}
return $phpWord;
}
}
@@ -0,0 +1,394 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader\RTF;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\SimpleType\Jc;
/**
* RTF document reader.
*
* References:
* - How to Write an RTF Reader http://latex2rtf.sourceforge.net/rtfspec_45.html
* - PHP rtfclass by Markus Fischer https://github.com/mfn/rtfclass
* - JavaScript RTF-parser by LazyGyu https://github.com/lazygyu/RTF-parser
*
* @since 0.11.0
*
* @SuppressWarnings(PHPMD.UnusedPrivateMethod)
*/
class Document
{
/** @const int */
const PARA = 'readParagraph';
const STYL = 'readStyle';
const SKIP = 'readSkip';
/**
* PhpWord object.
*
* @var \PhpOffice\PhpWord\PhpWord
*/
private $phpWord;
/**
* Section object.
*
* @var \PhpOffice\PhpWord\Element\Section
*/
private $section;
/**
* Textrun object.
*
* @var \PhpOffice\PhpWord\Element\TextRun
*/
private $textrun;
/**
* RTF content.
*
* @var string
*/
public $rtf;
/**
* Content length.
*
* @var int
*/
private $length = 0;
/**
* Character index.
*
* @var int
*/
private $offset = 0;
/**
* Current control word.
*
* @var string
*/
private $control = '';
/**
* Text content.
*
* @var string
*/
private $text = '';
/**
* Parsing a control word flag.
*
* @var bool
*/
private $isControl = false;
/**
* First character flag: watch out for control symbols.
*
* @var bool
*/
private $isFirst = false;
/**
* Group groups.
*
* @var array
*/
private $groups = [];
/**
* Parser flags; not used.
*
* @var array
*/
private $flags = [];
/**
* Parse RTF content.
*
* - Marks controlling characters `{`, `}`, and `\`
* - Removes line endings
* - Builds control words and control symbols
* - Pushes every other character into the text queue
*
* @todo Use `fread` stream for scalability
*/
public function read(PhpWord $phpWord): void
{
$markers = [
123 => '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 (isset($markers[$ascii])) { // Marker found: {, }, \, LF, or CR
$markerFunction = $markers[$ascii];
$this->$markerFunction();
} else {
if (false === $this->isControl) { // 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.
*/
private function markOpening(): void
{
$this->flush(true);
array_push($this->groups, $this->flags);
}
/**
* Mark closing braket `}` character.
*/
private function markClosing(): void
{
$this->flush(true);
$this->flags = array_pop($this->groups);
}
/**
* Mark backslash `\` character.
*/
private function markBackslash(): void
{
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.
*/
private function markNewline(): void
{
if ($this->isControl) {
$this->flushControl(true);
}
}
/**
* Flush control word or text.
*
* @param bool $isControl
*/
private function flush($isControl = false): void
{
if ($this->isControl) {
$this->flushControl($isControl);
} else {
$this->flushText();
}
}
/**
* Flush control word.
*
* @param bool $isControl
*/
private function flushControl($isControl = false): void
{
if (1 === preg_match('/^([A-Za-z]+)(-?[0-9]*) ?$/', $this->control, $match)) {
[, $control, $parameter] = $match;
$this->parseControl($control, $parameter);
}
if (true === $isControl) {
$this->setControl(false);
}
}
/**
* Flush text in queue.
*/
private function flushText(): void
{
if ($this->text != '') {
if (isset($this->flags['property'])) { // Set property
$this->flags['value'] = $this->text;
} else { // Set text
if (true === $this->flags['paragraph']) {
$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
*/
private function setControl($value): void
{
$this->isControl = $value;
$this->isFirst = $value;
}
/**
* Push text into queue.
*
* @param string $char
*/
private function pushText($char): void
{
if ('<' == $char) {
$this->text .= '&lt;';
} elseif ('>' == $char) {
$this->text .= '&gt;';
} else {
$this->text .= $char;
}
}
/**
* Parse control.
*
* @param string $control
* @param string $parameter
*/
private function parseControl($control, $parameter): void
{
$controls = [
'par' => [self::PARA, 'paragraph', true],
'b' => [self::STYL, 'font', 'bold', true],
'i' => [self::STYL, 'font', 'italic', true],
'u' => [self::STYL, 'font', 'underline', true],
'strike' => [self::STYL, 'font', 'strikethrough', true],
'fs' => [self::STYL, 'font', 'size', $parameter],
'qc' => [self::STYL, 'paragraph', 'alignment', Jc::CENTER],
'sa' => [self::STYL, 'paragraph', 'spaceAfter', $parameter],
'fonttbl' => [self::SKIP, 'fonttbl', null],
'colortbl' => [self::SKIP, 'colortbl', null],
'info' => [self::SKIP, 'info', null],
'generator' => [self::SKIP, 'generator', null],
'title' => [self::SKIP, 'title', null],
'subject' => [self::SKIP, 'subject', null],
'category' => [self::SKIP, 'category', null],
'keywords' => [self::SKIP, 'keywords', null],
'comment' => [self::SKIP, 'comment', null],
'shppict' => [self::SKIP, 'pic', null],
'fldinst' => [self::SKIP, 'link', null],
];
if (isset($controls[$control])) {
[$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
*/
private function readParagraph($directives): void
{
[$property, $value] = $directives;
$this->textrun = $this->section->addTextRun();
$this->flags[$property] = $value;
}
/**
* Read style.
*
* @param array $directives
*/
private function readStyle($directives): void
{
[$style, $property, $value] = $directives;
$this->flags['styles'][$style][$property] = $value;
}
/**
* Read skip.
*
* @param array $directives
*/
private function readSkip($directives): void
{
[$property] = $directives;
$this->flags['property'] = $property;
$this->flags['skipped'] = true;
}
/**
* Read text.
*/
private function readText(): void
{
$text = $this->textrun->addText($this->text);
if (isset($this->flags['styles']['font'])) {
$text->getFontStyle()->setStyleByArray($this->flags['styles']['font']);
}
}
}
@@ -0,0 +1,42 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader;
/**
* Reader interface.
*
* @since 0.8.0
*/
interface ReaderInterface
{
/**
* Can the current ReaderInterface read the file?
*
* @param string $filename
*
* @return bool
*/
public function canRead($filename);
/**
* Loads PhpWord from file.
*
* @param string $filename
*/
public function load($filename);
}
+193
View File
@@ -0,0 +1,193 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader;
use Exception;
use PhpOffice\PhpWord\Element\AbstractElement;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Reader\Word2007\AbstractPart;
use PhpOffice\PhpWord\Shared\XMLReader;
use PhpOffice\PhpWord\Shared\ZipArchive;
/**
* Reader for Word2007.
*
* @since 0.8.0
*
* @todo watermark, checkbox, toc
* @todo Partly done: image, object
*/
class Word2007 extends AbstractReader implements ReaderInterface
{
/**
* Loads PhpWord from file.
*
* @param string $docFile
*
* @return \PhpOffice\PhpWord\PhpWord
*/
public function load($docFile)
{
$phpWord = new PhpWord();
$relationships = $this->readRelationships($docFile);
$commentRefs = [];
$steps = [
[
'stepPart' => 'document',
'stepItems' => [
'styles' => 'Styles',
'numbering' => 'Numbering',
],
],
[
'stepPart' => 'main',
'stepItems' => [
'officeDocument' => 'Document',
'core-properties' => 'DocPropsCore',
'extended-properties' => 'DocPropsApp',
'custom-properties' => 'DocPropsCustom',
],
],
[
'stepPart' => 'document',
'stepItems' => [
'endnotes' => 'Endnotes',
'footnotes' => 'Footnotes',
'settings' => 'Settings',
'comments' => 'Comments',
],
],
];
foreach ($steps as $step) {
$stepPart = $step['stepPart'];
$stepItems = $step['stepItems'];
if (!isset($relationships[$stepPart])) {
continue;
}
foreach ($relationships[$stepPart] as $relItem) {
$relType = $relItem['type'];
if (isset($stepItems[$relType])) {
$partName = $stepItems[$relType];
$xmlFile = $relItem['target'];
$part = $this->readPart($phpWord, $relationships, $commentRefs, $partName, $docFile, $xmlFile);
$commentRefs = $part->getCommentReferences();
}
}
}
return $phpWord;
}
/**
* Read document part.
*
* @param array<string, array<string, null|AbstractElement>> $commentRefs
*/
private function readPart(PhpWord $phpWord, array $relationships, array $commentRefs, string $partName, string $docFile, string $xmlFile): AbstractPart
{
$partClass = "PhpOffice\\PhpWord\\Reader\\Word2007\\{$partName}";
if (!class_exists($partClass)) {
throw new Exception(sprintf('The part "%s" doesn\'t exist', $partClass));
}
/** @var AbstractPart $part Type hint */
$part = new $partClass($docFile, $xmlFile);
$part->setImageLoading($this->hasImageLoading());
$part->setRels($relationships);
$part->setCommentReferences($commentRefs);
$part->read($phpWord);
return $part;
}
/**
* Read all relationship files.
*
* @param string $docFile
*
* @return array
*/
private function readRelationships($docFile)
{
$relationships = [];
// _rels/.rels
$relationships['main'] = $this->getRels($docFile, '_rels/.rels');
// word/_rels/*.xml.rels
$wordRelsPath = 'word/_rels/';
$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));
$relationships[$docPart] = $this->getRels($docFile, $xmlFile, 'word/');
}
}
$zip->close();
}
return $relationships;
}
/**
* Get relationship array.
*
* @param string $docFile
* @param string $xmlFile
* @param string $targetPrefix
*
* @return array
*/
private function getRels($docFile, $xmlFile, $targetPrefix = '')
{
$metaPrefix = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/';
$officePrefix = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/';
$rels = [];
$xmlReader = new XMLReader();
$xmlReader->getDomFromZip($docFile, $xmlFile);
$nodes = $xmlReader->getElements('*');
foreach ($nodes as $node) {
$rId = $xmlReader->getAttribute('Id', $node);
$type = $xmlReader->getAttribute('Type', $node);
$target = $xmlReader->getAttribute('Target', $node);
$mode = $xmlReader->getAttribute('TargetMode', $node);
// Remove URL prefixes from $type to make it easier to read
$type = str_replace($metaPrefix, '', $type);
$type = str_replace($officePrefix, '', $type);
$docPart = str_replace('.xml', '', $target);
// Do not add prefix to link source
if ($type != 'hyperlink' && $mode != 'External') {
$target = $targetPrefix . $target;
}
// Push to return array
$rels[$rId] = ['type' => $type, 'target' => $target, 'docPart' => $docPart, 'targetMode' => $mode];
}
ksort($rels);
return $rels;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,56 @@
<?php
namespace PhpOffice\PhpWord\Reader\Word2007;
use DateTime;
use PhpOffice\PhpWord\Element\Comment;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\XMLReader;
class Comments extends AbstractPart
{
/**
* Collection name comments.
*
* @var string
*/
protected $collection = 'comments';
/**
* Read settings.xml.
*/
public function read(PhpWord $phpWord): void
{
$xmlReader = new XMLReader();
$xmlReader->getDomFromZip($this->docFile, $this->xmlFile);
$comments = $phpWord->getComments();
$nodes = $xmlReader->getElements('*');
foreach ($nodes as $node) {
$name = str_replace('w:', '', $node->nodeName);
$author = $xmlReader->getAttribute('w:author', $node);
$date = $xmlReader->getAttribute('w:date', $node);
$initials = $xmlReader->getAttribute('w:initials', $node);
$element = new Comment($author, new DateTime($date), $initials);
$range = $this->getCommentReference($xmlReader->getAttribute('w:id', $node));
if ($range['start']) {
$range['start']->setCommentRangeStart($element);
}
if ($range['end']) {
$range['end']->setCommentRangeEnd($element);
}
$pNodes = $xmlReader->getElements('w:p/w:r', $node);
foreach ($pNodes as $pNode) {
$this->readRun($xmlReader, $pNode, $element, $this->collection);
}
$phpWord->getComments()->addItem($element);
}
}
}
@@ -0,0 +1,40 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader\Word2007;
/**
* Extended properties reader.
*
* @since 0.10.0
*/
class DocPropsApp extends DocPropsCore
{
/**
* Property mapping.
*
* @var array
*/
protected $mapping = ['Company' => 'setCompany', 'Manager' => 'setManager'];
/**
* Callback functions.
*
* @var array
*/
protected $callbacks = [];
}
@@ -0,0 +1,81 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader\Word2007;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\XMLReader;
/**
* Core properties reader.
*
* @since 0.10.0
*/
class DocPropsCore extends AbstractPart
{
/**
* Property mapping.
*
* @var array
*/
protected $mapping = [
'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',
];
/**
* Callback functions.
*
* @var array
*/
protected $callbacks = ['dcterms:created' => 'strtotime', 'dcterms:modified' => 'strtotime'];
/**
* Read core/extended document properties.
*/
public function read(PhpWord $phpWord): void
{
$xmlReader = new XMLReader();
$xmlReader->getDomFromZip($this->docFile, $this->xmlFile);
$docProps = $phpWord->getDocInfo();
$nodes = $xmlReader->getElements('*');
if ($nodes->length > 0) {
foreach ($nodes as $node) {
if (!isset($this->mapping[$node->nodeName])) {
continue;
}
$method = $this->mapping[$node->nodeName];
$value = $node->nodeValue == '' ? null : $node->nodeValue;
if (isset($this->callbacks[$node->nodeName])) {
$value = $this->callbacks[$node->nodeName]($value);
}
if (method_exists($docProps, $method)) {
$docProps->$method($value);
}
}
}
}
}
@@ -0,0 +1,53 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader\Word2007;
use PhpOffice\PhpWord\Metadata\DocInfo;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\XMLReader;
/**
* Custom properties reader.
*
* @since 0.11.0
*/
class DocPropsCustom extends AbstractPart
{
/**
* Read custom document properties.
*/
public function read(PhpWord $phpWord): void
{
$xmlReader = new XMLReader();
$xmlReader->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);
}
}
}
}
@@ -0,0 +1,171 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader\Word2007;
use DOMElement;
use PhpOffice\PhpWord\Element\Section;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\XMLReader;
/**
* Document reader.
*
* @since 0.10.0
*
* @SuppressWarnings(PHPMD.UnusedPrivateMethod) For readWPNode
*/
class Document extends AbstractPart
{
/**
* PhpWord object.
*
* @var \PhpOffice\PhpWord\PhpWord
*/
private $phpWord;
/**
* Read document.xml.
*/
public function read(PhpWord $phpWord): void
{
$this->phpWord = $phpWord;
$xmlReader = new XMLReader();
$xmlReader->getDomFromZip($this->docFile, $this->xmlFile);
$readMethods = ['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 (isset($readMethods[$node->nodeName])) {
$readMethod = $readMethods[$node->nodeName];
$this->$readMethod($xmlReader, $node, $section);
}
}
}
}
/**
* Read header footer.
*
* @param array $settings
*/
private function readHeaderFooter($settings, Section &$section): void
{
$readMethods = ['w:p' => 'readParagraph', 'w:tbl' => 'readTable'];
if (is_array($settings) && isset($settings['hf'])) {
foreach ($settings['hf'] as $rId => $hfSetting) {
if (isset($this->rels['document'][$rId])) {
[$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 (isset($readMethods[$node->nodeName])) {
$readMethod = $readMethods[$node->nodeName];
$this->$readMethod($xmlReader, $node, $hfObject, $docPart);
}
}
}
}
}
}
}
/**
* Read w:sectPr.
*
* @ignoreScrutinizerPatch
*
* @return array
*/
private function readSectionStyle(XMLReader $xmlReader, DOMElement $domNode)
{
$styleDefs = [
'breakType' => [self::READ_VALUE, 'w:type'],
'vAlign' => [self::READ_VALUE, 'w:vAlign'],
'pageSizeW' => [self::READ_VALUE, 'w:pgSz', 'w:w'],
'pageSizeH' => [self::READ_VALUE, 'w:pgSz', 'w:h'],
'orientation' => [self::READ_VALUE, 'w:pgSz', 'w:orient'],
'colsNum' => [self::READ_VALUE, 'w:cols', 'w:num'],
'colsSpace' => [self::READ_VALUE, 'w:cols', 'w:space'],
'marginTop' => [self::READ_VALUE, 'w:pgMar', 'w:top'],
'marginLeft' => [self::READ_VALUE, 'w:pgMar', 'w:left'],
'marginBottom' => [self::READ_VALUE, 'w:pgMar', 'w:bottom'],
'marginRight' => [self::READ_VALUE, 'w:pgMar', 'w:right'],
'headerHeight' => [self::READ_VALUE, 'w:pgMar', 'w:header'],
'footerHeight' => [self::READ_VALUE, 'w:pgMar', 'w:footer'],
'gutter' => [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] = [
'method' => str_replace('w:', '', str_replace('Reference', '', $node->nodeName)),
'type' => $xmlReader->getAttribute('w:type', $node),
];
}
}
return $styles;
}
/**
* Read w:p node.
*/
private function readWPNode(XMLReader $xmlReader, DOMElement $node, Section &$section): void
{
// 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.
*/
private function readWSectPrNode(XMLReader $xmlReader, DOMElement $node, Section &$section): void
{
$style = $this->readSectionStyle($xmlReader, $node);
$section->setStyle($style);
$this->readHeaderFooter($style, $section);
}
}
@@ -0,0 +1,40 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader\Word2007;
/**
* Endnotes reader.
*
* @since 0.10.0
*/
class Endnotes extends Footnotes
{
/**
* Collection name.
*
* @var string
*/
protected $collection = 'endnotes';
/**
* Element name.
*
* @var string
*/
protected $element = 'endnote';
}
@@ -0,0 +1,95 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader\Word2007;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\XMLReader;
/**
* Footnotes reader.
*
* @since 0.10.0
*/
class Footnotes extends AbstractPart
{
/**
* Collection name footnotes|endnotes.
*
* @var string
*/
protected $collection = 'footnotes';
/**
* Element name footnote|endnote.
*
* @var string
*/
protected $element = 'footnote';
/**
* Read (footnotes|endnotes).xml.
*/
public function read(PhpWord $phpWord): void
{
$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 <footnote> or <endnote> without w:type attribute, or with w:type = normal
if ((null === $type || $type === 'normal')) {
$element = $this->getElement($phpWord, $id);
if ($element !== null) {
$pNodes = $xmlReader->getElements('w:p/*', $node);
foreach ($pNodes as $pNode) {
$this->readRun($xmlReader, $pNode, $element, $this->collection);
}
$addMethod = "add{$this->element}";
$phpWord->$addMethod($element);
}
}
}
}
}
/**
* Searches for the element with the given relationId.
*
* @param int $relationId
*
* @return null|\PhpOffice\PhpWord\Element\AbstractContainer
*/
private function getElement(PhpWord $phpWord, $relationId)
{
$getMethod = "get{$this->collection}";
$collection = $phpWord->$getMethod()->getItems();
//not found by key, looping to search by relationId
foreach ($collection as $collectionElement) {
if ($collectionElement->getRelationId() == $relationId) {
return $collectionElement;
}
}
return null;
}
}
@@ -0,0 +1,122 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader\Word2007;
use DOMElement;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\XMLReader;
/**
* Numbering reader.
*
* @since 0.10.0
*/
class Numbering extends AbstractPart
{
/**
* Read numbering.xml.
*/
public function read(PhpWord $phpWord): void
{
$abstracts = [];
$numberings = [];
$xmlReader = new XMLReader();
$xmlReader->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] = ['levels' => []];
$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 int $levelId
*
* @return array
*/
private function readLevel(XMLReader $xmlReader, DOMElement $subnode, $levelId)
{
$level = [];
$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['alignment'] = $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 (null === $value) {
unset($level[$key]);
}
}
return $level;
}
}
@@ -0,0 +1,170 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader\Word2007;
use DOMElement;
use PhpOffice\PhpWord\ComplexType\TrackChangesView;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\XMLReader;
use PhpOffice\PhpWord\Style\Language;
/**
* Settings reader.
*
* @since 0.14.0
*/
class Settings extends AbstractPart
{
/**
* @var array<string>
*/
private $booleanProperties = [
'mirrorMargins',
'hideSpellingErrors',
'hideGrammaticalErrors',
'trackRevisions',
'doNotTrackMoves',
'doNotTrackFormatting',
'evenAndOddHeaders',
'updateFields',
'autoHyphenation',
'doNotHyphenateCaps',
'bookFoldPrinting',
];
/**
* Read settings.xml.
*/
public function read(PhpWord $phpWord): void
{
$xmlReader = new XMLReader();
$xmlReader->getDomFromZip($this->docFile, $this->xmlFile);
$docSettings = $phpWord->getSettings();
$nodes = $xmlReader->getElements('*');
if ($nodes->length > 0) {
foreach ($nodes as $node) {
$name = str_replace('w:', '', $node->nodeName);
$value = $xmlReader->getAttribute('w:val', $node);
$method = 'set' . $name;
if (in_array($name, $this->booleanProperties)) {
$docSettings->$method($value !== 'false');
} elseif (method_exists($this, $method)) {
$this->$method($xmlReader, $phpWord, $node);
} elseif (method_exists($docSettings, $method)) {
$docSettings->$method($value);
}
}
}
}
/**
* Sets the document Language.
*/
protected function setThemeFontLang(XMLReader $xmlReader, PhpWord $phpWord, DOMElement $node): void
{
$val = $xmlReader->getAttribute('w:val', $node);
$eastAsia = $xmlReader->getAttribute('w:eastAsia', $node);
$bidi = $xmlReader->getAttribute('w:bidi', $node);
$themeFontLang = new Language();
$themeFontLang->setLatin($val);
$themeFontLang->setEastAsia($eastAsia);
$themeFontLang->setBidirectional($bidi);
$phpWord->getSettings()->setThemeFontLang($themeFontLang);
}
/**
* Sets the document protection.
*/
protected function setDocumentProtection(XMLReader $xmlReader, PhpWord $phpWord, DOMElement $node): void
{
$documentProtection = $phpWord->getSettings()->getDocumentProtection();
$edit = $xmlReader->getAttribute('w:edit', $node);
if ($edit !== null) {
$documentProtection->setEditing($edit);
}
}
/**
* Sets the proof state.
*/
protected function setProofState(XMLReader $xmlReader, PhpWord $phpWord, DOMElement $node): void
{
$proofState = $phpWord->getSettings()->getProofState();
$spelling = $xmlReader->getAttribute('w:spelling', $node);
$grammar = $xmlReader->getAttribute('w:grammar', $node);
if ($spelling !== null) {
$proofState->setSpelling($spelling);
}
if ($grammar !== null) {
$proofState->setGrammar($grammar);
}
}
/**
* Sets the proof state.
*/
protected function setZoom(XMLReader $xmlReader, PhpWord $phpWord, DOMElement $node): void
{
$percent = $xmlReader->getAttribute('w:percent', $node);
$val = $xmlReader->getAttribute('w:val', $node);
if ($percent !== null || $val !== null) {
$phpWord->getSettings()->setZoom($percent === null ? $val : $percent);
}
}
/**
* Set the Revision view.
*/
protected function setRevisionView(XMLReader $xmlReader, PhpWord $phpWord, DOMElement $node): void
{
$revisionView = new TrackChangesView();
$revisionView->setMarkup(filter_var($xmlReader->getAttribute('w:markup', $node), FILTER_VALIDATE_BOOLEAN));
$revisionView->setComments($xmlReader->getAttribute('w:comments', $node));
$revisionView->setInsDel(filter_var($xmlReader->getAttribute('w:insDel', $node), FILTER_VALIDATE_BOOLEAN));
$revisionView->setFormatting(filter_var($xmlReader->getAttribute('w:formatting', $node), FILTER_VALIDATE_BOOLEAN));
$revisionView->setInkAnnotations(filter_var($xmlReader->getAttribute('w:inkAnnotations', $node), FILTER_VALIDATE_BOOLEAN));
$phpWord->getSettings()->setRevisionView($revisionView);
}
protected function setConsecutiveHyphenLimit(XMLReader $xmlReader, PhpWord $phpWord, DOMElement $node): void
{
$value = $xmlReader->getAttribute('w:val', $node);
if ($value !== null) {
$phpWord->getSettings()->setConsecutiveHyphenLimit($value);
}
}
protected function setHyphenationZone(XMLReader $xmlReader, PhpWord $phpWord, DOMElement $node): void
{
$value = $xmlReader->getAttribute('w:val', $node);
if ($value !== null) {
$phpWord->getSettings()->setHyphenationZone($value);
}
}
}
@@ -0,0 +1,109 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Reader\Word2007;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Shared\XMLReader;
use PhpOffice\PhpWord\Style\Language;
/**
* Styles reader.
*
* @since 0.10.0
*/
class Styles extends AbstractPart
{
/**
* Read styles.xml.
*/
public function read(PhpWord $phpWord): void
{
$xmlReader = new XMLReader();
$xmlReader->getDomFromZip($this->docFile, $this->xmlFile);
$fontDefaults = $xmlReader->getElement('w:docDefaults/w:rPrDefault');
if ($fontDefaults !== null) {
$fontDefaultStyle = $this->readFontStyle($xmlReader, $fontDefaults);
if ($fontDefaultStyle) {
if (array_key_exists('name', $fontDefaultStyle)) {
$phpWord->setDefaultFontName($fontDefaultStyle['name']);
}
if (array_key_exists('size', $fontDefaultStyle)) {
$phpWord->setDefaultFontSize($fontDefaultStyle['size']);
}
if (array_key_exists('lang', $fontDefaultStyle)) {
$phpWord->getSettings()->setThemeFontLang(new Language($fontDefaultStyle['lang']));
}
}
}
$paragraphDefaults = $xmlReader->getElement('w:docDefaults/w:pPrDefault');
if ($paragraphDefaults !== null) {
$paragraphDefaultStyle = $this->readParagraphStyle($xmlReader, $paragraphDefaults);
if ($paragraphDefaultStyle != null) {
$phpWord->setDefaultParagraphStyle($paragraphDefaultStyle);
}
}
$nodes = $xmlReader->getElements('w:style');
if ($nodes->length > 0) {
foreach ($nodes as $node) {
$type = $xmlReader->getAttribute('w:type', $node);
$name = $xmlReader->getAttribute('w:val', $node, 'w:name');
if (null === $name) {
$name = $xmlReader->getAttribute('w:styleId', $node);
}
$headingMatches = [];
preg_match('/Heading\s*(\d)/i', $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;
}
}
}
}
}
+471
View File
@@ -0,0 +1,471 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord;
/**
* PHPWord settings class.
*
* @since 0.8.0
*/
class Settings
{
/**
* Zip libraries.
*
* @const string
*/
public const ZIPARCHIVE = 'ZipArchive';
public const PCLZIP = 'PclZip';
public const OLD_LIB = \PhpOffice\PhpWord\Shared\ZipArchive::class; // @deprecated 0.11
/**
* PDF rendering libraries.
*
* @const string
*/
public const PDF_RENDERER_DOMPDF = 'DomPDF';
public const PDF_RENDERER_TCPDF = 'TCPDF';
public const PDF_RENDERER_MPDF = 'MPDF';
/**
* Measurement units multiplication factor.
* Applied to:
* - Section: margins, header/footer height, gutter, column spacing
* - Tab: position
* - Indentation: left, right, firstLine, hanging
* - Spacing: before, after.
*
* @const string
*/
public const UNIT_TWIP = 'twip'; // = 1/20 point
public const UNIT_CM = 'cm';
public const UNIT_MM = 'mm';
public const UNIT_INCH = 'inch';
public const UNIT_POINT = 'point'; // = 1/72 inch
public const UNIT_PICA = 'pica'; // = 1/6 inch = 12 points
/**
* Default font settings.
* OOXML defined font size values in halfpoints, i.e. twice of what PhpWord
* use, and the conversion will be conducted during XML writing.
*/
public const DEFAULT_FONT_NAME = 'Arial';
public const DEFAULT_FONT_SIZE = 10;
public const DEFAULT_FONT_COLOR = '000000';
public const DEFAULT_FONT_CONTENT_TYPE = 'default'; // default|eastAsia|cs
public const DEFAULT_PAPER = 'A4';
/**
* Compatibility option for XMLWriter.
*
* @var bool
*/
private static $xmlWriterCompatibility = true;
/**
* Name of the class used for Zip file management.
*
* @var string
*/
private static $zipClass = self::ZIPARCHIVE;
/**
* Name of the external Library used for rendering PDF files.
*
* @var null|string
*/
private static $pdfRendererName;
/**
* Options used for rendering PDF files.
*
* @var array
*/
private static $pdfRendererOptions = [];
/**
* Directory Path to the external Library used for rendering PDF files.
*
* @var null|string
*/
private static $pdfRendererPath;
/**
* Measurement unit.
*
* @var string
*/
private static $measurementUnit = self::UNIT_TWIP;
/**
* Default font name.
*
* @var string
*/
private static $defaultFontName = self::DEFAULT_FONT_NAME;
/**
* Default font size.
*
* @var float|int
*/
private static $defaultFontSize = self::DEFAULT_FONT_SIZE;
/**
* Default paper.
*
* @var string
*/
private static $defaultPaper = self::DEFAULT_PAPER;
/**
* Is RTL by default ?
*
* @var ?bool
*/
private static $defaultRtl;
/**
* The user defined temporary directory.
*
* @var string
*/
private static $tempDir = '';
/**
* Enables built-in output escaping mechanism.
* Default value is `false` for backward compatibility with versions below 0.13.0.
*
* @var bool
*/
private static $outputEscapingEnabled = false;
/**
* Return the compatibility option used by the XMLWriter.
*
* @return bool Compatibility
*/
public static function hasCompatibility(): bool
{
return self::$xmlWriterCompatibility;
}
/**
* Set the compatibility option used by the XMLWriter.
* This sets the setIndent and setIndentString for better compatibility.
*/
public static function setCompatibility(bool $compatibility): bool
{
self::$xmlWriterCompatibility = $compatibility;
return true;
}
/**
* Get zip handler class.
*/
public static function getZipClass(): string
{
return self::$zipClass;
}
/**
* Set zip handler class.
*/
public static function setZipClass(string $zipClass): bool
{
if (in_array($zipClass, [self::PCLZIP, self::ZIPARCHIVE, self::OLD_LIB])) {
self::$zipClass = $zipClass;
return true;
}
return false;
}
/**
* Set details of the external library for rendering PDF files.
*
* @return bool Success or failure
*/
public static function setPdfRenderer(string $libraryName, string $libraryBaseDir): bool
{
if (!self::setPdfRendererName($libraryName)) {
return false;
}
return self::setPdfRendererPath($libraryBaseDir);
}
/**
* Return the PDF Rendering Library.
*/
public static function getPdfRendererName(): ?string
{
return self::$pdfRendererName;
}
/**
* Identify the external library to use for rendering PDF files.
*/
public static function setPdfRendererName(?string $libraryName): bool
{
$pdfRenderers = [self::PDF_RENDERER_DOMPDF, self::PDF_RENDERER_TCPDF, self::PDF_RENDERER_MPDF];
if (!in_array($libraryName, $pdfRenderers)) {
return false;
}
self::$pdfRendererName = $libraryName;
return true;
}
/**
* Return the directory path to the PDF Rendering Library.
*/
public static function getPdfRendererPath(): ?string
{
return self::$pdfRendererPath;
}
/**
* Set options of the external library for rendering PDF files.
*/
public static function setPdfRendererOptions(array $options): void
{
self::$pdfRendererOptions = $options;
}
/**
* Return the PDF Rendering Options.
*/
public static function getPdfRendererOptions(): array
{
return self::$pdfRendererOptions;
}
/**
* Location of external library to use for rendering PDF files.
*
* @param null|string $libraryBaseDir Directory path to the library's base folder
*
* @return bool Success or failure
*/
public static function setPdfRendererPath(?string $libraryBaseDir): bool
{
if (!$libraryBaseDir || false === file_exists($libraryBaseDir) || false === is_readable($libraryBaseDir)) {
return false;
}
self::$pdfRendererPath = $libraryBaseDir;
return true;
}
/**
* Get measurement unit.
*/
public static function getMeasurementUnit(): string
{
return self::$measurementUnit;
}
/**
* Set measurement unit.
*/
public static function setMeasurementUnit(string $value): bool
{
$units = [
self::UNIT_TWIP,
self::UNIT_CM,
self::UNIT_MM,
self::UNIT_INCH,
self::UNIT_POINT,
self::UNIT_PICA,
];
if (!in_array($value, $units)) {
return false;
}
self::$measurementUnit = $value;
return true;
}
/**
* Sets the user defined path to temporary directory.
*
* @param string $tempDir The user defined path to temporary directory
*
* @since 0.12.0
*/
public static function setTempDir(string $tempDir): void
{
self::$tempDir = $tempDir;
}
/**
* Returns path to temporary directory.
*
* @since 0.12.0
*/
public static function getTempDir(): string
{
if (!empty(self::$tempDir)) {
$tempDir = self::$tempDir;
} else {
$tempDir = sys_get_temp_dir();
}
return $tempDir;
}
/**
* @since 0.13.0
*/
public static function isOutputEscapingEnabled(): bool
{
return self::$outputEscapingEnabled;
}
/**
* @since 0.13.0
*/
public static function setOutputEscapingEnabled(bool $outputEscapingEnabled): void
{
self::$outputEscapingEnabled = $outputEscapingEnabled;
}
/**
* Get default font name.
*/
public static function getDefaultFontName(): string
{
return self::$defaultFontName;
}
/**
* Set default font name.
*/
public static function setDefaultFontName(string $value): bool
{
if (trim($value) !== '') {
self::$defaultFontName = $value;
return true;
}
return false;
}
/**
* Get default font size.
*
* @return float|int
*/
public static function getDefaultFontSize()
{
return self::$defaultFontSize;
}
/**
* Set default font size.
*
* @param null|float|int $value
*/
public static function setDefaultFontSize($value): bool
{
if ((is_int($value) || is_float($value)) && (int) $value > 0) {
self::$defaultFontSize = $value;
return true;
}
return false;
}
public static function setDefaultRtl(?bool $defaultRtl): void
{
self::$defaultRtl = $defaultRtl;
}
public static function isDefaultRtl(): ?bool
{
return self::$defaultRtl;
}
/**
* Load setting from phpword.yml or phpword.yml.dist.
*/
public static function loadConfig(?string $filename = null): array
{
// Get config file
$configFile = null;
$configPath = __DIR__ . '/../../';
if ($filename !== null) {
$files = [$filename];
} else {
$files = ["{$configPath}phpword.ini", "{$configPath}phpword.ini.dist"];
}
foreach ($files as $file) {
if (file_exists($file)) {
$configFile = realpath($file);
break;
}
}
// Parse config file
$config = [];
if ($configFile !== null) {
$config = @parse_ini_file($configFile);
if ($config === false) {
return [];
}
}
// Set config value
$appliedConfig = [];
foreach ($config as $key => $value) {
$method = "set{$key}";
if (method_exists(__CLASS__, $method)) {
self::$method($value);
$appliedConfig[$key] = $value;
}
}
return $appliedConfig;
}
/**
* Get default paper.
*/
public static function getDefaultPaper(): string
{
return self::$defaultPaper;
}
/**
* Set default paper.
*/
public static function setDefaultPaper(string $value): bool
{
if (trim($value) !== '') {
self::$defaultPaper = $value;
return true;
}
return false;
}
}
@@ -0,0 +1,79 @@
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
*
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Shared;
use InvalidArgumentException;
use ReflectionClass;
abstract class AbstractEnum
{
private static $constCacheArray;
private static function getConstants()
{
if (self::$constCacheArray == null) {
self::$constCacheArray = [];
}
$calledClass = static::class;
if (!array_key_exists($calledClass, self::$constCacheArray)) {
$reflect = new ReflectionClass($calledClass);
self::$constCacheArray[$calledClass] = $reflect->getConstants();
}
return self::$constCacheArray[$calledClass];
}
/**
* Returns all values for this enum.
*
* @return array
*/
public static function values()
{
return array_values(self::getConstants());
}
/**
* Returns true the value is valid for this enum.
*
* @param string $value
*
* @return bool true if value is valid
*/
public static function isValid($value)
{
$values = array_values(self::getConstants());
return in_array($value, $values, true);
}
/**
* Validates that the value passed is a valid value.
*
* @param string $value
*/
public static function validate($value): void
{
if (!self::isValid($value)) {
$calledClass = static::class;
$values = array_values(self::getConstants());
throw new InvalidArgumentException("$value is not a valid value for $calledClass, possible values are " . implode(', ', $values));
}
}
}

Some files were not shown because too many files have changed in this diff Show More