Giter Club home page Giter Club logo

php-stamp's Introduction

PHPStamp

PHPStamp is a simple templating engine for XML-based Microsoft Word documents.
Library aims to provide native XML-way of templating for DOCX documents as an alternative to treating its content as a plain text for regex replacing, which has a lot of downsides.
Instead it tries to clean messy WYSIWYG-generated code and create reusable XSL stylesheet from document.

Some additional information:
(EN) https://redd.it/30conp
(RU) https://habr.com/ru/articles/244421/

Features

  • Caching XSL template to filesystem for fast document render.
  • Track document mode - generate and cache new template if original document was updated.
  • Configurable brackets for placeholder tags.
  • Basic extension system, which helps to generate content blocks such as Cells or ListItems.

Known issues

Values inserted into placeholder tags may be highlighted as incorrect by spellcheck, since library removes language attribute and MS Word tries to check it with system language.

Requirements

Library requires PHP 7.4+ with DOM, XSL, Zip extensions.

Installation

Install with Composer:

composer require shadz3rg/php-stamp

Usage

Template:

alt tag

<?php
    require 'vendor/autoload.php';
    
    use PHPStamp\Templator;
    use PHPStamp\Document\WordDocument;
    
    $cachePath = 'path/to/writable/directory/';
    $templator = new Templator($cachePath);
    
    // Enable debug mode to re-generate template with every render call.
    // $templator->debug = true;
    
    // Enable track mode to generate template with every original document change.
    // $templator->trackDocument = true;
    
    $documentPath = 'path/to/document.docx';
    $document = new WordDocument($documentPath);
    
    $values = [
        'library' => 'PHPStamp 0.1',
        'simpleValue' => 'I am simple value',
        'nested' => [
            'firstValue' => 'First child value',
            'secondValue' => 'Second child value'
        ],
        'header' => 'test of a table row',
        'students' => [
            ['id' => 1, 'name' => 'Student 1', 'mark' => '10'],
            ['id' => 2, 'name' => 'Student 2', 'mark' => '4'],
            ['id' => 3, 'name' => 'Student 3', 'mark' => '7']
        ],
        'maxMark' => 10,
        'todo' => [
            'TODO 1',
            'TODO 2',
            'TODO 3'
        ]
    ];
    $result = $templator->render($document, $values);
    
    // Now you can get template result.
    // 1. HTTP Download
    $result->download();
    
    // Or
    // 2. Save to file
    // $saved = $result->save(__DIR__ . '/static', 'Test_Result1.docx');
    // if ($saved === true) {
    //     echo 'Saved!';
    // }
    
    // Or
    // 3. Buffer output
    // echo $result->output();
Result:

alt tag

php-stamp's People

Contributors

duxabilii avatar roquie avatar shadz3rg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-stamp's Issues

Header and footer

It'll be nice to have templating ability in this document sections, isn't it?

Нет возможности настраивать поля при сохранении

Столкнулся с проблемой, что размеры полей у исходного шаблона и выходящего документа различаются. В результате документ "съезжал" и не был похож на исходный.
Можно подумать в сторону либо выставления размеров идентичных исходному шаблону, либо добавить методы для прописывания полей дополнительно.

Не работают списки на никс серверах

Мне разработчик сказал, что "в самом коде также есть со списками небольшая ошибка(будет работать на вин, но не на никс хостинге)". Так и случилось: списки перестали работать когда закинул с локального сервера на хостинг (OS Ubuntu (Linux)). Прошу ответить, что можно сделать, чтобы генерировались списки в шаблоне в том числе на никс серверах?

Custom brackets

Hi, thank you for great lib!
Any ideas why double brackets {{example}} dont work? But single {example} works fine.
$templator = new \PHPStamp\Templator($cachePath, ['{{','}}']);

Release 8.1.21

After the release of PHP 8.1.2, template generation stopped working, gives the following error: Uncaught TypeError: PHPStamp\Templator::searchAndReplace(): Argument #1 ($nodeList) must be of type DOMNodeList, bool given, called in. After a little research, we managed to find out that the problem is in the formation of the template in the file "Processor.php" line "35" $template->appendChild($document->documentElement);
How to solve this problem?

Multiline string: CarriageReturn + LineFeed (CRLF) problem

My docx-Template contains the placeholder [[brief.anschrift]] which should be replaced by a multiline string:

Line 1
Line 2
Line 3
Line 4

The array passed to the $templator->render(...) function looks like this:

$values = array(
    'brief' => array( 'anschrift' => "Line1\r\nLine2\r\nLine 3\r\nLine 4" )
);

As a result, the placeholder [[brief.anschrift]] has been replaced by...

Line1 Line2 Line 3 Line 4

I have also tried several variations with single quotes ', double quotes ", CRLF within code, \r and \n as you can see here:

$values = array(
    'letter' => array(
        'address_1' => "Line1\r\nLine2\r\nLine 3\r\nLine 4"
        , 'address_2' => 'Line1\r\nLine2\r\nLine 3\r\nLine 4'
        , 'address_3' => "Line1
 Line2
 Line 3
 Line 4"
        , 'address_4' => "Line1\rLine2\rLine 3\rLine 4"
        , 'address_5' => "Line1\nLine2\nLine 3\nLine 4"
        , 'address_6' => "Line1<br>Line2<br>Line 3<br>Line 4"
 ));

For testing purposes the docx-Template contains the following placeholders:

image

And this is the result:

image

None of them returns the expected result. Am I missing something?

Question:
How can I pass a multi-line string containing CRLF?

May be publish first 0.1.0 release?

I would like use library without minimum-stability dev. Now, it has been more than 3 years, and it's time that for version.


Давно пора, даже если это прототип :) Композер будет намного удобнее использовать.

Не заполняются дублирующие таблицы

Добрый день! Возникла ситуация когда в одном документе должно быть 2 таблицы с одинаковыми данными, но при генерации почему-то заполняется только одна таблица.

Шаблон:
Аннотация 2019-05-08 162933

Что из него получилось:
Аннотация 2019-05-08 163209

PHPStamp deletes the table

When I try to insert information into a table, PHPStamp deletes the table and inserts just information
in $values
'services' => [ ['service' => $model->provided_services_1, 'price'=>$model->provided_services_1_price] ]

in template
default

ouput
1

What could be the problem? Thanks!

Unexpected token in Lexer

i have document:

[[current_date]]
text text
[[number_test]]
text text
[[пример_тест]]

save in format office open xml (docx) in libre office in .docx ext.
and get error:

Unexpected token, expected PHPStamp\Processor\Lexer::T_DOT, got PHPStamp\Processor\Lexer::T_STRING

how to fix?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.