Document fragments are used internally by Docxpresso to store a collection of elements (paragraphs, images, tables, etcetera) that may be further manipulated and inserted at will in the flow of its containing document.
Although the majority of users will never have the need to integrate them directly into their code they may become handy in certain cases.
Whenever using document fragments you will always have to do two things:
- Create them via the documentFragment method.
- Populate the document fragment with elements in exactly the same way you will do with a standard document.
- Insert them somewhere within the flow of a document with the help of the insertDocumentFragment method.
Their public APIs are really simple to use and they are described in the following.
How to create a document fragment
The Docxpresso method responsible for the creation of document fragments is the documentFragment method.
public documentFragment ( )
- This method takes no parameters.
How to insert a document fragment
The relevant method in this case is insertDocumentFragment.
Its public API is again extremely simple:
public insertDocumentFragment ($fragment)
- $fragment (type: object). A document fragment previously created with the help of the documentFragment method.
Let us illustrate the process with the help of a sample script:
<?php /** * This sample script inserts a simple document fragment within a table cell */ require_once 'pathToDOCXPRESSO/CreateDocument.inc'; $doc = new DocxpressoCreateDocument(); $format = '.pdf';//.pdf, .doc, .docx, .odt, .rtf //create a document fragment $fragment = $doc->documentFragment(); $fragment->paragraph() ->text(array('text' => 'A simple chunk of text with a ')) ->link(array('url' => 'http://google.com', 'text' => 'link to Google')) ->text(array('text' => '. ')); //create a simple table and insert the fragment within $cellStyle = array('style' => 'border: 1px solid red; padding: 10pt'); $doc->table(array('grid' => array('30%', '70%'), 'style' => 'width: 15cm')) ->row() ->cell($cellStyle)->paragraph(array('text' => 'First cell')) ->cell($cellStyle)->insertDocumentFragment($fragment); //include in the render method the path where you want your document to be saved $doc->render('document_fragment' . $format); //echo a link to the generated document echo 'You may download the generated document from the link below:<br/>'; echo '<a href="' . 'document_fragment' . $format . '">Download document</a>';
The insertDocumentFragment method is smart enough to correctly nest the inserted document elements. If one tries to improperly nest some content like, for example, a table within a paragraph the method will only use the text embedded in the table.