OpenTBS - create OpenOffice and Ms Office documents with PHP

version 1.12.1, 2024-03-06 by Skrol29
help file modified on 2024-03-06
  1. Introduction
  2. Installing
  3. Understanding principles
  4. Synopsis and code examples
  5. Demo
  6. Debugging your template
  7. What to do if Zlib extension is not enabled with PHP?
  8. License

1. Introduction

OpenTBS is a plug-in for the TinyButStrong Template Engine.

TinyButStrong is a PHP Template Engine which has special template syntax and allows you to design templates in their natural editing tools. But it normally works only for Text files, including XML and HTML.

With TinyButStrong and its plug-in OpenTBS, you can use the template engine to merge OpenOffice documents and Ms Office documents with lot of facilities. All OpenDocument Format (ODF) and Office Open XML (OOXML) can be merged with OpenTBS, and also XPS files (XPS is a PDF competitor provided by Microsoft). In fact, all zip archives containing Xml/Html/Text files can be merged with OpenTBS.

Since version 1.10.0, OpenTBS can also read data in workbooks (xlsx and ods files).

What is special to OpenTBS:

You should know Template Engines and more specifically TinyButStrong to use OpenTBS.

2. Installing

Requirements:
Installation:

Just put the file "tbs_plugin_opentbs.php" with your PHP scripts.

3. Understanding principles

It is important to figure out that documents made with LibreOffice, OpenOffice and Ms Office (since version 2007) are technically zip archives containing XML files, even if the extension of the document is not ".zip". Those zip archives can contain other file types like pictures or sounds, but the document structure and the text contents are saved as XML files. The XML Synopsis summarizes the key entities of XML sub-files contained in LibreOffice, OpenOffice and Ms Office documents.

TinyButStrong can merge XML files, but cannot read zip archives by itself. The plug-in OpenTBS extends the TinyButStrong methods LoadTemplate() and Show() to make them working with zip archives. But you do not have to bother with it because OpenTBS is managing archives in a way that is quite invisible for you.

When the OpenTBS plugin is installed, the LoadTemplate() method becomes able to first load a zip archive (a LibreOffice, OpenOffice or Ms Office document), and then to load the contents of any XML or Text files stored in the archive. Then you can load an merge the contents of XML or Text files with all features of the TinyButStrong template engine. TBS can merge fields and blocks only for the current loaded sub-file, but OpenTBS make you very easy to manage sub-files and gives lot of facilities for special contents such as pictures, charts, ... . At the end, the Show() method does render the entire zip archive including modified stored files. The render can be done as an HTTP download, or a new file on the server's disk, or as a PHP string containg the binary of the result archive.

Since OpenTBS version 1.3, you can also add and delete files in the archive.

OpenTBS has automatic extension recognition. When you load a document which has one of the following extensions { odt, odg, ods, odf, odp, odm, docx, xlsx, pptx }, then the main XML file of the archive are automatically loaded, and some special character conversion are preset. For example, for all OpenDocument files, the stored file "content.xml" is automatically loaded.

Since version 1.6.0, if the extension is not recognized then OpenTBS also try to find the document by the sub-file presence. And if all fails, then you can force the document type using a special command.

4. Synopsis and code examples

4.1. Preparation of TinyButStrong Template Engine with the OpenTBS plug-in

include_once('tbs_class.php');
include_once('tbs_plugin_opentbs.php');

$TBS = new clsTinyButStrong;
$TBS->Plugin(TBS_INSTALL, OPENTBS_PLUGIN);
Or, with an autoloader :
$TBS = new clsTinyButStrong;
$TBS->Plugin(TBS_INSTALL, 'clsOpenTBS');

4.2. Method LoadTemplate()

• Load an archive with the automatic extension recognition (explained above):

$TBS->LoadTemplate('document.odt'); // Load the archive 'document.odt'.
$TBS->LoadTemplate('document.odt', OPENTBS_ALREADY_UTF8); // Load the archive and tells that the PHP script and merged data are already UTF8.

• Load an archive without the automatic extension recognition:

(supported since OpenTBS version 1.1)
$TBS->LoadTemplate('document.odt#');

• Load an archive with a PHP file handle:

(supported since OpenTBS version 1.8.1)
$handle = tmpfile();
fwrite($handle, $binary_contents);
$TBS->LoadTemplate($handle);

• Load an archive and one file stored in this archive:

$TBS->LoadTemplate('document.odt#content.xml');

• Load an archive and several files stored in this archive:

$TBS->LoadTemplate('document.odt#content.xml;settings.xml');

• Unload the current template, so the template file is no longer locked:

(supported since OpenTBS version 1.9.5)
$TBS->LoadTemplate(false);

• Load a stored file from the current archive:

See command OPENTBS_SELECT_FILE.

• Load an archive with special data conversion:

(supported since OpenTBS version 1.3.2)
$TBS->LoadTemplate('document.odt', OPENTBS_ALREADY_UTF8);

OpenTBS manages XML files that are UTF8 encoded. But by default, it assumes that all the data to merge (which can come from PHP or SQL) is Ascii encoded, and thus it performs conversions. If you want to define the data conversion, then you can use one of the following constants:

Please note that if you need to change the data conversion for one or few fields only in your template, then you can use parameter "htmlconv" (see the TBS documentation for more details).

4.3. Method Show()

Render options for OpenTBS:

• Render the merged archive as an HTTP download: ($file_name is optional)

$TBS->Show(OPENTBS_DOWNLOAD, $file_name);

• Render the merged archive as an HTTP output with your customized HTTP headers:

header(...); // your custom headers here
$TBS->Show(OPENTBS_DOWNLOAD + OPENTBS_NOHEADER); // output the binary file without header

• Render the merged archive as a new file saved on the server's disk:

$TBS->Show(OPENTBS_FILE, $file_name);

• Render the merged archive as a PHP string:

(supported since OpenTBS version 1.1)
$TBS->Show(OPENTBS_STRING);
$string = $TBS->Source;

When you use OPENTBS_STRING then there is no output for the client. But instead, the binary source of the archive is placed into property $TBS->Source. This feature can be useful, for example, when you want to place the merged document into an email as an attached file.

4.4. Block alias

Block Alias are supported since OpenTBS version 1.8.0, they can work only with TBS 3.8.0 or higher.

The Block Alias are wrappers for defining TBS blocks on usual Libre Office and Ms Office entities. This helps to not referring directly to XML entities and to harmonize block definitions between types of documents. For example: you can use block=tbs:row instead of block=table:table-row.

Some Block Alias, such as tbs:page and tbs:section, are also defining an entity that you cannot have with normal XML entities.

Block alias available according to the type of document :
Alias Desciption LibreOffice Ms Office
Writer
(odt)
Calc
(ods)
Impress
(odp)
Word
(docx)
Excel
(xlsx)
PowerPoint
(pptx)
tbs:p A paragraph. yes no yes yes no yes
tbs:title A title. yes no yes yes no yes
tbs:section A section of text. yes no no yes (*) no no
tbs:table A table inserted in the document. yes a sheet yes yes no yes
tbs:row A row of a table. yes yes yes yes yes yes
tbs:cell A cell of a table. yes yes yes no yes yes
tbs:comment A comment. yes yes yes no no no
tbs:page A page defined by an explicit page break before a paragraph.(*) yes no no yes (*) no no
tbs:slide A slide. no no yes no no no
tbs:sheet A worksheet. a table yes no no no no
tbs:draw A single draw, or set of draws (Ms Word) yes yes yes yes yes yes
tbs:drawgroup A group of draws. yes yes yes yes yes yes
tbs:drawitem A single draw item among a set of items. yes yes yes yes yes yes
tbs:listitem An item of a bullet list. yes no yes yes no yes
Notes (*)

4.5. Change or read data of series in a chart

Change series in a chart:

(supported since OpenTBS version 1.6.0, for Ms Word and Ms Powerpoint, since version 1.8.0 for LibreOffice)
Example: $TBS->PlugIn(OPENTBS_CHART, $ChartRef, $SeriesNameOrNum, $NewValues, $NewLegend=false)

This command changes the values of a series in a Chart of the document. The chart will be automatically actualized when the merged document is opened because OpenTBS also breaks the link between the chart and its cached view. It can also delete or rename the series in the chart.

The result is true if the series is modified with success, otherwise the result is false.

Argument Description

$ChartRef

The reference to find the chart. This value can be either:

  • The name of a field placed anywhere in the Alternative Text property of the frame that embeds the chart. (supported since OpenTBS 1.10.4).
    This name must be unique for charts in the entire document.
    For example: $ChartRef = 'my_chart' is corresponding to the field [my_chart] placed in the Alt Text property.
    The property Alt Text of the frame that embeds the chart is available in both Ms Office and LibreOffice.
    In Ms Office you can retrieve this property from the contextual menu of the frame, and choose Alt. Text....
    In LibreOffice you can retrieve this property from the contextual menu of the frame, and choose Description..., or sometimes Properties... in Writer.
  • The order number of the chart in the document (first is number 1).
  • Deprecated: $ChartRef can aslo be exactly the property title of frame that embeds the chart (supported since OpenTBS 1.8.0).
    Note: In Ms Office, this property is no more available since Ms Office 2019.
    Note: In LibreOffice this property can sometimes be captioned "Alternative - text only" in Writer.

You can use the command OPENTBS_DEBUG_INFO in order to view all charts in the document that OpenTBS can manage.
You can use the command OPENTBS_CHART_INFO in order to read data in the chart.

Deprecated since version 1.8.0: in previous version, $ChartRef could be the internal name of the XML file that contains the chart definition, with or without the extension. Such as 'chart1'.

$SeriesNumOrName

Exact caption of the series in the chart, or its number (first is number 1). Typically 'Series 1' or 1.

$NewValues

The new data of the series. Must be an array, or value false if you want to delete the series.

The array can store data with 3 possibilities:

Structure #1: $NewValues = array( array('cat1', 'cat2', 'cat3', ...), array(val1, val2, val3, ...) );

Structure #2: $NewValues = array('cat1'=>val1, 'cat2'=>val2, 'cat3'=>val3, ...);

Structure #3: $NewValues = array( array(x1, y1), array(x2,y2), array(x3, y3), ...);

Notes :

  • A chart may have some values missing for one series and not for others. You can define a missing value for a category using PHP values null, 'NULL', false or '' (empty string).
  • Structure #3 is supported only for LibreOffice, and is required when the chart type is XY (Scatter), Bubble or Stock. Use 2 values in each items for XY, 3 for Bubble, and 4 for Stock.
  • Structure #1 is required for Ms Office when the chart type is XY (Scatter). Bubble and Stock are not yet supported for Ms Office.

$NewLegend

Optional. The new caption of the series.

Please note:

Charts in worksheets (DOCX and ODS files) are supported since OpenTBS version 1.9.12.

Before version OpenTBS 1.9.12, the visual Data Editor in Ms Office softwares (Excel, Word, Powerpoint) becomes unavailable on a merged chart.

Delete a category in a chart:

(supported since OpenTBS version 1.9.11)
Example: $ok = $TBS->PlugIn(OPENTBS_CHART_DELETE_CATEGORY, $ChartRef, $Categories, $NoErr = false)

This command delete one or several categories in the chart. It returns true if succeed.

Argument $Categories can be either the name of a single category, an array of names, or the keyword '*' wich mean all categories.

By default an error occurs if one of the searched categories is not found in the chart. But if your set argument $NoErr to true then the function returns false and no error occurs.

Array of names and the keyword '*' are supported since OpenTBS version 1.9.12.

Read series in a chart:

(supported since OpenTBS version 1.9.5)
Example: $info = $TBS->PlugIn(OPENTBS_CHART_INFO, $ChartRef, $Complete=false)

This command returns information about all series in the chart.

The result is an associative array whose structure depends on argument $Complete.

Argument Description

$ChartRef

The reference to find the chart. Same as OPENTBS_CHART.

$Complete

If $Complete = false, the command returns a simple list of all series and theirs corresponding data with structue #1 described in OPENTBS_CHART.

// Example :
array (
  'Series 1' => array(
      0 => array (0 => 'Category A', 1 => 'Category B', 2 => 'Category C'),
      1 => array (0 => '2', 1 => '2.1', 2 => false,),
  ),
  'Series 2' => array(
      0 => array (0 => 'Category A', 1 => 'Category B', 2 => 'Category C',),
      1 => array (0 => '7', 1 => '7.1', 2 => '6.9',),
  ),
  ...
); 

If $Complete = true, the command return an array with information about subfiles, and also all the series (name, categories, values) in a different structure.

// Example :
array (
  'file_idx' => 17,
  'file_name' => 'Object 1/content.xml',
  'parent_idx' => 19,
  'parent_name' => 'content.xml',
  'series' => array (
    0 => array (
      'name' => 'Series 1',
      'cat' => array (0 => 'Category A', 1 => 'Category B', 2 => 'Category C',),
      'val' => array (0 => '2', 1 => '2.1', 2 => false,),
    ),
    1 => array (
      'name' => 'Series 2',
      'cat' => array (0 => 'Category A', 1 => 'Category B', 2 => 'Category C',),
      'val' => array (0 => '7', 1 => '7.1', 2 =>'6.9',),
    ),
  ...
); 

4.6. Change pictures in the document

• Change an internal picture with a new one:

(supported since OpenTBS version 1.4.0, for OpenOffice and MsOffice documents only)
Example: [onshow.x;ope=changepic]

In the example above, $x is a PHP global variable containing the name of an external picture file (relative or absolute path). Of course you can use this feature on TBS fields merged with MergeBlock().

When a TBS field having "ope=changepic" is merged in the template, then OpenTBS will search the first picture located before the field (see parameter tagpos below for another position), and then it will change the picture assuming that the value of the field is the path for a picture file on the server. You don't have to care about loading the picture file in the document, OpenTBS will manage this for you.

Note that parameter "ope=changepic" is a feature provided by the OpenTBS plug-in, which extends the "ope" parameter natively present with TBS.

Instead of change a picture with a TBS tag, you can also do it manually at the PHP side using the command OPENTBS_CHANGE_PICTURE.

Known limitations:

Options:

In order to simplify your coding, they are other complementary optional parameters:

Parameter Description
tagpos

Supported values are "after", "before" and "inside". This option indicates the position of the TBS tag relativelly to the target picture.

The default value is "after", it means that the TBS tag (the one with "ope=changepic") must be placed after the picture.

You can use "tagpos=inside" when you put the TBS field in the Description or Title of the image (LibreOffice/OpenOffice or Ms Office).

  • This option won't work if you put the TBS tag inside the property Name of an image in LibreOffice/OpenOffice.
  • In Ms Word 2007, property Description and Title are supported but not available for editing, but you can use "Alternative text" (in the "Web" tab of the Size dialog box) , ot the URL, or the Toolipt of a Link on the image.
  • In Ms Excel, you must use "tagpos=inside" because pictures are not saved in the sheet, they are not positioned relativelly to cells.

Parameter tagpos is supported since OpenTBS version 1.8.0. Previsouly the TBS tag had to be placed after the picture.

adjust

Adjust the size of the picture in the document. This parameter requires that PHP is configured with the GD extension, which is usually the case.

Values can be on of the followings:

adjust (or adjust=inside) The picture is adjusted to enter into the picture bounds of the template.
adjust=samewidth The picture is adjusted to have the same width than the picture of the template.
adjust=sameheigth The picture is adjusted to have the same height than the picture of the template.
adjust=100% (or another pourcentage) The picture is adjusted to be proportional to the originial size.

Parameter adjust is supported since OpenTBS version 1.7.0.

unique

Indicate to OpenTBS that the original picture is unique in the template and can be deleted. This actually saves size of the final document.
The value of argument unique can be omitted. If the value is 1 or ommited, then the original picture is deleted from the template.

If the original picture is in fact displayed somewhere else in the template, that may produce a missing picture.

Parameter unique is supported since OpenTBS version 1.9.1.

from

This option reformulates the path of the new picture to insert. The parameter's value can contain the [val] keyword or any [var] fields, they work the same way as with parameter "file".

Example: [onshow.x;ope=changepic;from='../pic/[val].gif']
as

This option reformulates the name of the picture that it will take inside the document. It is rare to need it, but it can help in some cases. Note that the external picture file is not renamed. The new name must be defined without path. The parameter's value can contain the [val] keyword or any [var] fields, they work the same way as with parameter "file".

Example: [onshow.x;ope=changepic;as='[val].gif']
default

This option defines the picture that should be used when the expected one is not found. The parameter's value must be the path of a file on the server, or the keyword "current".
If the value is "current" then OpenTBS will let the current picture of the template if the new picture is not found.

Since OpenTBS version 1.8.0 the default value is "current". In prior versions, there was no default value and an OpenTBS error message was prompted if the new image was not found.

4.7. Delete or merge columns in a table

4.7.1 Delete columns in a table

Parameter "ope=delcol" enables you to delete specified columns in a table in an Ms Word document (docx) or any LibreOffice document.

Limitations of parameter "ope=delcol" :

You have to put a TBS field anywhere inside the table with the following parameters:

ope=delcol activate the deletion feature
colnum=...

(ignored if colset is defined) define the column numbers to delete. By default, this parameter is the merged value.
It can be :

  • a number (first column is number 1)
  • a range (tow columns numbers separated with '-')
  • a list of numbers or ranges separated with coma (,)

Both parameters "colnum" and "colshift" can contain [val] and [var] fields. Unfortunaltely parameter "ope" is processed before parametre "if", so the merged value must be directly the colums to delete.

colshift=... (optional, ignored if colset is defined) if parameter colnum has only one value then parameter colshift extends the number of columns to delete to the left (if positive) or to the right (if negative).
colset=...

Define several set of columns, seperated with pipe (|). When this parameters is used, then OpenTBS wil delete the set of columns corresponding to the merged value.

If a column number to delete is empty (''), or zero (0), or negative, or over the actual number of colmun int the table, then the value is ignored whitout raising error.

Examples:

Example Description

[onshow.col_to_delete;ope=delcol]

if $col_to_delete = 3, then it will delete columns 3.
if $col_to_delete = array(5,8), then it will delete columns 5,8.
if $col_to_delete = '5,8', then it will delete columns 5,8.
if $col_to_delete = '5-8', then it will delete columns 5,6,7,8.
if $col_to_delete = '1,3,5-8', then it will delete columns 1,3,5,6,7,8.
if $col_to_delete = 0, then it will delete no columns.
if $col_to_delete = '', then it will delete no columns.

[onshow.col_to_delete;ope=delcol;colshift=2]

if $col_to_delete = 3, then it will delete columns 3, 4, 5.
if $col_to_delete = 0, then it will delete no columns.

[onshow.set_to_delete;ope=delcol;colset=3]

if $set_to_delete = 1, then it will delete columns 3 (that is set #1).

[onshow.set_to_delete;ope=delcol;colset=3-5]

if $set_to_delete = 1, then it will delete columns 3 to 5 (that is set #1).

[onshow.set_to_delete;ope=delcol;colset=3,5]

if $set_to_delete = 1, then it will delete columns 3 and 5 (that is set #1).

[onshow.set_to_delete;ope=delcol;colset=1,7-10|4,5,6]

if $set_to_delete = 1, then it will delete columns 1,7,8,9,10 (that is set #1).
if $set_to_delete = 2, then it will delete columns 4,5,6 (that is set #2).
if $set_to_delete = 0, then it will delete no columns.
if $set_to_delete = array(1,2), then it will delete columns of set #1 and #2.

Parameter "ope=delcol" is supported since OpenTBS version 1.8.0.
Parameter "colset" is supported since OpenTBS version 1.10.0.
Parameter "colnum" is optional since OpenTBS version 1.10.0.

4.7.2 Merge dynamic columns in a table

Parameter "parallel=tbs:table" enables you to create dynamic columns in a table of an Ms Word Document or any LibreOffice document.

Limitations:

See the TBS manual and the OpenTBS demo for more details about how to use parameter "parallel".

Parameter "parallel=tbs:table" is supported since OpenTBS version 1.8.2.

4.8. Merge cells vertically

Parameter "ope=mergecell" enables you to merge cells vertically in a table of an Ms Word Document.

Limitations:

Parameter "ope=mergecell" can work only for a block merged on the rows of the table. Note that the TBS field with "ope=mergecell" does not display any value, it only produces the merge.

Example:

Parameter "ope=mergecell" is supported since OpenTBS version 1.8.0.

4.9. Merging data in spreadsheet cells

In speaksheets (Ms Excel or LibreOffice Calc), cells values may be formated but also typed. For example, a cell value may be typed as String, Numerical, Boolean or Date.

Unfortunately, as soon as you enter a TBS tag in a cell, the cell it is typed as String by the software. This may not be corresponding to the final value you wanted after the merging.

For those situations, TBS offers a parameter like "ope=cellType". The cell type will be changed during the merging and the merged value will be implicitly converted by TBS to fit to the expected type.

Example:
Parameters for merging data in spreadsheet cells:
Expected Cell Type Parameter Note
Number ope=tbs:num  
Boolean ope=tbs:bool  
Date/time ope=tbs:date  
Time only ope=tbs:time For XLSX, it's an alias of ope=tbs:date
Currency ope=tbs:curr

For XLSX, it's an alias of ope=tbs:num

Percentage ope=tbs:percent For XLSX, it's an alias of ope=tbs:num

The keywoks in the table above are supported since OpenTBS version 1.8.1.

In previous version you should use keywords: odsNum, odsBool, odsDate, odsTime, odsCurr, odsPercent, xlsxNum, xlsxBool and xlsxDate.

4.10. Read and write ranges in a worksheet

• Read a range in a worksheet

(supported since OpenTBS version 1.10.0)
Example: $result = $TBS->PlugIn(OPENTBS_GET_CELLS, $RangeRef, $Options = array())

This command returns an array containg all of the cell's values in a range of the workbook.

Empty cells will have a NULL value.

Cells with a formula will have the last value cached by the editor software (Calc or Excel).

The reading is limited to the actual range of data in the sheet, not the theorical rows and colmuns in the range. For example, reading the range ''A:C' (which has theorically an infinit number of rows) will return only 3 rows if there is no more data after the third row.

This command supports merged cells and also full columns and full rows. The result of full columns and full rows will be limited to the explicit data actually stored in the worksheet.

Argument Description

$RangeRef

It must be either :

  • An existing named range in the workbook. It can be a global name, or name local to a worksheet.
  • An absolute range definition. That is a range that include the worksheet name. The range definition must be compatible with the formats (ODS or XLSX). Examples :
    • "$'my_sheet'.$A$2:$D$23"
    • "$'my_sheet'.$A:$D"
    • "$'my_sheet'.$8:$10"
  • A local range definition. That is a range . Example : "A1:D18". In this case the range taken in the worksheet currently selected by OpenTBS.

$Options

  • 'header' (false by default) : indicate that the first row of the range contains the header information and will be used as the columns names for each returned rows.
  • 'columns' (false by default) : an assocaitif array of columns to be renamed. A missing index or a null value means the colum will not be returned in the result.
  • 'noerr' (false by default) : if this option is true and the range cannot be found or read, then the function return false without raising an error.
  • 'del_blank_rows' (false by default) : set this option to 'true' to not return blank rows. Note that blank rows after the last actual row with data are never return anyway.
  • 'row_max' (false by default) : the maximum number of row to return. False means no limit.
  • 'rangeinfo' (false by default) : set this option to true in order to return the debug information about the range definition instead of its data. For debuging purpose.

• Write a range in a worksheet (Will be available in a next version)

4.11. Merge document fields

(Supported since OpenTBS version 1.10.0)

Both DOCX and ODT files supports document fields that can be inserted anywhere in the document that is for example Mail Merge Fields.

In Ms Word, document fields are available using: ribbon Insert / Text / Quick Parts / Field…
In LibreOffice, document fields are available using: menu Insert / Field / Other fields…

For now, OpenTBS can replace only document fields whose type is Conditional.
For a DOCX, that is IF field.
For an ODT, that is Fonction / Conditional text.

When you’ve positioned your Conditional document field in your contents :

When the TBS fields will be merged, the full document field will be deleted and replaced with the merged value.

Limitations of parameter "ope=docfield" :

Example with DOCX:

IF 1 = 0 "[onshow.x_num;ope=docfield;frm=0,000.00]" "XX.XX"

Example with ODT:

Conditional text false [onshow.x_num;ope=docfield;frm=0,000.00] XX.XX

See the demo DOC and ODT for more details.

4.12. Other merging commands

The following commands are supported since OpenTBS version 1.7.0 :

Command Description
For all types of documents  
$TBS->PlugIn(OPENTBS_SELECT_MAIN)

Select and load the main sub-file in the opened template. For example in a Writer document, or an Ms Word document, this command can bring you back from the merging of a header to the main body.

$TBS->PlugIn(OPENTBS_SELECT_FILE, $SubFile)

Select a sub-file in the opened template. Return false if the sub-file is not found. If the sub- file is stored in a subfolder, then indicate the full path. For example: 'word/document.xml'.

Before OpenTBS 1.9.0, selecting a sub-file had to be done using $TBS->LoadTemplate('#' . $SubFile);.

Command OPENTBS_SELECT_FILE is supported since OpenTBS version 1.9.0.

$TBS->PlugIn(OPENTBS_CHANGE_PICTURE, $PicRef, $File [, $Prms])

 

Deprecated:

$TBS->PlugIn(OPENTBS_CHANGE_PICTURE, $PicRef, $File
[, $Default]
[, $Adjust]
)

Does not work with XLSX yet.

Change one or several pictures in the current sub-file. This command does the same as the changepic feature. The difference is that the command needs no TBS tags in the template.

  • $PicRef must be a string that is saved in the Title or the Description of the picture. If several pictures have the same key string then they are all replaced with the picture. It won't work if you put the string reference tag inside the property Name of an image in LibreOffice/OpenOffice. In Ms Word 2007, both properties Description and Title are supported but not available for editing, but you can use "Alternative text" (in the "Web" tab of the Size dialog box) , ot the URL, or the Toolipt of a Link on the image.
  • $File must be path for picture file that will be copied inside the document.
  • $Prms can be an associated array of parameters supported by parameter changepic.

Example:

$prms = array('unique' => true);
$TBS->Plugin(OPENTBS_CHANGE_PICTURE, '#main_map#', 'pics/new_map.png', $prms);

Command OPENTBS_CHANGE_PICTURE is supported since OpenTBS version 1.8.0.
Parameter $Prms is supported since version 1.9.1.
$TBS->PlugIn(OPENTBS_GET_FILES_BY_TYPE, $Types)

Return an array of all sub-files corresponding to the asked types.

$Types must be a string or an array of strings, supported values are:

  • 'main'
  • 'header'
  • 'footer'
  • 'chart'
  • 'comments'
  • 'sheet'
  • 'slide'
  • 'slidem' (for slide master)
  • 'all' (for all above)

// Example
$subfile_lst = $TBS->PlugIn(OPENTBS_GET_FILES_BY_TYPE, ['charts']);

Command OPENTBS_GET_FILES_BY_TYPE is supported since OpenTBS version 1.12.0.
$TBS->PlugIn(OPENTBS_DELETE_COMMENTS)

Delete all usual user comments in the opened template.

$TBS->PlugIn(OPENTBS_DELETE_ELEMENTS, $Elements)

Delete XML elements in the current sub-file.

$Elements must be an array of strings.

For example: $Elements = array('w:bookmarkStart', 'w:bookmarkEnd') This will delete all bookmarks in an Ms Word document.

$TBS->PlugIn(OPENTBS_ADD_CREDIT, $Text [, $Name])

Add a new credit text in the properties of the document.

For LibreOffice/OpenOffice, this will add the text as a new Custom Property of the document. You can use argument $Name for the custom property's name.

For Ms Office, this will add the text in the Author property of the document. You can use argument $Name to specify another XML element for placing the text. Exemple : 'dc:description' will add the text in the Comment property. Take care that using an unsupported value can corrupt the document.

Command OPENTBS_ADD_CREDIT is supported since OpenTBS version 1.9.1.

$TBS->PlugIn(OPENTBS_SYSTEM_CREDIT, $Enable)

Enable or disable the System Credit. System Credit add the current version of OpenTBS into a creator property of the document. The System Credit is enabled by default.

Command OPENTBS_SYSTEM_CREDIT is supported since OpenTBS version 1.9.1.

$TBS->PlugIn(OPENTBS_READ_ENTITY, $SubFile
, $ElPath, $Att)

Retrieve an attribute's value or an entity's value in the first element in a given sub-file. Return the asked value, or false if the attribute or the entity is not found. Also retrurn false if an entity’s value is asked while the entity is a self-closed tag.

  • $SubFile (string|boolean): the name or the index of the sub-file. Use value false to get the current sub-file.
  • $ElPath (string): path of the element. For example : 'w:document/w:body/w:p'. Sub-entities are optional but can remove ambiguities.
  • $Att (string|boolean): the attribute, or false to replace the entity's value.

Command OPENTBS_READ_ENTITY is supported since OpenTBS version 1.10.3.

$TBS->PlugIn(OPENTBS_EDIT_ENTITY, $SubFile
, $ElPath, $Att, $NewVal, $AddElIfMissing = false)

Change an attribute's value or an entity's value in the first element in a given sub-file. Return true if the attribute is found and processed, false otherwise.

  • $SubFile (string|boolean): the name or the index of the sub-file. Use value false to get the current sub-file.
  • $ElPath (string): path of the element. For example : 'w:document/w:body/w:p'. Sub-entities are optional but can remove ambiguities.
  • $Att (string|boolean): the attribute, or false to replace the entity's value.
  • $NewVal (string|boolean): the new value, or false to delete the attribute.

Command OPENTBS_EDIT_ENTITY is supported since OpenTBS version 1.9.5.

For documents (ODT and DOCX)  
$TBS->PlugIn(OPENTBS_SELECT_HEADER, [$Type[, $Offset])
$TBS->PlugIn(OPENTBS_SELECT_FOOTER, [$Type[, $Offset])

Select the sub-file corresponding to the header of the footer. Return true if succeed, false if it fails.

For LibreOffice/OpenOffice, headers and footer are saved in the same sub-file. For ODS and ODP, the sub-file containing headers and footer is the main file.

For XLSX and PPTX this command will always return false because headers and footers are saved in sheets or slides.

For DOCX, they may have several headers or footers in the same document. Eeach section can have its own set of typed header and footer :
  • a default header (or footer)
  • an optional header (or footer) for the first page of the section
  • an optional header (or footer) for even pages of the section

In order to select a specific header or footer, you have to use the arguments $Type and $Offset.

  • $Type can be : OPENTBS_DEFAULT (default value), OPENTBS_FIRST, or OPENTBS_EVEN.
  • $Offset (default value is 0) is used to select the typed header or footer of another section.

If you wan to select all the sections of the document, then see command OPENTBS_GET_HEADERS_FOOTERS.

Command OPENTBS_SELECT_HEADER and OPENTBS_SELECT_FOOTER are supported since OpenTBS version 1.9.0.

$TBS->PlugIn(OPENTBS_GET_HEADERS_FOOTERS)

Return an array of all sub-files that are headers and footers of the document.

See also command OPENTBS_GET_FILES_BY_TYPE.

// Example
$subfile_lst = $TBS->PlugIn(OPENTBS_GET_HEADERS_FOOTERS);
foreach ($subfile_lst as $subfile) {
  $TBS->PlugIn(OPENTBS_SELECT_FILE, $subfile);
  $TBS->MergeField('f', $info);
}

Command OPENTBS_GET_HEADERS_FOOTERS is supported since OpenTBS version 1.9.0.

For workbooks (ODS and XLSX)  
$TBS->PlugIn(OPENTBS_SELECT_SHEET, $NumOrName [, $ById])

Select the sub-file corresponding to $NumOrName. This command will raise an error if the opened template is not an expected document.

This command is useless for LibreOffice/OpenOffice because all sheets/slides are all saved in the main sub-file. Nevertheless using it will select the main sub-file without raising an error.

$NumOrName is an identifier that can be either an integer corresponding to the number of the sheet in the sheet list (first is number 1), or a string corresponding to the name of the sheet.

Use command $TBS->PlugIn(OPENTBS_DEBUG_INFO) to list all id and name of sheets/slides in the current document.

Use command $TBS->PlugIn(OPENTBS_COUNT_SHEETS) get the number of sheets in the workbook.

$ById is false by default, set it to true if you want to select the sheet by its internal ID instead of its number in the sheet list. This can be used for compatibility with previous OpenTBS vesions (see version history below).

Command OPENTBS_SELECT_SHEET is supported since OpenTBS version 1.8.0.
Argument $ById is supported since OpenTBS version 1.9.6.
Before OpenTBS version 1.9.6, the sheet was not find by its number in the sheet list but only by its internal id, which may be different.

$TBS->PlugIn(OPENTBS_DISPLAY_SHEETS, $NumOrNames[, $Visible])

Make one or several sheets/slides visible or hidden. This command will raise an error if the opened template is not an expected document.

  • $NumOrNames must be an array of identifiers, or even a single identifier. See command OPENTBS_SELECT_SHEET for more details about identifiers.
  • $Visible must be a boolean, default value is true.

Command OPENTBS_DISPLAY_SHEETS is supported since OpenTBS version 1.8.0.
Before OpenTBS version 1.9.6, the sheet was not selected by its number in the sheet list but only by its internal id, which may be different.

$TBS->PlugIn(OPENTBS_DELETE_SHEETS, $NumOrNames[, $Delete])

Make one or several sheets te be deleted or not. This command will raise an error if the opened template is not a Workbook.

  • $NumOrNames must be an array of identifiers, or even a single identifier. See command OPENTBS_SELECT_SHEET for more details about identifiers.
  • $Delete must be a boolean, default value is true.

Please note that for now, you must not delete a sheet that contains a Pivot Table in a XLSX workbook because this will produce an error when the workbook is opened.

Command OPENTBS_DELETE_SHEETS is supported since OpenTBS version 1.8.0.
Before OpenTBS version 1.9.6, the sheet was not find by its number in the sheet list but only by its internal id, which may be different.

$TBS->PlugIn(OPENTBS_COUNT_SHEETS)

Return the number of sheets in the workbook. Always return 0 if the document is neither an XLSX nor an ODS.

Command OPENTBS_COUNT_SHEETS is supported since OpenTBS version 1.9.1.

$TBS->PlugIn(OPENTBS_MERGE_SPECIAL_ITEMS)

Merge special items relatively to the current sub-file. For now, it has effect only with Ms Excel workbooks. This command makes automatic fields ([onload] and [onshow]) merged in pictures embedded in the current selected sheet. This can be useful for changing pictures in Ms Excel.

Command OPENTBS_MERGE_SPECIAL_ITEMS is supported since OpenTBS version 1.8.0.

$TBS->PlugIn(OPENTBS_RELATIVE_CELLS, $Enabled[, $Options])

This command may significatively optimize time generation for XLSX workbooks that contains sheets with large numerous rows. By default the Ms Excel software saves sheets with explicit cells positioning, and OpenTBS has the same behavior by default. This operation may be quite slowing OpenTBS for sheets with large numerous rows. In another hand saving sheets with relative cells positioning is quite faster and the final file may be smaller. Use this command in order to define the saving behavior about cells.

  • $Enabled set to true in order to activate the relative cells positioning for the current sheet only.
  • $Options set to OPENTBS_ALL in order to apply the command to all sheets in the current workbook.

This command has no effects for other documents type than XLSX workbooks.

Command OPENTBS_RELATIVE_CELLS is supported since OpenTBS version 1.9.2.

For presentations (ODP and PPTX)  
$TBS->PlugIn(OPENTBS_SELECT_SLIDE, $NumOrName[, $Master])

Same as command OPENTBS_SELECT_SHEET but for slides.

$Master is a boolean to indicate if you want to select a master slide in the document. Default value is false.

Command OPENTBS_SELECT_SLIDE is supported since OpenTBS version 1.8.0.
Argument $Master is supported since OpenTBS version 1.9.0.

$TBS->PlugIn(OPENTBS_DISPLAY_SLIDES, $NumOrNames[, $Visible])

Same as command OPENTBS_DISPLAY_SHEET but for slides.

$TBS->PlugIn(OPENTBS_DELETE_SLIDES, $NumOrNames[, $Delete])

Same as command OPENTBS_DELETE_SHEETS but for slides.

$TBS->PlugIn(OPENTBS_COUNT_SLIDES[, $Master])

Return the number of slides in the presentation. Always return 0 if the document is neither a PPTX nor an ODP.

$Master is a boolean to indicate if you want to count master slides in the document. Default value is false.

Command OPENTBS_COUNT_SLIDES is supported since OpenTBS version 1.8.0.
Argument $Master is supported since OpenTBS version 1.9.0.

$TBS->PlugIn(OPENTBS_SEARCH_IN_SLIDES, $Str[, $Options])

Search for the string $Str trough the slides of the current document. Return the id of the first slide where the string is found. Return false if the string is not found.

$Options must be a combination of the following constants. Default value is OPENTBS_FIRST.

  • OPENTBS_FIRST : stop the search at the first slide where the string is found.
  • OPENTBS_GO : select the corresponding slide if the string is found.
  • OPENTBS_ALL : search through all slides and return an array of the slide ids.

This command is useless for LibreOffice/OpenOffice because all slides are all saved in the main sub-file. Nevertheless using will not raise an error.

Command OPENTBS_SEARCH_IN_SLIDES is supported since OpenTBS version 1.9.0.

4.13. Manage files in the archive

• Get all files in the archive:

$TBS->Plugin(OPENTBS_GET_FILES)

Return the list of all files in the archive.

See also command OPENTBS_GET_FILES_BY_TYPE.

(supported since OpenTBS version 1.9.7)

 

 

 

 

 

• Get all files in the archive:

$TBS->Plugin(OPENTBS_GET_OPENED_FILES)

Return the list of all files in the archive that has been already loaded for a TBS merge. This includes all files that you manually loaded using command OPENTBS_SELECT_FILE, but also all files loaded automatically by OpenTBS such as the main file, or modified charts, or sometimes headers and footers. Some technical files that are modified by OpenTBS in back-end but cannot contain TBS fields (such as manifest files or relation files) are not returned by this command.

(supported since OpenTBS version 1.9.11)

• Get all files in the archive:

$TBS->Plugin(OPENTBS_WALK_OPENED_FILES, $callable)

Apply a user supplied function to every file in the archive that has been already loaded for a TBS merge (see command OPENTBS_GET_OPENED_FILES).

Argument $callable must be a callable function with one or two arguments: the editable content of the file being the first, and file's name the second.

// Example:
$user_func = array($my_object, 'translate');
$TBS->Plugin(OPENTBS_WALK_OPENED_FILES, $user_func);
(supported since OpenTBS version 1.9.11)

• Check if a file does exists in the archive:

$TBS->Plugin(OPENTBS_FILEEXISTS, $Name)

Return true or false. $Name must include the inner path. For example : $Name = 'META-INF/manifest.xml';

(supported since OpenTBS version 1.7.4)

• Add any new file in the archive:

// OpenTBS >= 1.6.0
$TBS->Plugin(OPENTBS_ADDFILE, $Name, $Data, $DataType=OPENTBS_STRING, $Compress=true);

// Deprecated since OpenTBS 1.6.0
$TBS->Plugin(OPENTBS_PLUGIN, OPENTBS_ADDFILE, $Name, $Data, $DataType=OPENTBS_STRING, $Compress=true);  

If $Data is false then the previously add file with the given name is canceled if any.

$DataType must be OPENTBS_STRING if $Data is the content to add ; it must be OPENTBS_FILE if $Data is the path of the external file to insert.

$Compress can be true, false or an array with keys ('meth','len_u','crc32') which means that the data is already previously compressed.

(supported since OpenTBS version 1.3)

• Replace an existing file in the archive:

$TBS->Plugin(OPENTBS_REPLACEFILE, $Name, $Data, $DataType=OPENTBS_STRING, $Compress=true);

The arguments are the same as command OPENTBS_ADDFILE.

Please note that any TBS merge on a file in the archive will cancel previous or future replacements.

(supported since OpenTBS version 1.7.4)

• Delete an existing file in the archive:

// OpenTBS >= 1.6.0
$TBS->Plugin(OPENTBS_DELETEFILE, $Name);

// Deprecated since OpenTBS 1.6.0
$TBS->Plugin(OPENTBS_PLUGIN, OPENTBS_DELETEFILE, $Name);

Delete the existing file in the archive, or a file previously added using the OPENTBS_ADDFILE command.

(supported since OpenTBS version 1.3)

• Reset all modifications in the archive:

// OpenTBS >= 1.6.0
$TBS->Plugin(OPENTBS_RESET);

// Deprecated since OpenTBS 1.6.0
$TBS->Plugin(OPENTBS_PLUGIN, OPENTBS_RESET);

The automatic extension recognition is also applied as it was applied for the first load of the archive.

4.14. Special options

Dealing with apostrophes:

Both OpenOffice and Ms Office may automatically convert single quotes (') into typographic apostrophes (’), depending to the auto-correction options. This may be annoying when you need to code a TBS fields that have a single quote. That's why OpenTBS automatically convert by default all (’) back to single quotes (') in documents.

If you want to stop this conversion, you can set $TBS->OtbsConvertApostrophes = false; and no apostrophes will be converted. Note that you can avoid the auto-correction of single quotes (') in Ms Word using keys[ctrl]+[z], and in OpenOffice using the cancel button.

Property OtbsConvertApostrophes is supported since OpenTBS version 1.6.0.

•Make an optimized version of a template:

Some template can be long to load because OpenTBS has to cleanup or prepare somes sub-files. There is a command that save a template as a new template file which is already prepared for OpenTBS, thus loading it will be faster.

$TBS->Plugin(OPENTBS_MAKE_OPTIMIZED_TEMPLATE, $template, $new_template);

This command is supported since OpenTBS version 1.9.8.

• Forcing the document type recognition:

You can force the document type recognition using command OPENTBS_FORCE_DOCTYPE. Example:

$TBS->PlugIn(OPENTBS_FORCE_DOCTYPE, 'docx');

This command is supported since OpenTBS version 1.6.0.

• Retrieving the name of the current document:

Property $TBS->tbsCurrFile indicates the name of the current file loaded from the archive. The value is false if no file is loaded yet from the archive.

Other TinyButStrong methods and properties stay unchanged and are available for merging your template.

(supported since OpenTBS version 1.1)

5. Demo

The OpenTBS package includes a full set of runnable templates. Some templates can contain useful complementary information for designing.

You can test the demo at the web site: OpenTBS demo

6. Debugging your template

Since OpenTBS version 1.6.0, there are several commands for debugging. Please note that those commands do not exit the process.

Command Desciption
$TBS->PlugIn(OPENTBS_DEBUG_INFO [, $Exit]) Display technical information about the current loaded template, including sheet information if the template is a workbook, and chart information if the template have some.
$Exit must be a boolean, default value is true.
$TBS->PlugIn(OPENTBS_DEBUG_XML_CURRENT [, $Exit]) Display XML contents of sub-files already opened and modified for merging. XML is indented in order to improve reading.
$Exit must be a boolean, default value is true.
$TBS->PlugIn(OPENTBS_DEBUG_XML_SHOW) Ends the merge process as if the final document was created. But instead of creating the document, displays the XML contents of sub-files modified for merging. XML is indented in order to improve reading.

There is also deprecated debug options:

Command Desciption
$TBS->Show(OPENTBS_DEBUG_XML) Does the same as $TBS->PlugIn(OPENTBS_DEBUG_XML_SHOW);Supported since OpenTBS version 1.3.2.
$TBS->Show(OPENTBS_DEBUG_XML+OPENTBS_DEBUG_AVOIDAUTOFIELDS) Avoid merging of [onload], [onshow] and [var].Supported since OpenTBS version 1.3.2.
$TBS->Render = OPENTBS_DEBUG_AVOIDAUTOFIELDS; Work also in property Render.Supported since OpenTBS version 1.3.2.
$TBS->PlugIn(OPENTBS_DEBUG_CHART_LIST) Does the same as $TBS->PlugIn(OPENTBS_DEBUG_INFO);Supported since OpenTBS version 1.6.0.

Otherwise, here are some indications that may help for the issues you can met with merging:

a) The merged document is producing error messages when opened with its application (OpenOffice or Ms Office)

The most likely causes are:

• You've chosen the OPENTBS_DOWNLOAD render option but a php error message or any other unexpected content has been output before by PHP.

Activate the debug mode using the command OPENTBS_DEBUG_XML_SHOW, it helps to check PHP error message and other unexpected content.

• The merging has produced an invalid document or an invalid XML content in an XML file of the document.

Activate the debug mode using it helps to check the XML contents of merged files.

See section (b) below for more information in the XML structure of the files.

b) Some TBS tags are not merged

First be sure that the TBS tag is a in a part of the document which is loaded and selected. Since a sub-file is loaded, automatic block ([onload] and [onshow]) will be merged. And you need to have the sub-file selected in order to use MergeBlock() and MergeField() on it. See commands like OPENTBS_SELECT_*. For example, in Ms Word , header and footers are loaded, and the main document is loaded and selected, but your need to select back a header part in order to use MergeBlock() on it.

Then, it may happens that a TBS tag seems uniformly formatted, while in fact the inner XML is split because of small difference in format, small different spelling information, or other... In order to avoid inner split, you can select the TBS tags, then cut it, and then paste it back without formatting.  It is “Paste special / Unformatted text” in LibreOffice, or “Paste / Keep Text Only” is Ms Office.

For MS Word, you can also use “OpenTBS plug-in for Microsoft Word”, which is given with the standard OpenTBS package. This plug-in gives a tag cleaner tool.

c) The merged document is well opened by its application (OpenOffice or Ms Office) but the content is not designed as expected

First, you can have a look the demo templates, they contain examples and advices for each type of document.

And to go further: even if you can edit your template using directly OpenOffice or Ms Office, you will probably need to understand the XML tags and attributes to complete your merge. The file xml_synopsis.txt is a small synopsis of the XML structure you can found in the inner source of those documents. Have a look to it if you feel lost.

d) Go deeper in the debugging

You can view the inner source of a document using a zip software like 7-Zip. It allows you to open an archive even if the extension is not ".zip".

7. What to do if Zlib extension is not enabled with PHP?

OpenTBS uses Zlib functions in order to automatically uncompress and recompress files stored in the zip archive. If Zlib is not enabled, then you have to use your own uncompress/compress tool, or to prepare the template to have files uncompressed in the zip archive.

Example to uncompress the "content.xml" file in an ODT document using 7-Zip:

  1. open the ODT file with 7-Zip,
  2. extract the "content.xml" file from the ODT file in the same folder than the ODT file,
  3. close 7-Zip,
  4. open 7-Zip, and change current directory to be the same as the ODT file
  5. select the "content.xml" file and click on button [Add], or menu [File][7-Zip][Add to archive...],
  6. a new window named "Add to archive" is opened,
    • replace the archive name with the ODT file name,
    • set the Compression level to "None",
  7. click on [Ok].

If you re-open the ODT file with 7-Zip, you can notice that the size and the uncompressed size are the same.
If the file should be placed in a sub-folder of the archive, then open the archive and rename the file in order to move it in a folder. For example rename "manifest.xml" to "META-INF\manifest.xml" will move it into META-INF. But moving the file will no delete the one which has the same name in the target folder. You have to go and delete the old one.

8. License

OpenTBS is under LGPL (Lesser General Public License)