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:

  1. Create them via the documentFragment method.
  2. Populate the document fragment with elements in exactly the same way you will do with a standard document.
  3. 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:

 * This sample script inserts a simple document fragment within a table cell
require_once 'pathToDOCXPRESSO/';
$doc = new Docxpresso\CreateDocument();
$format = '.pdf';//.pdf, .doc, .docx, .odt, .rtf
//create a document fragment
$fragment = $doc->documentFragment();
            ->text(array('text' => 'A simple chunk of text with a '))
            ->link(array('url' => '', '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')) 
            ->cell($cellStyle)->paragraph(array('text' => 'First cell'))
//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>';         

DOWNLOAD:download pdfdownload docdownload docxdownload odtdownload rtf

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.