Word Template Engine:
PHP based template processor and converter
Word Template Engine is a PHP based template processor and converter that allows to create documents from DOCX templates (download an example.docx) and convert them trough LibreOffice into the following formats: PDF, HTML, XHTML, mail-adapted HTML. This light-weight library will help you in creating invoices, contracts, waylists and other documents. Use variables inside your document and substitute them with values on the server side, replace and delete images, manage document sections (pages), make a document copy or a section copy inside the document, add rows to your tables. Output the documents to a user browser, attach the WORD or PDF files to emails, or create a HTML mail content from your template.
Changelog
- 1.0.1 : 2021-07-19 : Improved performance of processing large documents. More than 1000 variable replacements take a few seconds. Reduced memory and CPU usage. Speed increased by 6-8 times.
- 1.0.2 : 2021-07-21 : 1) Fixed directory separators caused issues on Windows platform. 2) Generation of unique temporary subdirectory to resolve potential multiuser conflicts.
- 1.0.3 : 2023-04-28 : Fixed broken titles/headers in Safari browser when outputting a file.
Download from GitHub
Installation and usage
Public methods
- __construct ( string $template [, string|null $tmp_path, callable $errorHandler ] )
-
- @param $template The full path to the .docx template.
- @param $tmp_path Optional. The full path to the temporary directory where the working files are created. By default, the site root or a current directory is used.
- @param $errorHandler Optional. A function to replace the default error handler. The callback takes two string parameters: the error description and a unique error status.
The constructor.
- setValue ( string $varName, string|null $replacement ): void
-
- @param $varName The variable name.
- @param $replacement The replacement.
Method to replace a template variable with the $replacement value. A template variable must have the following format: ${name}, where 'name' is passed as the $varName argument.
- cloneRow ( string $varName, int $cnt ): void
-
- @param $varName The anchor variable.
- @param $cnt How many rows you need.
Method to clone a table row with an anchor. An integer counter followed by '#' is appended to the names of all variables inside the row including the anchor.
E.g. you have an anchor variable: ${key} and other variables inside the row: ${customer}, ${order_id}, they are replaced with: ${key#1}, ${customer#1}, ${order_id#1}; ${key#2}, ${customer#2}, ${order_id#2} etc.
- alternativeSyntax ( bool $bool ): void
-
- @param $bool Whether to use alternative variable syntax.
Call this method before replacements to use alternative variable syntax ~(name) instead of default ${name}. You can also switch back to default syntax. Use the alternative syntax to replace the variables inside hyperlinks and other targets.
- replaceImage ( int $imageID, string $replacement ): void
-
- @param $imageID An image id according to the Word enumerator.
- @param $replacement The path of a new image.
Replace an image in the document with another image.
- deleteImage ( int $imageID ): void
-
- @param $imageID An image id according to the Word enumerator.
Completely removes images with a certain id, it deletes both the elements and the file.
- save ( string $destination [, string $format = 'docx' ] ): string
-
- @param $destination The destination path. Can be full or relative, e.g. '/var/www/newdoc.docx', 'newdoc.pdf'. The root of a relative path is the temporary directory.
- @param $format Optional. The document format: 'docx' (default), 'pdf', 'html', 'xhtml', 'mail' (HTML adapted to email).
- @return string The full path to the created document.
Creates a document from the processed template.
- output ( [ string $format = 'docx', string|null $fileName, bool $isAttachment ] ): void
-
- @param $format Optional. The document format: 'docx' (default), 'pdf', 'html', 'xhtml', 'mail' (HTML adapted to email).
- @param $fileName Optional. Defines the filename of downloaded file.
- @param $isAttachment Optional. Forces docx and pdf documents to the certain disposition type: inline or attachment. By default, docx documents are attachments, PDFs are inlines.
Creates a document from the processed template and outputs it to the client browser.
- useSection ( int $idx ): void
-
- @param $idx The section index.
Remove all the sections in the template except the section with an index passed as the argument. This method truncates the document to the certain section.
Note! It must be called before any replacements, because the document paragraphs and rows are cached for better performance.
Note! If you use page breaks inside a section, the next page must begin with a paragraph. Otherwise, the document can be broken. - repeat ( [ int $cnt = 1, int $idx ] ): void
-
- @param $cnt Optional. How many copies are created. Default 1.
- @param $idx Optional. Repeat only one section.
Copy the document one or several times. If the second argument is passed, it creates only a section copy and appends it to the end of the document.
Note! It must be called before or after any replacements, because the document paragraphs and rows are cached for better performance. The call order depends on your document. - dropMetaData ( ): void
-
Drop all core document properties and two extended properties: Company, Manager. After calling this method you have to redefine the document creation time, the title and the document creator; otherwise, the document will be broken.
- setTitle ( string $title ): void
-
- @param $title
Set core document metadata - title. It also displays as the page title in documents opened in a browser: PDF, HTML, XHTML.
- setAuthor ( string $author ): void
-
- @param $author
Set core document metadata - creator. Defines the document creator, clears lastModifiedBy properties.
- setTime ( [ string|null $time ] ): void
-
- @param $time Optional. DateTime in ISO 8601 format. If undefined or null, current DateTime is used.
Set core document metadata - created. Defines the document creation DateTime, clears modified and lastPrinted DateTime properties.
- setCompany ( string $companyName ): void
-
- @param $companyName
Set extended document metadata - Company.
- setManager ( string $manager ): void
-
- @param $manager
Set extended document metadata - Manager.
- setSubject ( string $subject ): void
-
- @param $subject
Set core document metadata - subject.
- setKeywords ( string $keywords ): void
-
- @param $keywords
Set core document metadata - keywords.
- setDescription ( string $description ): void
-
- @param $description
Set core document metadata - description.
- setCategory ( string $category ): void
-
- @param $category
Set core document metadata - category.
- setStatus ( string $contentStatus ): void
-
- @param $contentStatus
Set core document metadata - content status.
- embedStyleSheet ( string $stylesheet ): void
-
- @param $stylesheet
Method to embed a custom stylesheet into the HEAD section of a document that is to be converted into HTML or XHTML format.
- embedScript ( string $script ): void
-
- @param $script
Method to embed a custom script into the HEAD section of a document that is to be converted into HTML or XHTML format.
- addStyleSheet ( string $url ): void
-
- @param $url
Method to append an external stylesheet into the HEAD section of a document that is to be converted into HTML or XHTML format.
- addScript ( string $url ): void
-
- @param $url
Method to append an external script into the HEAD section of a document that is to be converted into HTML or XHTML format.
- sendOutputHeaders ( bool $bool ): void
-
- @param $bool
Call this method with the FALSE parameter before outputting the document if you want to send your own HTTP headers.
- setOutputFilter ( string $filter ): void
-
- @param $filter LibreOffice filter parameter, e.g. 'HTML:EmbedImages'.
If you need to overwrite a default conversion filter, define it before saving / outputting the document.
- setLocale ( string $locale ): void
-
- @param $locale UNIX locale.
The locale that is set before conversion the .docx template into other formats. Default is 'C.UTF-8'.
Additional information
- See more examples in the examples folder of the package.
- Star this project on GitHub: https://github.com/philip-sorokin/word-template-engine.
- Support this project: share it on social networks, write about Word Template Engine in your blog.
- Donate to this project: https://addondev.com/donate.