Skip to content
sbodenPublic
forked from cybermonde/odtphp

About

Generate Open Document Text-files from PHP code

Resources

Stars

3 stars

Watchers

1 watching

Forks

 
 

Repository files navigation

ODTPHP

A PHP library for creating and manipulating ODT (OpenDocument Text) files.

Requirements

  • PHP 8.1 or higher
  • PHP ZIP Extension or PclZip library. PHP ZIP Extension is recommended as we will probably remove the PclZip library sometime in the future.

Installation

Install via Composer:

composer require sboden/odtphp:^4

Basic Usage

Simple Variable Substitution

<?php
use Odtphp\Odf;

// Create a new ODT document from a template
$odt = new Odf("template.odt");

// Set simple text variables
$odt->setVars('company_name', 'ACME Corporation');
$odt->setVars('current_date', date('Y-m-d'));

// Save the modified document
$odt->saveToDisk('output.odt');

Advanced Usage with Images and Segments

<?php
use Odtphp\Odf;

// Create ODT document with custom configuration
$config = [
    'DELIMITER_LEFT' => '{',
    'DELIMITER_RIGHT' => '}',
];
$odt = new Odf("invoice_template.odt", $config);

// Insert a company logo
$odt->setImage('company_logo', 'path/to/logo.png');

// Create a repeatable segment for line items
$lineItems = $odt->setSegment('invoice_items');
foreach ($invoiceData['items'] as $item) {
    $lineItems->setVars('item_name', $item->name);
    $lineItems->setVars('item_price', number_format($item->price, 2));
    $lineItems->setVars('item_quantity', $item->quantity);
    $lineItems->merge();
}

// Set summary variables
$odt->setVars('total_amount', number_format($invoiceData['total'], 2));
$odt->setVars('invoice_number', $invoiceData['number']);

// Save the completed invoice
$odt->saveToDisk('invoice.odt');

Custom Properties

You can update custom document properties in your ODT file using the updateCustomProperty() method:

$odf->updateCustomProperty('Author', 'John Doe');
$odf->updateCustomProperty('Version', '1.0');

Important notes about custom properties:

  • It's recommended to use only strings for custom properties. The reason is that the value will be replaced by odtphp, but the value is supposed to be in the internal format as defined by odt for that particular type. Odtphp only replaces the value of the custom property, odtphp will not do data conversions.
  • For dates e.g., make sure to use YYYY-MM-DD as format as that is what ODT wants as internal date format.
  • Special characters will be HTML encoded by default.
  • Properties must exist in the document before they can be set.
  • Setting custom properties works when using LibreOffice/OpenOffice only. It seems to fail using Microsoft Word as Microsoft Word does not update the custom property values upon opening an ODT file.
  • Newlines are not supported in custom property values because the LibreOffice GUI does not allow newlines. updateCustomProperty() will happily insert newlines and the newlines will also be outputted, but this "unofficial" functionality which may be blocked in the future by ODT.

Examples:

// Basic string properties
$odf->updateCustomProperty('Author', 'John Doe');
$odf->updateCustomProperty('Department', 'Engineering');

// Dates should use YYYY-MM-DD format
$odf->updateCustomProperty('Creation Date', '2024-01-20');

// Special characters are encoded by default
$odf->updateCustomProperty('Note', '<important> & urgent');  // Will be encoded
$odf->updateCustomProperty('Note', '<important> & urgent', FALSE);  // Won't be encoded

Images

You can insert images into your ODT file using different measurement units:

// Using centimeters (original function)
$odf->setImage('logo', 'path/to/logo.png', -1, 5, 7.5);  // 5cm width, 7.5cm height
$odf->setImage('photo', 'path/to/photo.jpg', 1, 10, 15, 2, 2);  // On page 1 with 2cm offsets

// Using millimeters
$odf->setImageMm('logo', 'path/to/logo.png', -1, 50, 75);  // 50mm width, 75mm height
$odf->setImageMm('photo', 'path/to/photo.jpg', 1, 100, 150, 20, 20);  // On page 1 with 20mm offsets

// Using pixels (automatically converts to mm)
$odf->setImagePixel('logo', 'path/to/logo.png', -1, 189, 283);  // 189px ≈ 5cm, 283px ≈ 7.5cm
$odf->setImagePixel('photo', 'path/to/photo.jpg', 1, 378, 567, 76, 76);  // On page 1 with 76px offsets

// Keep original image size
$odf->setImage('icon1', 'path/to/icon.png');  // Will convert to cm
$odf->setImageMm('icon2', 'path/to/icon.png');  // Will convert to mm
$odf->setImagePixel('icon3', 'path/to/icon.png');  // Will keep original pixel dimensions

Parameters for all image functions:

  • $key: Name of the variable in the template
  • $value: Path to the image file
  • $page: Page number (-1 for as-char anchoring)
  • $width: Width in respective units (null to keep the aspect ratio, or the original size when $height is also null)
  • $height: Height in respective units (null to keep the aspect ratio, or the original size when $width is also null)
  • $offsetX: Horizontal offset (ignored if $page is -1)
  • $offsetY: Vertical offset (ignored if $page is -1)

Each image file gets one name in Pictures/ of the document. Two different files with the same name (a/logo.png and b/logo.png) are saved as logo.png and logo-2.png, and a new image never replaces a picture of the template.

Note: While setImagePixel accepts measurements in pixels, the ODT format requires millimeters or centimeters internally. The function automatically converts pixel measurements to the appropriate format.

Error Handling

<?php
use Odtphp\Odf;
use Odtphp\Exceptions\OdfException;

try {
    $odt = new Odf("template.odt");
    
    // This will throw an exception if the variable doesn't exist
    $odt->setVars('non_existent_variable', 'Some Value');
} catch (OdfException $e) {
    // Handle template-related errors
    error_log("ODT Processing Error: " . $e->getMessage());
}

Testing

  1. Install dependencies:
composer install
  1. Run the tests:

On Linux:

# Go to the root of odtphp, then:
./run-tests.sh

On Windows:

# Go to the root of odtphp, then:
run-tests.bat

# Note that depending on your PHP installation you may have to edit the
# script to include the path to php.exe

You can also run the PHPUnit tests e.g. in PHPStorm, but you have to exclude the vendor directory to avoid warnings about the PHPUnit framework itself.

Testing Against Multiple PHP Versions

run-tests-multi-php.sh runs the test suite inside Docker containers for one or more PHP versions. Docker must be installed and running.

# Test all supported versions (8.1, 8.2, 8.3, 8.4)
./run-tests-multi-php.sh

# Test a single version
./run-tests-multi-php.sh 8.1

# Test several specific versions
./run-tests-multi-php.sh 8.2 8.4

# Force a rebuild of the Docker test images (e.g. after a PHP release)
./run-tests-multi-php.sh --rebuild

# Pass extra arguments through to PHPUnit
./run-tests-multi-php.sh -- --display-deprecations
./run-tests-multi-php.sh 8.3 -- --testdox

Docker images are built once per PHP version and cached locally as odtphp-test:phpX.Y, so subsequent runs are fast. Each container runs composer update to resolve packages that are compatible with the PHP version under test, which ensures the correct dependency versions are used across the full supported range (PHP 8.1 through 8.5+).

Test Structure

The test suite covers various aspects of the ODT templating functionality:

  1. Basic Tests (Basic1Test.php and Basic2Test.php):

    • Verify basic variable substitution in ODT templates
    • Test both PhpZip and PclZip ZIP handling methods
    • Demonstrate simple text replacement and encoding
  2. Configuration Tests (ConfigTest.php):

    • Validate configuration handling
    • Test custom delimiters
    • Check error handling for invalid configurations
  3. Edge Case Tests (EdgeCaseTest.php):

    • Handle complex scenarios like:
      • Large variable substitution
      • Nested segment merging
      • Special character encoding
      • Advanced image insertion
      • Invalid template handling
  4. Image Tests (ImageTest.php):

    • Verify image insertion functionality
    • Test image resizing
    • Check error handling for invalid image paths
  5. Variable Tests (VariableTest.php):

    • Test variable existence checks
    • Verify special character handling
    • Check multiline text substitution
  6. Custom Property Test (SetCustomPropertyTest.php):

    • Test custom propertyfunctionality

Each test is designed to ensure the robustness and reliability of the ODT templating library across different use cases and configurations.

A lot of tests run twice:

  • Once using PclZip library
  • Once using PHP's native Zip extension

The tests generate ODT files and compare them with gold standard files located in:

  • tests/src/files/gold_phpzip/ - Gold files for PHP Zip tests
  • tests/src/files/gold_pclzip/ - Gold files for PclZip tests

Linting

On Linux:

# Go to the root of odtphp, then:
composer install
vendor/bin/phpcs --standard="Drupal,DrupalPractice" -n --extensions="php,module,inc,install,test,profile,theme" src

Features

  • Template variable substitution
  • Image insertion and manipulation
  • Segment management for repeatable content
  • Support for custom delimiters
  • Type-safe implementation
  • Modern PHP 8.1+ features

Configuration

$config = [
    'ZIP_PROXY' => \Odtphp\Zip\PhpZipProxy::class, // or PclZipProxy
    'DELIMITER_LEFT' => '{',
    'DELIMITER_RIGHT' => '}',
    'PATH_TO_TMP' => '/tmp'
];

$odt = new Odf("template.odt", $config);

Type Safety

This library is built with PHP 8.1's type system in mind:

  • Strict typing enabled
  • Property type declarations
  • Return type declarations
  • Parameter type hints
  • Improved error handling

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the GPL-3.0 License - see the LICENSE file for details.

The GPL-3.0 license is because of what the cybermonde/odtphp author put it to, I (sboden) don't want to change it. I don't consider odtphp to be "my" software, I only tried to make the cybermonde/odtphp fork work properly in PHP v8.3 and beyond.

Personally (sboden) I would have used an MIT or BSD license for odtphp, but I will happily abide with the original author's intent.

The original version/source code of odtphp is at https://sourceforge. net/projects/odtphp/. The cybermonde/odtphp fork I started from is at https://github. com/cybermonde/odtphp.

Usage justification

How and why we use odtphp in our projects.

Some of our projects send out letters (either PDF or on physical paper) to people: the idea is to have a nice template, fill in some data, create a PDF file from the filled-in template, and send the resulting PDF to the recipient.

The template is an ODT file, the data is stored in a database. We use odtphp to fill in the template. The filled-in ODT file is then transformed into a PDF file using (originally) jodconverter, and in newer projects gotenberg.dev (which is essentially "jodconverter in golang"). The PDF converters run in a different container than the main applications.

The reason for using gotenberg over jodconverter is that gotenberg is better supported. Main problem with gotenberg is the quantity of PDFs. In a customised jodconverter we run multiple threads at the same time in one docker container to generate about 50,000 PDFs daily (10K per hour); with gotenberg you would have to run multiple docker containers to generate those the same amount of PDFs in the same timespan.

Why not generate PDFs directly from PHP? We tried, but it's difficult to have nice-looking PDFs using the existing PHP libraries. One PHP library has problems with images, another PHP PDF library faces issues with margins and headers/footers, ... We tried a lot of different setups and finally settled for odtphp/gotenberg to have the PDF output "pixel perfect".

Technical informations

Why do my variables sometimes not get filled in?

Because LibreOffice adds metadata to text that you change. E.g. when you have something as follows in your ODT file:

{variable_text}

And you make a small change to the previous text it may very well end up as:

{variable<text:span text:style-name="T4">s</text:span>_text}]

where you don't see the "text:span" part visually, but it is there.

odtphp repairs the variables and segment markers that are split by <text:span>, <text:bookmark> and <text:soft-page-break/> when it opens the template: the markup is moved after the tag. Other markup in a tag still prevents the match.

How to get around that: When you change variable texts, select the variable text (including the begin and end delimiters), copy it, and then use "Paste special/Paste unformatted text" to copy the text in the same place without any invisible metadata.

Variables vs Custom Properties

ODT files support two different ways to insert dynamic content: variables and custom properties.

Variables

Variables are an ODTPhp feature that works by replacing text anchors (like {variable_name}) with new content:

$odf->setVars('company_name', 'ACME Corporation');
$odf->setImage('logo', 'path/to/logo.png', -1, 50, 75);  // 50mm width, 75mm height

Key points about variables:

  • Variables are specific to ODTPhp, variables are not a feature of the ODT specification
  • Work as simple text replacements in the document
  • Support images through setImage, setImageMm, and setImagePixel functions
  • Can be affected by LibreOffice's invisible metadata when editing the template (see previous topic)
  • Must be surrounded by delimiters (default: { and })
  • Can be used anywhere in the document text

Custom Properties

Custom properties are an official ODT feature for storing (usually) metadata about the document:

$odf->updateCustomProperty('Author', 'John Doe');
$odf->updateCustomProperty('Version', '1.0');

Key points about custom properties:

  • Official ODT feature supported by all ODT-compatible software
  • Stored in the document's meta.xml file
  • Not affected by LibreOffice's invisible metadata
  • Must exist in the document before they can be set
  • Cannot be used with image functions
  • Must be created through the LibreOffice GUI (File > Properties > Custom Properties)

When to use which:

  • Use variables for:

    • Any text content in the document body
    • Images and other media
    • Dynamic content that needs formatting
    • Repeatable segments
  • Use custom properties for:

    • Small single line text fields: name, address line 1, address line2, postal code, city, ...

Why does "Catégorie 1" sometimes appear as "Catégorie 1" in the output?

Usually this is a double-encoding problem. When UTF-8 text is encoded again as UTF-8, special characters like 'é' can appear as 'é'. This typically
happens when the text is already in UTF-8 but gets encoded again.

While setting variables you can specify the encoding as needed, e.g. as:

$categorie->setVars('TitreCategorie', 'Catégorie 1', true, 'UTF-8');

The default charset has changed?

One of the "major" changes I made is to put UTF-8 as the default charset when setting variables. Before the default was ISO-8859-1, but UTF-8 currently makes more sense to me.

I always recommend using UTF-8 internally within the application and handling encoding/decoding at the boundaries.

How do I upgrade from v1/v2 to v3?

While it is a breaking change, as long as you only use odtphp and don't use any of its internals you should be fine by just upgrading the odtphp library to v3.

If you inherit from Odf or you use some internal things in the odtphp library, then all bets are off.

History

The odtphp project was initially started by Julien Pauli, Olivier Booklage, Vincent Brouté and published at http://www.odtphp.com (the website no longer exists).

As DXC Technology working for the Flemish government we started using the cybermonde/odtphp fork (source) in a couple of projects to fill in template ODT files with data, then transforming the filled-in ODT to PDF using gotenberg. We ran into a couple of problems with the cybermonde/odtphp library for which it was easier to just create my own fork, hence sboden/odtphp: we sometimes generate 50,000 forms daily, and cybermonde/odtphp would occasionally overwrite outputs when processing a lot of ODT files simultaneously (because of non-random random numbers).

Why do I try to keep this "corpse" alive? Simply because I found no replacement for it. The projects I work that use odtphp are now (= end 2024) on PHP 8.2 moving to PHP 8.3, and some pieces of the original odtphp library are starting to spew warnings. During my 2024 Christmas holidays I was writing some unit test cases for odtphp, and while testing the AI tool "Windsurf", I tried to have Windsurf automatically update odtphp to a newer PHP version, and sboden/odtphp v3 is the result of that (after some extra manual human changes).

While this fork sboden/odtphp is not officially supported, maintenance and bug fixes are provided on a best-effort basis. The sboden/odtphp library is actively used in production applications with planned lifecycles extending to at least 2030.

This software is not by DXC Technology, else it would have been called dxc/odtphp. This software is not by the Flemish government, else it would probably have been called vo/odtphp. I have always worked on odtphp during my personal time.

Upgrade plan

From v3.x to v4.0.0

If you only use sboden/odtphp and don't poke around in its internal structures, you should be fine simply replacing v3 with v4. The main reason for introducing v4 is that you have to consciously do the upgrade, and you have to test.

Quick upgrade checklist:

  1. Update the constraint in your composer.json to "sboden/odtphp": "^4.0" and run composer update sboden/odtphp.
  2. Replace every direct read of $segment->manifestVars with $segment->getManifestVars().
  3. Replace calls to setCustomProperty() with updateCustomProperty() (the old name still works, but it is deprecated).
  4. If your code reads the temporary ODT file between calls, call saveToDisk() first: updateCustomProperty() no longer writes to the file directly.
  5. If you extend Odf or Segment, read "Subclassers only" below.
  6. Generate your documents with your own templates and compare the output with the v3 output.

The full list of changes follows.

Breaking changes — action required:

  1. Segment::$manifestVars is now protected. In v3 this property was public, so direct reads like $segment->manifestVars will cause a fatal error. Replace with the new getter:

    // v3
    foreach ($segment->manifestVars as $val) { … }
    // v4
    foreach ($segment->getManifestVars() as $val) { … }
  2. setCustomProperty() is now deferred, like all other setters. In v3 it wrote the change directly to the ZIP file on every call. In v4 the change is held in memory and flushed to disk when you call saveToDisk() or exportAsAttachedFile() — consistent with setVars(), setImage(), and all other setters. Code that relied on the immediate side-effect (e.g. inspecting the tmpfile between calls) must now save first.

  3. Image path handling changed for paths without a directory separator. setImage(), setImageMm(), and setImagePixel() now use basename() / pathinfo() instead of strrchr() / strtok(). Paths like "logo.png" (no /) now work correctly; paths with a slash produce identical results.

Non-breaking changes worth knowing:

  • setVars() and setVariable() formally declare string|null $value. Passing null with encoding enabled yields an empty string, unchanged from v3.
  • setVars($key, null, false) — passing null with $encode=FALSE now also coerces to an empty string in both Odf::setVars and Segment::setVars instead of throwing a TypeError. Previously only the encoding path handled null correctly.
  • setImagePixel() width/height are declared float|null (were untyped). Passing float pixel counts like 188.97 now works without a TypeError.
  • getConfig() return type corrected to mixed (was incorrectly string). It still returns false for unknown keys — callers checking === false are unaffected.
  • Image MIME types in META-INF/manifest.xml now come from the image content (getimagesize()), not from the file extension: photo.jpg is declared as image/jpeg (was image/jpg), and images without an extension work.
  • Manifest image entries are now inserted before the closing manifest tag, with the namespace prefix of the template's manifest (manifest: or another one). If the manifest has no closing tag, saving throws an OdfException (before, the images were silently not declared).
  • Two image files with the same name no longer overwrite each other in Pictures/: the second one is saved as name-2.ext. A new image never replaces a picture of the template.
  • When only the width or only the height of an image is given, the other one keeps the aspect ratio (before, the XML got an empty size such as svg:height="cm"). For page anchoring, a null offset is now 0.
  • Odf::setImage() accepts floats for the width, the height and the offsets (int|float|null, was int|null).
  • The setImage*() methods check that the variable exists before they register the image, so a failed call no longer leaves an unused image in the document.
  • Variables and segment markers that LibreOffice splits with <text:span>, bookmarks or soft page breaks are repaired when the template is opened (new class Odtphp\TemplateCleaner).
  • A template without meta.xml can be opened (meta.xml is optional in ODF). customPropertyExists() returns false and updateCustomProperty() throws an OdfException for such a template.
  • Segments are no longer read from an HTML-decoded copy of the content XML, so &amp;amp; or &amp;lt; in the static text of a segment stays escaped (before, the merged XML could be malformed). A segment name that is written with HTML entities in the template no longer matches.

Correctness fixes:

  • setCustomProperty() and customPropertyExists() now use DOMDocument + XPath to locate <meta:user-defined> elements. The previous regex required meta:name to appear in a specific position among the element's attributes; attribute ordering is no longer significant.
  • Calling saveToDisk() or exportAsAttachedFile() more than once on the same Odf instance no longer produces duplicate image entries in META-INF/manifest.xml. saveInternal() now works from a local copy of the manifest XML so $this->manifestXml is never mutated.
  • exportAsAttachedFile() now sends an RFC 5987 filename*=UTF-8''… header alongside the ASCII filename="" fallback. Filenames that contain accented characters, spaces, or other non-ASCII content are transmitted correctly to modern browsers; legacy clients still receive the sanitised ASCII name.
  • setImage(), setImageMm(), and setImagePixel() (in both Odf and Segment) no longer suppress PHP warnings with @ when calling getimagesize(). Errors now surface through normal PHP error-handling channels; the failing path is included in the OdfException message.

Performance improvements (transparent):

  • moveRowSegments() rewired to a single preg_replace_callback pass — was a nested preg_match_all + per-row preg_match loop.
  • Segment image files are batch-added inside saveInternal() instead of opening and closing the ZIP archive on every merge() call.

Subclassers only:

  • Segment no longer has a $file (ZIP handler) property; remove any references to it in subclasses.
  • All Segment properties ($xml, $xmlParsed, $name, $children, $vars, $manifestVars, $images) are now fully typed — subclasses that redeclare them must use compatible types.
  • Segment::$odf is now declared protected Odf $odf instead of the untyped protected $odf. Subclasses that redeclare the property must use Odf or a compatible type.
  • Segment::__construct() now enforces string $name, string $xml, Odf $odf. Any call that previously relied on implicit type coercion for these parameters will now raise a TypeError.
  • Odf::initializeProperties() removed (was dead code duplicating property defaults already set at declaration).

New tooling:

  • Dockerfile.test and run-tests-multi-php.sh added for running the test suite against PHP 8.1 – 8.6 via Docker without changing the host environment.

Deprecations (soft — still callable, removed in a future version):

  • setCustomProperty() renamed to updateCustomProperty(). setCustomProperty() is kept as a deprecated pass-through alias and will be removed in a future release. Update call sites now:

    // deprecated
    $odf->setCustomProperty('Author', 'John Doe');
    // use instead
    $odf->updateCustomProperty('Author', 'John Doe');

    The rename makes the semantics explicit: the property must already exist in the document — it is updated, not created.

  • Odf::mergeAndValidateConfig() replaced by mergeConfig(). This is a private method, so it only affects subclasses that called it via reflection. The new mergeConfig() uses array_replace() rather than a manual foreach loop and drops the misleading "validate" label (actual validation still happens in validateTemporaryDirectory() and validateZipProxy()). mergeAndValidateConfig() now delegates to mergeConfig() and carries a @deprecated tag; remove any reflection-based calls that target it.

From v3.0.3 to v3.2.0

There should be no issues upgrading; only new functionality and small bugfixes were added.

Version History

  • v4.0.0 - 01Dec2026: Code quality, correctness, and performance pass, including a null-safe Odf::recursiveHtmlspecialchars() (see upgrade plan above for the full change list)
  • v3.2.0 - 24Mar2025: Introduction of customPropertyExists()
  • v3.1.0 - 21Mar2025: Introduction of functions setCustomProperty()/setImageMm()/setImagePixel()
  • v3.0.3 - 29Dec2024: Odtphp version for PHP 8.x
  • v2.2.1 - 07Dec2022: Parallel processing by odtphp does not overwrite outputs

Disclaimer

This software is provided "as is" without warranty of any kind, either expressed or implied. The entire risk as to the quality and performance of the software is with you.

In no event will the authors, contributors, or licensors be liable for any damages, including but not limited to, direct, indirect, special, incidental, or consequential damages arising out of the use or inability to use this software, even if advised of the possibility of such damage.

By using this software, you acknowledge that you have read this disclaimer, understand it, and agree to be bound by its terms.

Links:

About

Generate Open Document Text-files from PHP code

Resources

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages