OODoc::Intro(3pm)
β¨ OpenOffice::OODoc::Intro β¨
okay so this is OODoc::Intro(3pm), from the User Contributed Perl Documentation corner of the manual, and it's the glow-up guide to the Open OpenDocument Connector π«Ά
π NAME π
OpenOffice::OODoc::Intro β Introduction to the Open OpenDocument Connector π
πΈ DESCRIPTION πΈ
okay so the whole point of this intro notice is to let you understand the general principles and learn some basic features of the OODoc module without browsing the entire reference manual. you're welcome, bestie.
the reference manual is a set of separate OpenOffice::OODoc::xxx documents, where xxx is the codename of a particular functional area. the present introduction, as well as the OpenOffice::OODoc main chapter, should be read in order to get the big picture before any attempt to dig in the detailed documentation. periodt.
just before reading this intro, it's a good idea to have a look at the short (and commented) examples provided in the distribution. literally go look at them, they're adorable.
another general introduction to this Perl OpenDocument Connector has been published in The Perl Review (issue #3.1, dec. 2006) β http://www.theperlreview.com
there is an alternative intro for french-reading users π it's available in ODT (http://jean.marie.gouarne.online.fr/doc/oodoc_guide.odt) or PDF (http://jean.marie.gouarne.online.fr/doc/oodoc_guide.pdf). in addition, a general presentation in French can be downloaded at http://jean.marie.gouarne.online.fr/doc/perl_odf_connector.pdf
π Overview π
the main goal of the Open OpenDocument Connector (OODoc) is to allow quick application development in 2 areas:
- replacement of old-style, proprietary, client-based macros for intensive and non-interactive document processing;
- direct read/write operations by enterprise software on office documents, and/or document-driven applications.
OODoc provides an abstraction of the document objects and isolates the programmer from low level XML navigation, UTF8 encoding and file compression details. for example:
use OpenOffice::OODoc;
my $document = odfDocument(file => 'filename.odt');
$document->appendParagraph
(
text => 'Some new text',
style => 'Text body'
);
$document->appendTable("My Table", 6, 4);
$document->cellValue("My Table", 2, 1, "New value");
$document->save;
the script above appends a new paragraph, with given text and style, and a table with 6 lines and 4 columns, to an existing document, then inserts a value at a given position in the table. it takes much less time than the opening of the document with your favourite text processor, and can be executed without any desktop software connection. a program using this library can run without any OpenOffice.org installation (and, practically, OODoc has been tested on platforms where OpenOffice.org is not available yet). slay.
more generally, OpenOffice::OODoc provides a lot of methods (probably most of them are not useful for you, no shade) allowing create/search/update/delete operations with document elements such as:
- ordinary text containers (paragraphs, headings, item lists);
- tables and cells;
- user fields;
- sections;
- images;
- styles;
- bookmarks;
- bibliography entries;
- page layout;
- metadata (i.e. title, subject, and other general properties).
every document processing begins by the initialization of an object abstraction of the document. the most usual constructor for this object is the odfDocument() function. when an object is initialized using this function, it brings a lot of methods allowing the application to retrieve, read, update, delete or create almost every content and style element. another constructor, odfMeta(), is available in order to allow metadata processing (see below). these odfXxx() methods (and others) are shortcuts for
OpenOffice::OODoc::Xxx->new(options)
where "Xxx" is generally "Document", for full access to the content, but may be another specialized object such as "Manifest" or "Meta". the long OpenOffice::OODoc::...->new() syntax can (and should) be avoided, and replaced by the odfDocument(), odfMeta() or odfManitest() functions.
a document object initialization requires one or more options. the most usual option is the file name, as in the first example. by default, this parameter is regarded as a previously existing file. it's possible to instantiate a document object with a new, empty document, with an additional "create" option giving the content class of the document to be generated. so, in our first example, the constructor could be:
my $document = odfDocument
(
file => 'filename.odt',
create => 'text'
);
this instruction creates a new file containing a text (i.e. an OpenDocument Text) document (and replaces any previously existing file with the same name). however, the new file will be actually created by the $document->save instruction, not by the object initialization. if "create" is set, the documents are generated according to ODF templates. by default, OODoc uses a set of templates which are included in the CPAN package, but it's possible to use custom templates instead. β¨
when the 'create' option is in use, the newly created document may be formatted either in the OASIS OpenDocument format (ODF) or in the primary OpenOffice.org 1.0 format. if an additional 'opendocument' is provided and set to 'true', then the new document will be ODF-compliant. if the same option is present and set to 'false', the old OOo 1.0 format will be selected instead. without the 'opendocument' option, the format will depend on the installation default (in the CPAN distribution, the default is set to OpenDocument but it can be changed by the user at the install time). on the other hand, the provided filename is not used by OODoc in order to select the file format, so you are free to create an ODF file with an OOo-like ".sxw" extension, and so on. the only one filename suffix that is meaningful for OODoc is ".xml" (by default, a file whose name is like "*.xml" is processed as flat XML and not as a regular, compressed ODF file).
for existing files, the format (ODF or OOo) is automatically detected according to the real content of the file (whatever the filename). detective mode activated π
the present version of OpenOffice::OODoc is based on the OpenDocument specification, which has been published (May 2005) as an OASIS standard under the following title:
"Open Document Format for Office Applications (OpenDocument) v1.0"
it works with ODF 1.1 and 1.2 documents as well, knowing that these newer versions use the same basic data structure as 1.0, and (hopefully) this library doesn't depend on any particular feature which could be removed from the specification.
π¦ Architecture π¦
the OODoc toolbox is organized in 3 logical layers. it's not necessary for you to remember the (annoying) details given in the next few paragraphs, but these details are described only to explain the general organisation of the modules. if you have only a few dozens of seconds for reading this document, please jump directly at the part III (practical examples) and come back later if you want to know more. no pressure bestie, it's giving skim-friendly
π OpenDocument packaging π
the first layer consists of the OpenOffice::OODoc::File class (defined in the File.pm module). this class is responsible of read/write operations with the ODF physical files. it does every I/O and compression/uncompression processing. it's mainly an easy-to-use, OpenDocument-oriented wrapper for the standard Archive::Zip Perl module (but it could be extended to encapsulate any other physical storage method for the ODF documents).
every physical access to a document through the OpenOffice::OODoc API requires the use of one or more "connectors", each one being associated to an ODF "container". the appropriate constructor is the odfContainer() function, which requires a file name/path as its first (and mandatory) argument:
my $resource = odfContainer("myfile.odt");
the instruction above creates an instance of ODF container, associated to a given filename. the returned object (assuming the specified file exists and is readable) is an OpenOffice::OODoc::File instance, i.e. an abstraction of the ODF physical file. however, it's possible to associate a container with an ODF that doesn't exist yet, provided that an additional 'create' named parameter, whose value is the class of the new document, is set. the following example creates an instance of spreadsheet ODF package:
my $container = odfContainer("accounts.ods", create => 'spreadsheet');
note that no persistent resource is created at this time. without the 'create' option, the odfContainer() function attempts to load the structure of the specified ODF file (and fails if something is wrong). with the 'create' option, the structure is loaded in memory according to default ODF templates that belong to the OpenOffice::OODoc installation. but any persistent change (including the creation of the new ODF file, if any) requires the save() method. as an example, the following code really created a new ODF presentation file (without content):
my $container = odfContainer("show.odp", create => 'presentation');
$container->save;
or, more concisely:
odfContainer("show.odp", create => 'presentation')->save;
so, the most minimalistic OpenOffice::OODoc application is a one-liner that creates an empty document. iconic behavior honestly π
for an existing resource, an open IO::File is allowed instead of a file name.
once initialized, such a container is typically used as a basis to instantiate one or more document-oriented connectors using odfDocument(), introduced later. however, for the users who know exactly what they do, an ODF container brings some low-level methods, such as physical export and/or import of document parts. the next example exports all the named persistent styles of "doc1.odt" then imports them in "doc2.odt":
my $p1 = odfContainer("doc1.odt");
my $p2 = odfContainer("doc2.odt");
$p1->raw_export("styles.xml");
$p2->raw_import("styles.xml");
$p2->save;
β οΈ Caution: there is no consistency check withraw_import(), so the application may ensure that the imported part makes sense according to the remainder of the target container (so, in this example, it may ensure that all the styles needed in the document content are conveniently defined in the imported part). note that theraw_import()method doesn't produce any persistent effect before thesave()method is issued from the importing container. all the changes are lost if the program ends or the objects goes out of scope beforesave(). π
β¨ XML access β¨
Okay so bestie, picture this: the moment an OpenOffice::OODoc::File object gets instantiated using odfContainer(), it's officially available for processing through these document-oriented, XML-based connectors. And here's the tea β a typical OpenOffice::OODoc user genuinely does not need to be "XML-aware". Like, at all. Most applications are gonna use the high-level, XML-free methods that the Document and Meta objects hand over, and those get introduced later. But this section? Lowkey useful for general knowledge of the API, so we're doing it. π«Ά
The second layer is made of the OpenOffice::OODoc::XPath class (XPath.pm), which is an ODF/XML-aware class. Now, this class is generally not directly used by applications β it's mainly a common ancestor for other, more specialised (and way more user-friendly) classes. OpenOffice::OODoc::XPath is an object-oriented representation of an XML part of an OpenDocument file (ex: content.xml, meta.xml, styles.xml, etc.), and it uses the XML::Twig Perl API to access individual XML elements. It serves up an XPath-based syntax for the advanced girlies who want to directly get or set any element or attribute in any part of a document. π
And if you wanna deal with several XML components of the same document at the same time? You can/must create several OpenOffice::OODoc::XPath against the document (ex: one OpenOffice::OODoc::XPath will be associated with 'meta.xml' to represent the metadata, another one will be associated with 'content.xml' to give access to the content). OpenOffice::OODoc::XPath accepts and provides only XML strings from/to the application β but it's able to connect with an OpenOffice::OODoc::File object for file I/O operations, so you can use it without doing any explicit file management coding. Iconic behaviour honestly. β¨
For an example, if you want to get access to the content of any ODF file (say 'foo.odt'), you have to write something like:
use OpenOffice::OODoc;
my $container = odfContainer("foo.odt");
my $doc = odfDocument
(
container => $container,
part => 'content'
);
then $doc becomes an abstraction of the 'content' part of the document (corresponding to the document body and some automatic styles). This new object brings a lot of methods allowing the applications to retrieve, read, modify, delete and creates elements in the documents. She's versatile, okay? π
An element is a consistent piece of content or style definition. Any element may contain a text and/or one or more attributes. As an example, the following example selects a paragraph, then gets its text content and the name of its style:
my $element = $doc->getElement('//text:p', 2);
my $text = $doc->getText($element);
my $style = $doc->getAttribute($element, 'style name');
Note that the getElement() method works with XPath expressions. According to the ODF specification, "text:p" specifies a paragraph. The double slash ("//") means "everything from the root of the document". The second argument of getElement() is the position of the needed element in the list (knowing that "//text:p" designates all the paragraphs); this position is zero-based, so in this example the third paragraph is selected. π
The search space of getElement() is the whole document by default, but it's possible to restrict it to a given context, specified through a additional argument. A context is a particular element, previously selected. As an example, the following code selects the 3rd paragraph in the 4th section (if any):
my $section = $doc->getElement('//text:section', 3);
my $paragraph = $doc->getElement('//text:p', 2, $section);
(Of course, there is a getSection() method that allows you to forget the XPath expression and to retrieve a section by name instead of number.) π
In a real application, the user doesn't need to known such an XPath expression, because there is a more convenient getParagraph() method that just requires the paragraph number. However, the generic, XPath-based getElement() method remains available in order to retrieve any element that is not covered by a specialized accessor. So like, it's the backup dancer that can actually also headline. β
The getText() method is self-documented in the example. The getAttribute() method requires, after the element itself, the name of the attribute whose value is needed. The real ODF name of the style attribute of a paragraph is "text:style-name"; however, the application may use the "style name" simplified form knowing that getAttribute() is able to translate the attribute names according to a simple logic: every space in the given name is replaced by a "-" and, if no prefix is specified, the prefix of the element itself is used, so "style name" is automatically interpreted as "text:style-name" in this particular context. It's giving β¨mind-readingβ¨ but it's just rules.
You don't need to remember the path of such usual objects as paragraphs, headings, lists, images, ..., and other well known document components, because the 3rd layer (see below) provides easy-to-use, predefined accessors for these objects.
The text content and the attributes of a selected element may be changed. The following sequence puts a new text content and affects a new style to our previously selected paragraph:
$doc->setText($element, "A new text content");
$doc->setAttribute($element, 'style name' => "Text Body Style");
The same layer of the API allows one to append of insert new elements. The next example demonstrates the use of appendElement(); it creates a new paragraph with given text and style and appends it to the existing content:
$doc->appendElement(
'text:p',
text => "Hello world",
attributes => {
'style name' => "Text Body Style"
}
);
For those who hate complex instructions, the 3 lines below do the same job as the example above:
my $new_element = $doc->appendElement('text:p');
$doc->setText($new_element, "Hello world");
$doc->setAttribute($new_element, 'style name' => "Text Body Style");
Remember that the changes above are done in the volatile content of document object; up to now; nothing is changed in the corresponding file. In order to commit the changes and make them persistent, we need to call the save() method of the container that has been used to instantiate the document. Don't forget the save bestie, or it literally never happened. π
The API allows the user, in simple situations, to "forget" the ODF container behind the document. The following "hello world" example, that creates and saves a new document, works without explicit use of the odfContainer() constructor:
my $doc = odfDocument(
file => "foo.odt",
create => 'text',
part => 'content'
);
$doc->appendElement(
'text:p',
text => "Hello World !",
attributes => {
'style name' => "Text Body Style"
}
);
$doc->save;
Note that odfDocument() is used here with a 'file' parameter, whose value is a file name, instead of a 'container'. At the end, save() is called from the document instance itself instead of a container. However, a container is always instantiated, but it's just hidden; and save() is only a stub method, the real job being done by the save() method of the container. Such a shortcut is useful in this example because the program processes one part only, i.e. the content; for applications that uses more than one part (content, styles, meta- data), two or more document connectors must be instantiated in association with the same container connector, and, as a consequence, the explicit use of odfContainer() is recommended. π«Ά
OpenOffice::OODoc::XPath allows some quick element manipulation and exchange, and can operate on several documents in the same session. For example:
my $doc1 = odfDocument(file => 'file1.odt', part => 'content');
my $doc2 = odfDocument(file => 'file2.odt', part => 'content');
my $paragraph = $doc1->getElement('//text:p', 15);
$doc2->insertElement
('//text:h', 0, $paragraph, position => 'after');
This sequence takes an arbitrary paragraph (the 16th one) of a document and inserts it immediately after an arbitrary heading (the first one) in another document. Here, we used an insertElement() method to directly transfer an existing text element, but the same method (with different arguments) can create a new element according to application data, or from a well- formed XML string describing any document element in regular Open Document syntax. Example:
# a program
my $doc = odfDocument(file => 'file1.odt', part => 'content');
open MYFILE, "> transfer.xml";
print MYFILE $doc1->exportXMLElement('//text:p', 15);
close MYFILE;
# another program
my $doc2 = odfDocument(file => 'file2.odt', part => 'content');
open MYFILE, "< transfer.xml";
$doc2->insertElement
('//text:h', 0, <MYFILE>, position => 'after');
close MYFILE;
These last two short programs produce the same effect as the preceding one, but the target file can be processed later than the source one and in a different location, because there is no direct link in the two documents. The first program exports an XML description of the selected element, then the second program uses this description to create and insert a new element that is an exact replicate of the exported one. In the meantime, the XML intermediate file can be checked, processed and transmitted with any language and protocol. Multilingual queen. π
The OpenOffice::OODoc::XPath manual page describes a lot more common features that may be used through the document-oriented API introduced below.
But it's just a beginning, because, in the real world, you have to do much more sophisticated processing, and you have not a lot of time to learn the XML path of any kind of document element (paragraph, heading, item list, table, draw frame, style, ...). π
πΈ Document-oriented API πΈ
So there is a third, more user-friendly layer, that should be the only one visible for most of the applications.
The third layer is designed as a set of application-oriented classes, inherited from OpenOffice::OODoc::XPath. In this layer, the basic principle is "allow the user to forget XML". Each document element is considered from the user's point of view, and the XML path to get it is hidden. This approach works only if a specialized OpenOffice::OODoc::XPath class is defined for each kind of content. So, we ultimately need the following classes:
OpenOffice::OODoc::Textβ for the textual content of any document, bestie πOpenOffice::OODoc::Imageβ to deal with the graphic objects, slay β¨OpenOffice::OODoc::Stylesβ for page/style definitions, iconic πOpenOffice::OODoc::Metaβ for the metadata (meta.xml), periodt π
Fortunately, the 3 first ones should not be expressly used in real applications, because the toolbox provides a compound OpenOffice::OODoc::Document class that inherits all their features. So basically, ordinary users just have to deal with OpenOffice::OODoc::Document to process any content (graphic or textual) or layout. An OpenOffice::OODoc::Document object is instantiated through the odfDocument() function, which is a shortcut for OpenOffice::OODoc::Document->new(). For other parts, such as the metadata or the file manifest, other constructors are available. β¨
Simply put, a typical application will need OpenOffice::OODoc::Document in order to process the content and the layout, and OpenOffice::OODoc::Meta for a read/write access to the global properties. π«Ά
However, the reference manual is organized according to the kind of features, in order to avoid a huge manual page for the Document class. As a consequence, the documentation of this compound class includes 4 chapters (::Text, ::Styles, ::Image and ::Document), the last one describing a few transverse methods. In addition, you should remember that all the low-level attributes and methods described in the ::Xpath manual chapter are inherited by both ::Document and ::Meta. π
The OpenOffice::OODoc::Text class brings some table processing methods (table creation, direct access to individual cells). These methods, under some conditions, can be used with spreadsheets (ODF spreadsheet documents) as well as with tables included in text documents. π
To illustrate the differences between the layers, the two following instructions are equivalent:
print $doc->getText('//text:p', 2);
print $doc->getParagraphText(2);
provided that $doc has been previously created through an odfDocument() call. π
The difference looks tiny, but in fact OODoc::Text contains much more sophisticated text-aware methods that avoid a lot of coding and probably a lot of errors. For example, the following code puts the content of an ordinary perl list (@mydata) in an ODF document as a regular item list:
my $list = $doc->appendItemList();
$doc->setText($list, @mydata);
The first instruction creates an empty list at the end of the document body. The second one populates the new list with the content of an application-provided table. The setText() method automatically modifies its behaviour according to the functional type of its first argument (which is not the same for a paragraph as for an itemlist or a table cell). π¦
The same layer provides some global processing methods such as:
my $result = $doc->selectTextContent($filter, \&myFunction);
that produces a double effect:
- it scans the whole document body and extracts the content of every text element matching a given filter expression (that is an exact string or a conventional Perl regular expression);
- it triggers automatically an application-provided function each time a matching content is found; the called function can execute any on-the-fly search/replace/delete operation on the current content and get data from any external database or communication channel; the return value of the function automatically replaces the matching string.
So such a method can be used in sophisticated conditional fusion-transformation scripts. π₯
But you can use the same method to get a flat ASCII export of the whole document, without other processing, if you provide neither filter nor action:
print $doc->getTextContent;
Of course, OODoc can process presentation and not only content. Example:
$filter = 'Dear valued customer';
foreach $element ($doc->selectElementsByContent($filter))
{
$doc->setStyle($element, 'Welcome')
if $element->isParagraph;
}
After this last code sequence, every paragraph containing the string 'Dear valued customer' has the 'Welcome' style (assuming 'Welcome' is a paragraph style, already defined or to be defined in the document). πΈ
A style (like any other document element) can be completely created by program, or imported (directly or through an XML string) from another document. The second way is generally the better because you need a lot of parameters to build a completely new style by program, but the creation of a simple style is not a headache with the OODoc::Styles module, provided that you have an ODF attributes glossary at hand. The following example shows the way to build the "Welcome" style. This piece of code declares "Welcome" as a paragraph style, with "Standard" as parent style, and with some private properties (Times 16 bold font and navy blue foreground). π
$doc->createStyle
(
"Welcome",
family => 'paragraph',
parent => 'Standard',
properties =>
{
'area' => 'text',
'style:font-name' => 'Times',
'fo:font-size' => '16pt',
'fo:font-weight' => 'bold',
'fo:color' => '#000080'
}
);
The color attributes are encoded in RGB hexadecimal format. It's possible to use more mnemonic values or symbols, through conversion functions provided by the Styles module, and optional user-provided colour maps. For example, "#000080" could be replaced by odfColor('navy blue'), provided that an appropriate color table is available at the run time; see odfLoadColorMap() in the OpenOffice::OODoc::Styles manual chapter. π
According to the application logic, each newly created style can be registered either as a "named" style (i.e. visible and reusable through a typical office software suite) or as an "automatic" style. β¨
For an ordinary application that needs the best processing facility for any kind of content and presentation element, the OODoc::Document module is the best choice. This module defines a special class that inherits from Text, Image and Styles classes. It allows the programmer, for example, to simply insert a new paragraph, create an image object, anchor the image to the paragraph, then create the styles needed to control the presentation of both the paragraph and the image, all that in the same sequence and in any order. π
Caution: In order to get a convenient translation between the user's local character set and the common ODF encoding (utf8), the application must indicate the appropriate encoding. The default one isiso-8859-1in the CPAN distribution; it can be set using theodfLocalEncoding()function. Example:
use OpenOffice::OODoc;
odfLocalEncoding 'iso-8859-15';
The default encoding can be selected by the user during the installation, and changed later by editing a configuration file. In addition, a program working with several documents in the same time can select a distinct character set for each one. π§
β¨ Some practical uses β¨
To begin playing with the modules, you should before all see the self-documented sample scripts provided in the package. These scripts do nothing really useful, but they show the way to use the modules. π
You should directly load the full library with the single use OpenOffice::OODoc in the beginning of your scripts. Then you should only use (in the beginning) the Document and/or Meta classes only. We encourage you, in the first time, to avoid any explicit OODoc::XPath basic method invocation, and to deal only with available "intelligent" modules (Text, Image, Styles, via Document, and Meta), in order to get immediate results with a minimal effort. And, if you use this stuff for evangelization purpose, you can show the code to prove that the OpenDocument format allows a lot of things with a few lines. β¨
You can avoid the heavy object oriented notation such as:
my $meta = OpenOffice::OODoc::Meta->new(file => "xxx.ods");
and use the shortcuts like:
my $meta = odfMeta(file => "xxx.ods");
The first thing you have to do with a document is to create an object focused on the member you want to work with, and "feed" it with regular ODF XML. The most straightforward way to do that is to create the object in association with an ODF file. π¦
β¨ Dealing with metadata β¨
We need metadata access, so we use OODoc::Meta
use OpenOffice::OODoc;
my $doc = odfMeta(file => 'myfile.odt');
my $title = $doc->title;
if ($title) { print "The title is $title"; }
else { print "There is no title"; }
Here, because the constructor of OODoc::Meta is called with a 'file' parameter, OODoc::Meta knows it needs a file access and it dynamically requires the OODoc::File module, instantiates a corresponding object using the file name, connects to it, and asks it for the 'meta.xml' member of the file. All that annoying processing is hidden for the programmer. We have just to query for the useful object, the title. π
In the same way, we could get (or even change) the document creation or last modification date registered by the editing software:
my $d1 = $doc->creation_date;
my $d2 = $doc->date;
The dates, in the ODF documents properties, are stored in ISO-8601 format (yyyy-mm-ddThh:mm:ss); this format is readable but not necessarily convenient for any application. But the API provides easy to use tools allowing conversion to or from the regular numeric time() format of the system, allowing any kind of formatting or calculation. π₯
We could get more complex metadata structures, such as the user defined fields:
my %ud = $doc->user_defined;
foreach my $name (keys %ud)
{ print $name . '->' . $ud{$name} . "\n"; }
This code captures the user defined fields (names and values) in a hash table, which then is displayed in a "name->value" form. You could see the way to update the user defined fields in the 'set_fields' script, provided with the distribution. The most usual metadata accessors have a symmetrical behaviour. To update the title, for example, you have to call the 'title' method with a string argument:
$doc->title("New title");
You can proceed in the same way with subject, description, keywords. π
The keywords thing? That's polymorphic behaviour bestie, and it's lowkey everywhere in OODoc methods:
my $keywords = $doc->keywords;
my @keywords = $doc->keywords;
First form? You get the keywords back concatenated and comma-separated in one single editable text line. Second form? You get them as a list. But listen β if you're calling keywords to add new ones, they gotta come as a list:
$doc->keywords("kw1", "kw2", "kw3");
$doc->keywords(@my_keywords);
And the program automatically blocks you from adding duplicates, because the keywords method deletes them for you. No redundant keyword lists in this house π
But bestie, keywords can only add. To delete an existing keyword you need removeKeyword. And if you want to nuke the entire keyword list in one single call, you just write:
$doc->removeKeywords;
Okay so we've done some metadata updates, slay β¨ But those updates? They live in memory only. To make it persistent in the file, we just issue a:
$doc->save;
Now here's the tea β β I said OODoc::Meta (which is an OODoc::XPath) doesn't know anything about the OpenDocument compressed files. But in my example, the object was created with a 'file' argument and got associated with an implicit OODoc::File object. So the save method of OODoc::XPath? It's just a stub method that sends a 'save' command to the connected OODoc::File object.
But if the object was created with an 'xml' parameter (metadata as an XML string, no file reference)? Then a save call gives you a No archive object error. And if the object came from an XML flat file instead of a regular ODF compressed file, the output would be a flat XML file too.
Note: A document is always saved in the same file format as its source.save()can't act as a format converter. So you can't save an OOo 1.0 file in OASIS OpenDocument format and vice versa, and you can't directly (without intermediate processing) save in ODF compressed format a document loaded from XML data. However β thanks to thegetXMLContent()method, you can write the flat XML to standard output or a given file handle. π«Ά
If you prefer to keep the original file unchanged, you can issue a
$doc->save('my_other_file.odt');
which does the same thing as 'File/SaveAs' in your favorite office software: called with an argument, save creates a new file containing all the changed and unchanged members of the original one.
Of course, whatever way you use (or don't use) the save() method, you will never process valuable documents without a backup copy... π fr fr
πΈ Example 2 - Manipulating text πΈ
Here we gotta read and update some text content elements. And by "text content" we mean not only "flat text". While the most interesting module is named OpenOffice::OODoc::Text, it's not fully dedicated to text documents. It can deal with the text content of presentations, as well as the sheets and cells of a spreadsheet. Versatile icon behavior π
Our program begins with something like:
use OpenOffice::OODoc;
my $doc = odfDocument(file => 'myfile.odt');
That second line produces an OpenOffice::OODoc::Document object, which inherits from O::O::Text, O::O::Image and O::O::Styles. But in this example, we're only using its O::O::Text features.
To give a very high level abstract, OODoc::Text provides 2 kinds of read access methods:
- the
'get'methods that return data referred by unconditional addressing, likegetParagraph(4); - the
'select'methods that return data selected against a given filter, related to a text content or an attribute value, likeselectParagraphsByStyle('Text body').
Some 'get' or 'select' methods return lists while others return individual elements or values.
Returned data may be elements or texts. Text data can be exported or displayed, but the application needs elements to do any read/write operation on the content. For example:
my $text = $doc->getTextContent;
extracts the whole content of the document as a flat, editable text in the local character set, for immediate use (or display on a dumb terminal π). And of course there's more than one way to do the same thing β you can get the same result with a 'select' method as with a 'get' one if you use a "non-filtering filter". So:
my $text = $doc->selectTextContent('.*');
will also return the whole text content. But this last method, with some additional arguments and an appropriate filter, is much more powerful, because it can do 'on-the-fly' processing in each text element matching the filter (like, insert values from an enterprise database or results from complex calculations β¨).
The output of getTextContent can be tagged according to the type of each text element, so the application can easily use this method to export the text in an alternative (simple) markup language.
To do some intelligent processing in the text, we need to deal with individual text objects such as paragraphs, headings, list items or table cells. For example, to export the content of the 5th paragraph (paragraph numbering beginning with 0), we could directly get the text with:
my $text = $doc->getParagraphText(4);
But to update the same paragraph, or change its style, I need the paragraph element, not only its text content:
my $para = $doc->getParagraph(4);
# text processing takes place here
$doc->setText($para, $other_text);
$doc->setStyle($para, $my_style);
Some methods can dynamically adapt to the text element type they have to process. Like, the getText method (exporting the text content of a given text element) can return the content of many kinds of element (paragraphs, headings, table cells, item lists or individual list items). Plus, any text content extracted with a high-level OODoc method is transcoded in the local character set (UTF-8 issues are β we hope π€ β hidden for the application). Optionally, the text output can be instrumented with begin and end application-provided tags according to the element type, so it's possible to export the text in an alternative, simple XML dialect, or in LaTeX, or in an application-specific markup language. The range? Iconic π
To facilitate some kinds of massive document processing operations, OODoc::Text provides a few high level methods that do iterative processing upon whole sets of text elements. One example is selectElementsByContent: this method looks for any text container matching a given pattern (string or regular expression) and, each time an element is selected, it executes an application-provided callback function. An example of use is provided in the 'search' demo script, which selects any text element in a document matching a given expression, and appends the selected content as a sequence of paragraphs in another document.
The more usual methods have explicit names, and can be used without their exhaustive documentation, provided that the programmer has a good understanding of the general philosophy. Heading and paragraph manipulations are quite simple. The situation is more complex with other text content such as item lists, tables and graphics.
To get an individual list item, you must point to it from a previously obtained list element:
my $item_list = $doc->getList(2);
my $item = $doc->getListItem($item_list, 4);
Here, $item contains the 5th item of the 3rd list of the document. The content of the item could then be exported by a generic method such as getText(), or processed using another method. Note that if the application doesn't need the $item_list object for any other use, it can directly get the list item with the same method with a list number (instead of a list object) as its first argument:
my $item = $doc->getListItem(2, 4);
π Playing with tables and spreadsheets π
Because the need for data capture within table structures is more evident, there's a direct accessor to get any individual table cell:
my $value = $doc->getCellValue($table, $line, $col);
For example:
my $value = $doc->getCellValue(0, 12, 0);
This code example returns the value of the 1st cell of the 13th row of the 1st table in the document. Note the 'cell value' is simply the text content if the cell type is string; but if the cell type is any numeric type, getCellValue returns the content of the value attribute and ignores the text. The first argument (the table) can be either the table number (zero-based, according to its sequential position in the document) or the logical table name (as it's get or set by the end-user with OOo Writer or Calc).
A cell can be selected in a table using either its numeric (row, column) coordinates or a "spreadsheet-like" alphanumeric notation. So, the example above could be written as
my $value = $doc->getCellValue(0, "A11");
Caution: in the classical spreadsheet notation, the column comes first while it comes last in the numeric coordinates. Plus, knowing that the numeric coordinates are zero-based,"A1"corresponds to(0,0). And finally, remember that the alphanumeric coordinates must be provided in a single string while numeric coordinates require two arguments. Don't mix them up bestie π
This alphanumeric notation is probably more user-friendly for OOo Calc documents, but it's allowed by OODoc whatever the document class: you can use it with tables in text documents as well. Versatility queen π
Caution: The direct cell addressing works only when the table XML storage is "normalized", i.e. when every table object (row, column or cell) is mapped to an exclusive XML element. The application program can easily ensure this "normalization" thanks to thenormalizeSheet()method, described in theOpenOffice::OODoc::Textmanual page.
However, up to now, the tables included in text documents through OpenOffice.org Writer are normalized, so they're immediately available for direct addressing. On the other hand, with OpenOffice.org Calc spreadsheets, several contiguous objects are mapped to a single XML element as long as they have the same content, the same type and the same presentation. It's not an issue β it's a feature allowed by the OpenDocument specification in order to save storage space, knowing that typical large spreadsheets contain a lot of empty, or repetitive, cells. As a consequence, several cells may be located at the same coordinates. The normalizeSheet() method allows the application to define a safe area, sized according to its needs, where the direct object addressing works whatever the XML storage method in use. Periodt π
Okay so the table-ish methods? They work with spreadsheets (like, OOo Calc documents, yk) and with tables that live inside text documents. But bestie, hear me out β before you go addressing cells in a spreadsheet document, your program has to "declare" the size of the used area in each target sheet. Not optional. This requirement exists purely for performance considerations, and it's Calc documents only π .
You can also change the content of a cell:
$doc->updateCell($table, $line, $col, $value);
$doc->updateCell($table, $line, $col, $value, $string);
$doc->updateCell($cell, $value);
$doc->updateCell($cell, $value, $string);
Let's break these four icons down:
- The first form drops
$valueinto the target cell, assuming it's a string cell β or, if it's a numeric one, you're choosing to put the same content as both the value and the displayable string. - The second form (assuming the target cell is numeric) gives you independent content for value and string. Programmer, you gotta know what you're doing here β like, say, in the case of a currency or date cell.
- The 3rd and 4th forms do the same things respectively, except they use a previously obtained cell element instead of 3D coordinates (so you dodge unnecessary low-level XPath recalculation β slay).
For a flat text (non-numeric) cell whose reference is already available, setText() produces the same result as updateCell():
my $cell = $doc->getCell($table, $row, $col);
$doc->setText($cell, "The text in the cell");
Both getCellValue() and updateCell() can be replaced by the cellValue() shortcut, which is a read/write accessor to individual cells. So:
my $value = $doc->cellValue("Sheet4", "B12");
$doc->cellValue("Sheet1", "P5", $value);
β¦copies a value from one cell to another one in another table. β¨
In this intro, the cells are assumed to be text-only. Of course, the code is more complex with numeric cells, because the program has to get or set some additional information, according to its data type.
OODoc::Text allows the program to create a new table, using the appendTable or insertTable method. The following example appends a new table with 8 lines and 5 columns to the document.
my $table = $doc->appendTable("MyTable", 8, 5);
But this new table is (by default) a pure text table. It's possible to build very sophisticated table structures, with an appropriate data type and a special presentation for each cell β but to complete this task, the application must provide a lot of parameters. So, recommendation time: avoid purely programmatic table construction, and reuse existing table structures and styles in template documents previously created with an ODF compatible software instead. π«Ά
π Sections, subdocuments and hyperlinks π
For sophisticated document structures, paragraphs and other text containers may be included in sections. The API allows the applications to easily create or retrieve sections, with the getSection(), appendSection(), and insertSection() methods. A given section may be either populated with a local content or provided with an external link (file path or URL) in order to include a subdocument. In addition, using lockSection() and unlockSection(), the programs can control the end-user write protection of any section. π
The following example (working with OOo 2.0) appends to a master document a new, write-protected section including a new document which can be reached through an internet link:
my $url = "http://jean.marie.gouarne.online.fr/doc/oodoc_guide.odt";
$doc->appendSection
(
"Getting Started",
link => $url,
protected => "true"
);
And, if an unfortunate end-user is barred from updating a section by a lost password, the programmer can help with a single line such as:
$doc->unlockSection($section_name);
Of course, a section can host any local content instead of an external link. π¦
my $section = $doc->appendSection("Section 1");
$doc->appendParagraph
(
attachment => $section,
text => "The first paragraph in the section",
style => "Standard"
);
Here, a section is created and receives a paragraph as its first content.
An existing set of content elements could migrate under a section. The next example, more sophisticated, selects the list of all the elements that hierarchically depend on the first level 1 title of the document and moves these elements to a given section:
my @content = $doc->getChapterContent(0, level => 1);
$doc->moveElementsToSection("Section 1");
Sections are not the only places for using hyperlinks, btw. The applications can associate hyperlinks to any portion of text. The following example puts a remote (http) link on every "OpenDocument" character string in a given paragraph:
$doc->setHyperlink
($para, "OpenDocument", "http://www.oasis-open.org");
The target of an hyperlink may be a bookmark or a heading in the current document or in another ODF document. For example, if the target is a bookmark included in the same document, the link is the name of the bookmark with a leading #:
$doc->setHyperlink($para, "a string", "#MyMark");
When the target is a heading (i.e. a hierarchical title), the link is made of the text of the heading, prefixed with # and suffixed by |outline.
If an hyperlink is aimed at any target belonging to another document (in the local filesystem or elsewhere), you have just to concatenate the file path and the internal path. The example below puts an hyperlink to a particular heading located in a remote document:
$doc->setHyperlink
(
$para, "read the conclusion",
"http://somewhere.com/somewhat.odt#Conclusion|outline"
);
π Manipulating variables, bibliographic entries, bookmarks π
The OODoc toolbox provides easy read/write accessors to some useful objects that can be included in OOo text documents.
If a text document contains a user-defined field, the corresponding value can be read and updated. For example, if the user needs to increase a numeric by a given value, the corresponding code could be:
$old_value = $doc->userFieldValue("FieldName");
$doc->userFieldValue("FieldName", $old_value + $added_value);
In addition, the OODoc API allows the user to "declare" new user-defined fields if needed (see setUserFieldDeclaration() in OpenOffice::OODoc::XPath). πΈ
Any OpenDocument-compliant variable text field may be inserted in a document through the textField() method. The next example appends a paragraph whose text content is "This document contains <page-count> pages", knowing that the real page count will be dynamically displayed by the office software:
my $p = $doc->appendParagraph
(text => "This document contains ");
$doc->appendElement($p, $doc->textField('page-count'));
$doc->extendText($p, " pages");
While the sequence above appends a text field at the end of a paragraph, the setTextField() method may insert a text field anywhere within an existing paragraph according to various positioning parameters. The example hereafter creates a date field immediately after the last occurrence of the substring "the current date is "; the 'after' option provides the search string while the 'way' option specifies that it must be searched backward:
$doc->setTextField(
$paragraph, 'date',
after => "the current date is ",
way => 'backward'
);
It's possible to get or set any property of a bibliography entry. An entry can be selected by its identifier (as it appears for the end-user). The first example below prints the title and the author of the first found occurrence of a "[GEN99]" entry, while the second one creates (or updates) its "ISBN" and "pages" properties:
# 1
my %properties = $doc->bibliographyEntryContent("GEN99");
print "Title = $properties{'title'}\n";
print "Author = $properties{'author'}\n";
# 2
$doc->bibliographyEntryContent
(
"GEN99",
isbn => 'xxxxyyyyzzzz',
pages => 254
);
In addition, a getBibliographyEntries() method allows the user to retrieve the full list of the entries included in a document. π
An additional bibliography entry may be inserted within a paragraph using setBibliographyMark(). As an example, the following instruction inserts a new bibliography mark as a replacement of the first substring "reference needed" that may occur after the 20th character in a given paragraph:
$doc->setBibliographyMark (
$paragraph,
offset => 20,
replace => "reference needed",
attributes => {
identifier => "JDE",
title => "OASIS OpenDocument Essentials",
author => "J. David Eisenberg",
year => 2005,
isbn => "1-4116-6832-4"
}
);
We can put a bookmark in a paragraph containing a given string. Example:
my $paragraph = $doc->selectElementByContent("my search string");
$doc->setBookmark($paragraph, "MyMark");
The instruction above puts the mark at the beginning of the paragraph; however, setBookmark() could put the mark at any position within the text, according to optional parameters. To illustrate the positioning logic, the following instruction puts the bookmark immediately after the first occurrence of "xyz" that appear after the first 20 characters:
$doc->setBookmark(
$paragraph, "MyMark",
offset => 20,
after => "xyz"
);
Note that there are many possible positioning parameter combinations for bookmarks and any other markup elements intended to be inserted within text containers; the various possibilities are inherited from thesetChildElement()method, that is described in theOpenOffice::OODoc::XPathmanual page.
A bookmark (created either through OpenOffice::OODoc or through this Perl API) can be used to retrieve a text element:
my $paragraph = $doc->selectElementByBookmark("MyMark");
Note that where you drop text fields, bibliography marks, bookmarks and all those other markup elements is fully your call β you can point at the exact spot using the same set of position parameters, following the very same logic, all inherited from the common setChildElement() method, which is described over in OpenOffice::OODoc::XPath. π
π Dealing with text AND metadata π
Sometimes we gotta touch both the text content and the metadata. So that means two objects: one OODoc::Document and one OODoc::Meta. And to dodge collisions and wasteful I/O operations, we wire both of them into the same OODoc::File "server". β¨
use OpenOffice::OODoc;
my $archive = odfContainer('myfile.odt');
my $content = odfDocument(container => $archive);
my $meta = odfMeta(container => $archive);
# process content and metadata
$archive->save;
Here $content and $meta are explicitly linked to a shared container, no cap. Which means when you trigger the save() method of that container, literally every change you made through either of them becomes persistent. π«Ά
There's a whole example of hitting content and metadata at the same time in the script set_title (where some text content gets used to generate a piece of metadata). Obsessed.
πΌοΈ Manipulating graphics πΌοΈ
The OODoc::Image module brings some functionalities you can throw at any OO document. The code below (mixing the powers of OODoc::Text and OODoc::Image) picks the first paragraph containing the string "OpenOffice" and attaches an imported image to it. Slay.
my $p = $doc->selectElementByContent("OpenOffice");
die "Paragraph not found" unless $p;
$doc->createImageElement
(
"Paris landscape",
description => "Montmartre in winter",
attachment => $p,
import => "C:\MyDocuments\montmartre.jpg",
size => "5cm, 3.5cm",
style => "graphics2"
);
In a spreadsheet document, that same image could be attached to a cell instead of a paragraph; to do that, the "attachment" option should be set to a cell element, which you previously got using getCell(). Same syntax, different container: in a presentation document the "attachment" should be a draw page, previously selected using getDrawPage(). And there's a "page" option that lets the user anchor an image to a page instead of attaching it to a text container. π
In this example the image is physically imported. But you could swap the "import" parameter for a "link" one, to use the image as an external link instead (cf. the "link" option when you insert an image in OpenOffice.org). That link could use a local filesystem path as well as a remote access path such as "http://...". π
My new image needs a style (called "graphics2" in my example) to be presented. This style could be an existing one, but my program could create it if needed, using an OODoc::Styles method (see below).
Any characteristic of an existing image can be read or updated using simple methods. For example, it's easy to change the size and the position of my image:
$doc->imageSize("Paris landscape", "10cm, 7cm");
$doc->imagePosition("Paris landscape", "3cm, 0cm");
The size and position strings indicate the used length unit. OODoc doesn't check the provided unit, so the application should ensure that only ODF-compliant units are used. Possible units are, for example, "cm" (centimeter), "mm" (meter), "in" (inch), "pt" (point).
The logical name of the image (here "Paris landscape") is the best way to retrieve an image object, so it's a mandatory argument with the createImageElement method. With OpenOffice.org Writer, each image is created with an unique name (that is "Image1", "Image2", etc. if the user doesn't provide a more significant one). But with OpenOffice.org Impress, the images are unnamed by default. We recommend you give a significant name to each object that you want to process later by program, knowing that if an object can be easily caught by program, it's potentially reusable. π
An image can be selected by his description (i.e. the text the end-user can edit in the image properties dialog in OpenOffice.org). So the following sequence provides the list of images whose the description contains the string "Montmartre":
my @images = $doc->selectImageElementsByDescription("Montmartre");
If you have to store and process a graphical content out of the end user's editing software, you can export it as an ordinary file:
$doc->exportImage("Paris landscape", "/home/pictures/montmartre.jpg");
And you can use a symmetric importImage method to change the content of an image element. π¦
π¨ Managing styles π¨
OODoc::Styles lets the programmer get any style definition, change it and β if really needed β create new styles. In the first part of this document you can see an example of paragraph style creation. Unfortunately, createStyle could drive you to heavy coding efforts, because a very sophisticated style definition needs a lot of parameters and requires the knowledge of a lot of ODF attribute names. So we recommend you systematically reuse existing styles (stored in ODF template documents used as "style repositories" or in XML databases). The createStyle method supports a "prototype" parameter that allows you to clone an existing style, contained in the same document or in another one. π
The next code sequence selects the "Text body" style of a document, and uses it as a template to create a "My Text body" style in another document, changing the font size only:
my $template = $doc1->getStyleElement("Text body");
$doc2->createStyle
(
"My Text Body",
family => "paragraph",
prototype => $template,
properties =>
{
"area" => "text",
"fo:font-size" => "12pt",
"fo:color" => odfColor("dark blue")
}
);
Here a "dark blue" color has been given to the text; but "dark blue" is an arbitrary string, that must be present in a user-provided, previously loaded color map. Without this color map, the users must, at their choice, either directly provide an hexadecimal, six-digit color code, with a leading "#" (such as "#00008b", that is the translation of "dark blue" in my installation), or get it through the odfColor() function with 3 decimal RGB values as arguments. πΈ
Because a style is required for each image in a document, the OODoc::Document brings a more user-friendly createImageStyle method. This method allows you to create an image style without any mandatory parameter (excepted the name). So the "graphics2" style I invoked in a previous createImage example could be simply created by:
$doc->createImageStyle("graphics2");
Without other indication, the module automatically creates a style with "reasonable" values, so the image is really visible in the document. Of course, the application could provide explicit values for some parameters if needed. The following call, for example, provides specific values for contrast, luminance and gamma correction:
$doc->createImageStyle
(
"graphics2",
properties =>
{
'draw:contrast' => '2%',
'draw:luminance' => '-3%',
'draw:gamma' => '1.1'
}
);
Styles are not made only to control the presentation of individual elements. There are special styles for page layout. While these styles are described with very specific data structures, the OODoc::Styles module contains some methods dedicated to page styling. β¨
π Dealing with styles AND content π
While the OpenOffice::OODoc::Document methods can process both the content (text, complex structures and graphics) and the styles, it's not always possible to get any style and any content through the same object in the same session. π
Each individual instance of ::Document wraps an individual part of an ODF package. The default part is "content.xml", but all the named style definitions are stored in the "styles.xml" part (in a few words, a named style is a style which was designed in order to be used by more than one content element; for example, any style which could be selected through the style dialog box of a typical user-oriented office software is a "named" style).
In order to avoid a lot of useless XML parsing, only one part at a time is loaded. As a consequence, if the application needs to process content and named styles during the same session, it must create 2 instances of ::Document objects, associated with the same ODF container. Each instance must be associated with the appropriate target. For example:
use OpenOffice::OODoc;
my $archive = odfContainer('myfile.odt');
my $content = odfDocument
(
container => $archive,
part => 'content'
);
my $styles = odfDocument
(
container => $archive,
part => 'styles'
);
After this sequence, the $styles object gives access to any named style while all the document body can be processed through the $content object. Note that in this last example, we could avoid the "part" option for the "content" member of the package (because "content" is the default). π
Knowing that its always possible to process content, named styles and metadata in the same session, we could instantiate a ::Meta object through odfMeta() as well. So up to 3 connecting objects can be used as interfaces for the same ODF file. π₯
Of course, a single $archive->save() can make persistent all the changes made through all the connected objects. Periodt.
π¬ COMMENTS AND BUG REPORTS π¬
Comments, questions and answers are welcome through the CPAN forum http://www.cpanforum.com/dist/OpenOffice-OODoc
Bug reports should be sent using http://rt.cpan.org/NoAuth/Bugs.html?Dist=OpenOffice-OODoc
π AUTHOR/COPYRIGHT π
Okay so who actually made this whole thing? Let's give credit where credit is due, bestie, because these people ATE. π
- Developer/Maintainer: Jean-Marie Gouarne β <http://jean.marie.gouarne.online.fr>
- Contact: jmgdoc@cpan.org
- Copyright 2004-2010 by Genicorp, S.A. β <http://www.genicorp.com>
- Initial English version of the reference manual by Graeme A. Hunter (graeme.hunter@zen.co.uk)
- License: GNU Lesser General Public License v2.1
Like, the original English version of the reference manual? That was Graeme A. Hunter's doing, and we are so grateful because translating docs is genuinely the most underrated act of service fr fr. π«Ά
And the whole license situation is GNU Lesser General Public License v2.1 β that's the legal vibe, not a suggestion, so respect it. β¨
Not me getting emotional over a copyright block. It's giving "history of the craft." ππΈ
That's a wrap on OODoc::Intro(3pm) besties!! This page is from perl v5.34.0, dated 2022-06-16 β the OODoc::Intro(3pm) era, iconic behavior only. Go forth and document your code, you absolute main character. π
π¦π
π¦ where this page comes from
- debian bookworm: libopenoffice-oodoc-perl 2.125-4 Β· LGPL-2.1-only
- debian trixie: libopenoffice-oodoc-perl 2.125-4 Β· LGPL-2.1-only
- ubuntu noble: libopenoffice-oodoc-perl 2.125-4 Β· LGPL-2.1-only
- ubuntu questing: libopenoffice-oodoc-perl 2.125-4
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms