“Word Fragments”: the new PHPDocX paradigm to build sophisticated Word documents
- 02 / 06 / 2013
This post is outdated. For up date information about WordFragments please refer to Practical guide - WordFragments and WordML.
Since v3.0 we have included the notion of Word (or WordML) fragments to simplify the process of creating sophisticated Word documents from scratch.
The idea is conceptually simple: one can create “independent chunks” of content that are not directly included in the Word document but rather “buffered” so they can be easily inserted within other Word elements like tables, lists or paragraphs.
This allows for much greater flexibility because it allows for an unlimited degree of recursivity: you may include images within paragraphs, that are inserted within a table cell that can be itself inserted in the header element of the document.
The coding is also very simple:
one creates, as usual, a Word element with the corresponding PHPDocX code,
captures the output in a variable via the ‘rawWordML’ option set to true,
generates a WordML fragment via the creatWordMLFragment method,
inserts the fragment in, for example, a table cell.
$docx = new CreateDocx();
//We create the paragraph content
$myParagraph = $docx->addText('Simple paragraph', array('rawWordML' => true));
//Generate the corresponding WordML fragment
$fragment = $docx->createWordMLFragment($myParagraph);
//We insert it in the upper right cell of the following table
$tableCells = array(array('1_1', $fragment), array('2_1', '2_2'));
//We finish by generating the Word document
Although this example is very simple (and, in fact, the final result could have been more easily achieved without the use of WordML fragments) it perfectly illustrate the process.
If instead of inserting directly the table we would have used:
$myTable = $docx->addTable($tableCells, array('rawWordML' => true));
$tableFragment = docx->createWordMLFragment($myTable);
The Word contents of $tableFragment could have themselves been inserted within other table cell or wherever considered adequate.
Among the methods currently supporting the rawWordML option we have:
addFormElement (to be released in v3.2)
addStructuredDocumentTag (to be released in v3.2)
The resulting output may be inserted within:
- Headers and footers
- Lists and paragraphs (as inline content)
We can hardly wait to see what you guys can build with all of this!!