pyopenoffice
index
/home/martin/skripte/python/PyOpenOffice/pyopenoffice.py

#coding: latin-1

 
Modules
       
reportlab.lib.colors
copy
glob
os
re
shutil
string
sys
time
types
_xmlplus
zipfile

 
Classes
       
reportlab.platypus.doctemplate.BaseDocTemplate
ooDocTemplate
xml.sax.handler.ContentHandler
oo2pdfHandler
ooTextHandler
PyOpenOffice
Regexes
Textutilities
oo2pdf

 
class PyOpenOffice
    This is the main class which provides all functionality.
 
  Methods defined here:
__init__(self, v=1)
makePdf(self, infile='test.sxw', outfile=None, plainText=0, plain_text_output=0)
makePlainText(self, oowriter, plain_text_output=0)
Makes PDFs or plain text files from sxw files. All XML-Tags for formatting are dropped,
no images are processed, table cells are transformed to paragraphs with text data.
Output: pdf or plain text (plain_text_output=1).
makeSafePdf(self, oowriter)
Make PDFs from a list of sxw-files or a single file. Make several trials, when an error occurs:
full featured, without underlines, without images, text only without all formatting as a last rescue.
makeSerialLetters(self, sourcefile, replace_listofdicts, one_file=1)
Make Serial letters from the records in replace_listofdicts. If one_file=1, the output is merged to one file.
Output: sxw.

 
class Regexes
     Methods defined here:
__init__(self)

 
class Textutilities
     Methods defined here:
__init__(self)
abkuerzungenTesten(self, text, wortliste)
Soll einen Text darauf testen, ob er lediglich eine Anzahl von Abkürzungen
enthält, ggf. getrennt durch Spaces, Kommas usw. z.B. für Tests von
Datenbankfeldern.
alsDictionary(self, spalten, array)
bildschirmLoeschen(self)
Arbeitet mit ANSI-Escape-Sequenzen. Für DOS nicht vergessen,
ansi.sys einzubinden.
csvDateiSchreiben(self, matrix, dateiname, trenner='\t', alsString='nein')
Schreibt eine Liste von einer Liste in eine Datei,
überschreibt ggf. ohne Nachfrage!
csvdatei_einlesen(self, datei='/home/martin/skripte/python/gemeindekartei.txt', trenner='\t', datumumwandeln='nein', nichtaendern=['Telefon', 'Fax', 'EMail'])
Spaltenüberschriften als erste Zeile werden nicht gesondert behandelt!
Rückgabeformat: Liste von Liste.
datumParsen(self, string)
gibt ein erkanntes Datum als ISO-String
JJJJ-MM-TT zurück, sonst den String selbst.
Erlaubte Eingabeformate: "TT/MM/JJJJ" oder "TT.MM.JJJJ"
oder "TT. Monatsname(deutsch ohne Abkürzung: "September") JJJJ".
Ist tolerant gegen fehlende Spaces.
Damit nicht jedes Textutilities-Objekt die komplizierten Regexes
kompilieren muß, erscheinen sie nur hier und nicht in __init__.
extract_tags(self, starttag, endtag, startposition, inhalt, mitTags='ja')
extract_tags_all(self, starttag, endtag, inhalt, mitTags='ja')
Like extract_tags, but returns a list of all matches.
heute(self)
Current date in German form.
importUmwandeln(self, string)
Gibt an, wie jedes einzelne Datenfeld - unabhängig von
datumParsen - noch behandelt werden soll.
konfigurationEinlesen(self, text)
Liest einen Text (z.B. aus einer Konfigurationsdatei) ein, gibt die Daten
in einem Dictionary zurück. Primitiv und nicht sehr fehlertolerant. Windows-geeignet?
(Wegen Zeilenendezeichen)
openOfficeErsetzen(self, datei, inhalt, neuedatei=None)
openOfficeLesen(self, datei)
Liest die content.xml-Datei eines OO-"Archivs".
openOfficeMerge(self, content1, content2, pagebreak='ja')
Ergänzt bei der content.xml-Datei des ersten OO-Archivs in <office:body> den Inhalt von
<office:body> der zweiten Datei. Nur die automatic-styles der ersten Datei werden übernommen.
openOfficeMergetextPruefen(self, text)
Manche XML-Styles machen bei dieser primitiven Merge-Methode Probleme,
deshalb dieser Test. Achtung, überall nur reine ASCII-Zeichen nehmen, keine Umlaute!
openOfficeMultiReplace(self, sourcefile, replace_listofdicts, tags=('TFA-', '-TFE'), as_file=1, with_paragraphs=0)
Multiple replace of tables-rows and paragraphs. Working without an XML-Parser - fast, but primitive.
Use only custom fields with pure ASCII-Sign - not "TFA-GermanUmlauteÄÖÜ-TFE" etc.
openOfficeMultiReplaceParagraphs(self, content, listofdicts, tags=('TFA-', '-TFE'))
Replaces one paragraph with the records from listofdicts. Use the line-break-sign in the
sxw-document (shift-return in OO) instead of carriage-return to print multi-line-records
for example: Surname - linebreak - First Name - linebreak - City.
TODO: this function is not safe yet. It is switched off by default.
openOfficeMultiReplaceTables(self, content, listofdicts, tags=('TFA-', '-TFE'))
Replaces one table-row with the records from listofdicts.
TODO: is it useful to use other tags?
openOfficePagebreakstyle(self)
Very primitive. Assumes that you will never more than 2000 automatic-styles...
openOfficePagebreakstyleEinsetzen(self, content)
openOfficeRemoveEmptyParagraphs(self, content)
Removes all empty paragraphs from content.
openOfficeReplaceKeyCheck(self, string, list_of_keys, multi=0)
Checks the string for TFA-key-TFE or Multi:TFA-key-TFE fields.
Returns 1, if at least one field is in the string.
openOfficeSerialLetter(self, sourcefile, replace_listofdicts, one_file=1, tags=('TFA-', '-TFE'), content='')
Takes an sxw-file and a list of dictionaries, makes many documents from it
by replacement. The startag and endtag defaults are from the "Bezirksreiter"-Software.
If one_file is set to 0, it will be saved as one document per record, otherwise everything
will be in one document. When using frames in the sxw-document: do not use "anchor-type:page".
Working without an XML-Parser: fast, but primitive.
You may pass a preprocessed content, then sourcefile is only used for the output file name.
TODO: the tags only may contain ascii-signs.
Use only custom fields with pure ASCII-Sign - not "TFA-GermanUmlauteÄÖÜ-TFE" etc.
openOfficeStringErsetzenDatei(self, datei, stringalt, stringneu)
openOfficeStringUtf8(self, string)
privatStattDienstlich(self, dict)
Setzt bei  nicht vorhandener Dienstadresse die Privatadresse ein.
Speziell für Datenbank vom Typ emkadressen_neu
privatStattDienstlichDictarray(self, dictarray)
remove_tags(self, starttag, endtag, inhalt, mitTags='ja')
schluesselworteExtrahieren(self, text, wortliste, ohneSpaces='ja')
Entfernt aus einem String alle Wörter aus Wortliste.
schluesselworteFinden(self, text, wortliste, ohneSpaces='ja')
stringErsetzenDatei(self, datei, stringalt, stringneu)
Eine sichere Methode, einen String zu ersetzen in einer Datei.
berücksichtigt das verzögerte Setzen von Rechten bei Windows usw.
today(self)
Current date

 
class oo2pdf
    This class is responsible for the OO-to-PDF transformation. It builds up the "story" for the Platypus engine.
Mind the different SKIP-flags.
 
  Methods defined here:
__init__(self, filename='test.pdf', LANDSCAPE=0)
addEmptyParagraph(self, stylename, return_not_add=0)
addParagraph(self, text, stylename, bullet='', orderedList=1, return_not_add=0)
Add a paragraph to the Platypus-"Story". It can be (formatted) text, a bulleted list or an ordered list.
Use return_not_add=1 for just getting the Paragraph object, without adding it to the story.
addParagraphStyle(self, stylename, styledict={'fontName': 'Times-Roman'})
Add a new Paragraph Style to doc.stylesheet.
addPicture(self, oo_attrs, picture_filename, picture_content, return_not_add=0)
Add a picture flowable to the "Story".
TODO: There may be several different pictures!
addTable(self, tableContent, stylename)
Adds a hardcoded, simple-style table with a grid, the whole table with hAlign=LEFT.
addTextStyle(self, stylename, oo_attrs, currentParagraphStyle='')
Make XML-Markup-Tags from OO-text-styles. Used for intra-paragraph-markup.
Problems with underlining (lines too short) - probably from a bug in the Platypus engine.
buildStory(self)
distancePoint(self, length=1, color='white')
Produces a non-visible point, uses XML-Markup. For "Tabs" etc.
mapFontName(self, fontname)
Map the OO-Fonts to the standard fonts found in ReportLab.
mapParagraphAlignment(self, oo_attrs)
Map the text alignment for the Platypus-Engine.
mapParagraphStyle(self, oo_attrs)
Map the OO-automatic-styles to Reportlab-ParagraphStyles
mapPictureStyle(self, oo_attrs)
Map a picture-style, use very few attributes. Only works with embedded (not linked) pictures.
TODO: Only works with cm and inch.
mapTableStyle(self)
Not implemented yet.
TODO: oo has a different method when a table contains columns of the same width!
table:table-columns ... table:number-columns-repeated="5"/> etc.
mapUnits(self, s)
Maps "cm" and "inch" to Reportlab-Units. TODO: Very primitive.
normalizeTableContent(self, tableContent)
Normalizes tables with different row lengthes.
testTable(self)
A test function for Platypus tables.

 
class oo2pdfHandler(xml.sax.handler.ContentHandler)
    Specialized handler for the sax parser.
TODO: Page numbering, better table formatting...
 
  Methods defined here:
__init__(self, infile='test.sxw', outfile=None)
characters(self, characters)
conditionalEscape(self, text)
Special escape for XML-Style-Markups in Platypus.
endElement(self, name)
Custom-style endElement-Events. The events are used to build up the Platypus-"Story".
handleParagraphStyle(self, attrs)
handlePicture(self, attrs)
handleTextStyle(self, attrs)
readContent(self, file='content.xml')
read content-xml from the sxw-zip-archive
readPicture(self, picture)
read a picture from Pictures/ in the sxw-zip-archive.
setTableBorder(self, attrs)
If at last one table cell of the oo-table has a border, in pdf the whole table is printed with a grid.
TODO: Too primitive?
startElement(self, name, attrs)
Custom style function for the "startElement"-event.
Transform unicode always to latin-1 - do not use it for Asian fonts etc.
testLandscape(self)
Test the styles.xml for landscape. TODO: very primitive.

Methods inherited from xml.sax.handler.ContentHandler:
endDocument(self)
Receive notification of the end of a document.
 
The SAX parser will invoke this method only once, and it will
be the last method invoked during the parse. The parser shall
not invoke this method until it has either abandoned parsing
(because of an unrecoverable error) or reached the end of
input.
endElementNS(self, name, qname)
Signals the end of an element in namespace mode.
 
The name parameter contains the name of the element type, just
as with the startElementNS event.
endPrefixMapping(self, prefix)
End the scope of a prefix-URI mapping.
 
See startPrefixMapping for details. This event will always
occur after the corresponding endElement event, but the order
of endPrefixMapping events is not otherwise guaranteed.
ignorableWhitespace(self, whitespace)
Receive notification of ignorable whitespace in element content.
 
Validating Parsers must use this method to report each chunk
of ignorable whitespace (see the W3C XML 1.0 recommendation,
section 2.10): non-validating parsers may also use this method
if they are capable of parsing and using content models.
 
SAX parsers may return all contiguous whitespace in a single
chunk, or they may split it into several chunks; however, all
of the characters in any single event must come from the same
external entity, so that the Locator provides useful
information.
 
The application must not attempt to read from the array
outside of the specified range.
processingInstruction(self, target, data)
Receive notification of a processing instruction.
 
The Parser will invoke this method once for each processing
instruction found: note that processing instructions may occur
before or after the main document element.
 
A SAX parser should never report an XML declaration (XML 1.0,
section 2.8) or a text declaration (XML 1.0, section 4.3.1)
using this method.
setDocumentLocator(self, locator)
Called by the parser to give the application a locator for
locating the origin of document events.
 
SAX parsers are strongly encouraged (though not absolutely
required) to supply a locator: if it does so, it must supply
the locator to the application by invoking this method before
invoking any of the other methods in the DocumentHandler
interface.
 
The locator allows the application to determine the end
position of any document-related event, even if the parser is
not reporting an error. Typically, the application will use
this information for reporting its own errors (such as
character content that does not match an application's
business rules). The information returned by the locator is
probably not sufficient for use with a search engine.
 
Note that the locator will return correct information only
during the invocation of the events in this interface. The
application should not attempt to use it at any other time.
skippedEntity(self, name)
Receive notification of a skipped entity.
 
The Parser will invoke this method once for each entity
skipped. Non-validating processors may skip entities if they
have not seen the declarations (because, for example, the
entity was declared in an external DTD subset). All processors
may skip external entities, depending on the values of the
http://xml.org/sax/features/external-general-entities and the
http://xml.org/sax/features/external-parameter-entities
properties.
startDocument(self)
Receive notification of the beginning of a document.
 
The SAX parser will invoke this method only once, before any
other methods in this interface or in DTDHandler (except for
setDocumentLocator).
startElementNS(self, name, qname, attrs)
Signals the start of an element in namespace mode.
 
The name parameter contains the name of the element type as a
(uri, localname) tuple, the qname parameter the raw XML 1.0
name used in the source document, and the attrs parameter
holds an instance of the Attributes class containing the
attributes of the element.
 
The uri part of the name tuple is None for elements which have
no namespace.
startPrefixMapping(self, prefix, uri)
Begin the scope of a prefix-URI Namespace mapping.
 
The information from this event is not necessary for normal
Namespace processing: the SAX XML reader will automatically
replace prefixes for element and attribute names when the
http://xml.org/sax/features/namespaces feature is true (the
default).
 
There are cases, however, when applications need to use
prefixes in character data or in attribute values, where they
cannot safely be expanded automatically; the
start/endPrefixMapping event supplies the information to the
application to expand prefixes in those contexts itself, if
necessary.
 
Note that start/endPrefixMapping events are not guaranteed to
be properly nested relative to each-other: all
startPrefixMapping events will occur before the corresponding
startElement event, and all endPrefixMapping events will occur
after the corresponding endElement event, but their order is
not guaranteed.

 
class ooDocTemplate(reportlab.platypus.doctemplate.BaseDocTemplate)
     Methods defined here:
__init__(self, filename, LANDSCAPE=0, **kwargs)
Make a page template. TODO: only DIN A 4 portrait or landscape possible.

Methods inherited from reportlab.platypus.doctemplate.BaseDocTemplate:
addPageTemplates(self, pageTemplates)
add one or a sequence of pageTemplates
afterFlowable(self, flowable)
called after a flowable has been rendered
afterInit(self)
This is called after initialisation of the base class.
afterPage(self)
This is called after page processing, and
immediately after the afterDrawPage method
of the current page template.
beforeDocument(self)
This is called before any processing is
done on the document.
beforePage(self)
This is called at the beginning of page
processing, and immediately before the
beforeDrawPage method of the current page
template.
build(self, flowables, filename=None, canvasmaker=<class reportlab.pdfgen.canvas.Canvas>)
Build the document from a list of flowables.
If the filename argument is provided then that filename is used
rather than the one provided upon initialization.
If the canvasmaker argument is provided then it will be used
instead of the default.  For example a slideshow might use
an alternate canvas which places 6 slides on a page (by
doing translations, scalings and redefining the page break
operations).
clean_hanging(self)
handle internal postponed actions
filterFlowables(self, flowables)
called to filter flowables at the start of the main handle_flowable method.
Upon return if flowables[0] has been set to None it is discarded and the main
method returns.
handle_breakBefore(self, flowables)
preprocessing step to allow pageBreakBefore and frameBreakBefore attributes
handle_currentFrame(self, fx)
chenge to the frame with name or index fx
handle_documentBegin(self)
implement actions at beginning of document
handle_flowable(self, flowables)
try to handle one flowable from the front of list flowables.
handle_frameBegin(self, resume=0)
What to do at the beginning of a frame
handle_frameEnd(self, resume=0)
Handles the semantics of the end of a frame. This includes the selection of
the next frame or if this is the last frame then invoke pageEnd.
handle_keepWithNext(self, flowables)
implements keepWithNext
handle_nextFrame(self, fx)
On endFrame chenge to the frame with name or index fx
handle_nextPageTemplate(self, pt)
On endPage chenge to the page template with name or index pt
handle_pageBegin(self)
Perform actions required at beginning of page.
shouldn't normally be called directly
handle_pageBreak(self)
some might choose not to end all the frames
handle_pageEnd(self)
show the current page
check the next page template
hang a page begin
multiBuild(self, story, filename=None, canvasmaker=<class reportlab.pdfgen.canvas.Canvas>, maxPasses=10)
Makes multiple passes until all indexing flowables
are happy.
notify(self, kind, stuff)
"Forward to any listeners
pageRef(self, label)
hook to register a page number
setPageCallBack(self, func)
Simple progress monitor - func(pageNo) called on each new page
setProgressCallBack(self, func)
Cleverer progress monitor - func(typ, value) called regularly

 
class ooTextHandler(oo2pdfHandler)
    Extract the plain text from a sxw-file. Inserts one carriage-return per sxw-paragraph.
 
 
Method resolution order:
ooTextHandler
oo2pdfHandler
xml.sax.handler.ContentHandler

Methods defined here:
__init__(self, infile='test.sxw', outfile=None, plain_text_output=0)
characters(self, characters)
endDocument(self)
endElement(self, name)
makeParagraphs(self)
startElement(self, name, attrs)

Methods inherited from oo2pdfHandler:
conditionalEscape(self, text)
Special escape for XML-Style-Markups in Platypus.
handleParagraphStyle(self, attrs)
handlePicture(self, attrs)
handleTextStyle(self, attrs)
readContent(self, file='content.xml')
read content-xml from the sxw-zip-archive
readPicture(self, picture)
read a picture from Pictures/ in the sxw-zip-archive.
setTableBorder(self, attrs)
If at last one table cell of the oo-table has a border, in pdf the whole table is printed with a grid.
TODO: Too primitive?
testLandscape(self)
Test the styles.xml for landscape. TODO: very primitive.

Methods inherited from xml.sax.handler.ContentHandler:
endElementNS(self, name, qname)
Signals the end of an element in namespace mode.
 
The name parameter contains the name of the element type, just
as with the startElementNS event.
endPrefixMapping(self, prefix)
End the scope of a prefix-URI mapping.
 
See startPrefixMapping for details. This event will always
occur after the corresponding endElement event, but the order
of endPrefixMapping events is not otherwise guaranteed.
ignorableWhitespace(self, whitespace)
Receive notification of ignorable whitespace in element content.
 
Validating Parsers must use this method to report each chunk
of ignorable whitespace (see the W3C XML 1.0 recommendation,
section 2.10): non-validating parsers may also use this method
if they are capable of parsing and using content models.
 
SAX parsers may return all contiguous whitespace in a single
chunk, or they may split it into several chunks; however, all
of the characters in any single event must come from the same
external entity, so that the Locator provides useful
information.
 
The application must not attempt to read from the array
outside of the specified range.
processingInstruction(self, target, data)
Receive notification of a processing instruction.
 
The Parser will invoke this method once for each processing
instruction found: note that processing instructions may occur
before or after the main document element.
 
A SAX parser should never report an XML declaration (XML 1.0,
section 2.8) or a text declaration (XML 1.0, section 4.3.1)
using this method.
setDocumentLocator(self, locator)
Called by the parser to give the application a locator for
locating the origin of document events.
 
SAX parsers are strongly encouraged (though not absolutely
required) to supply a locator: if it does so, it must supply
the locator to the application by invoking this method before
invoking any of the other methods in the DocumentHandler
interface.
 
The locator allows the application to determine the end
position of any document-related event, even if the parser is
not reporting an error. Typically, the application will use
this information for reporting its own errors (such as
character content that does not match an application's
business rules). The information returned by the locator is
probably not sufficient for use with a search engine.
 
Note that the locator will return correct information only
during the invocation of the events in this interface. The
application should not attempt to use it at any other time.
skippedEntity(self, name)
Receive notification of a skipped entity.
 
The Parser will invoke this method once for each entity
skipped. Non-validating processors may skip entities if they
have not seen the declarations (because, for example, the
entity was declared in an external DTD subset). All processors
may skip external entities, depending on the values of the
http://xml.org/sax/features/external-general-entities and the
http://xml.org/sax/features/external-parameter-entities
properties.
startDocument(self)
Receive notification of the beginning of a document.
 
The SAX parser will invoke this method only once, before any
other methods in this interface or in DTDHandler (except for
setDocumentLocator).
startElementNS(self, name, qname, attrs)
Signals the start of an element in namespace mode.
 
The name parameter contains the name of the element type as a
(uri, localname) tuple, the qname parameter the raw XML 1.0
name used in the source document, and the attrs parameter
holds an instance of the Attributes class containing the
attributes of the element.
 
The uri part of the name tuple is None for elements which have
no namespace.
startPrefixMapping(self, prefix, uri)
Begin the scope of a prefix-URI Namespace mapping.
 
The information from this event is not necessary for normal
Namespace processing: the SAX XML reader will automatically
replace prefixes for element and attribute names when the
http://xml.org/sax/features/namespaces feature is true (the
default).
 
There are cases, however, when applications need to use
prefixes in character data or in attribute values, where they
cannot safely be expanded automatically; the
start/endPrefixMapping event supplies the information to the
application to expand prefixes in those contexts itself, if
necessary.
 
Note that start/endPrefixMapping events are not guaranteed to
be properly nested relative to each-other: all
startPrefixMapping events will occur before the corresponding
startElement event, and all endPrefixMapping events will occur
after the corresponding endElement event, but their order is
not guaranteed.

 
Functions
       
plattformTesten()
Tests the current platform: win95, winNT, other.

 
Data
        A4 = (595.27559055118104, 841.88976377952747)
A5 = (420.94488188976374, 595.27559055118104)
PAGE_HEIGHT = 841.88976377952747
PAGE_WIDTH = 595.27559055118104
SKIP = {'all': 0, 'images': 0, 'tables': 0, 'underline': 0}
STYLES = <reportlab.lib.styles.StyleSheet1 instance>
VERBOSE = 0
cm = 28.346456692913385
defaultPageSize = (595.27559055118104, 841.88976377952747)
inch = 72.0
lod = [{'Book': 'Holy Bible, Luther Version', 'Price': '15.00 EUR'}, {'Book': 'Calendar for Daily Devotion', 'Price': '8.00 EUR'}, {'Book': 'Holy Bible, Good News Version', 'Price': '17.00 EUR'}, {'FirstName': 'Martin', 'Surname': 'Simon'}, {'FirstName': 'Steve', 'Surname': 'Miller'}, {'FirstName': 'John', 'Surname': 'Smith'}, {'StrangeField': 'StrangeValue'}]