DocxMustache is a Laravel 11.x package for manipulating DOCX templates using the Mustache templating language. It allows you to merge richly styled Word documents with data from various sources. This package is still under active development, and breaking changes may occur.
With DocxMustache, you can:
- Replace text using Mustache syntax.
- Embed images dynamically.
- Support basic HTML styling (bold, italic, underline).
Install the package via Composer:
composer require wrklst/docxmustache
Refer to the Examples section and the examples
folder for configuration and usage instructions.
Basic HTML conversion is supported, including:
- Bold (
<b>
) - Italic (
<i>
) - Underline (
<u>
)
Limitations:
- Does not support combined styling (e.g., bold + italic).
- Non-HTML values must be escaped using:
htmlspecialchars($value, ENT_COMPAT, 'UTF-8');
Special Note: To prevent unnecessary escaping of HTML, prefix the value with:
*[[DONOTESCAPE]]*
Dynamic image replacement is supported. Follow these steps:
- Add the image URL (reachable and supported format) to the image's alt text description field in the DOCX template.
- Use pseudo-tags around the URL, like so:
[IMG-REPLACE]http://placehold.it/350x150[/IMG-REPLACE]
Note: Images will be resampled to match the constraints of the placeholder image in the template.
To enable DOCX-to-PDF conversion, install libreoffice-common
on your server:
sudo apt install libreoffice-common
For Arial font support, install:
sudo apt-get install ttf-mscorefonts-installer
For Intervention Image, ensure you:
- Add the provider and alias to your app config.
- Install
gd
orimagick
as required (details here).
If you want to port the package to a non-Laravel environment, consider replacing:
- Storage and File Classes: Based on Flysystem, can be replaced with PHP native file handling.
- Process Handling: Uses
\Symfony\Component\Process\Process
for PDF conversion.
Check out the examples
folder for sample templates and usage.
Contributions are welcome! To contribute:
- Fork the repository.
- Create a pull request with your changes.
- Include a corresponding issue for discussion.
We’ll be happy to review and discuss your ideas!
While there are existing libraries for DOCX manipulation, they often:
- Use proprietary or non-standard templating syntaxes.
- Focus on complex feature sets, making them heavyweight for simple use cases.
DocxMustache was designed to:
- Use the widely adopted Mustache syntax.
- Provide simple and intuitive value and image replacement.
- Support repeating content in multiple dimensions.
Here are other popular PHP libraries for DOCX manipulation:
- openTBS – Tiny But Strong
- PHPWord
- docxtemplater pro (MIT licensed; image replacement requires a commercial plugin)
- docxpresso (commercial)
- phpdocx (commercial)