Development/Tutorials/KWord Scripting: Difference between revisions

From KDE TechBase
(Mark for updating)
 
(10 intermediate revisions by 5 users not shown)
Line 1: Line 1:
{{Review|
* Port to KF5
* Rename to Calligra Words
}}
==Intro==
==Intro==


KWord uses [http://wiki.koffice.org/index.php?title=Kross Kross] to provide scripting with [http://www.python.org/ Python], [http://www.ruby-lang.org/ Ruby] and [http://xmelegance.org/kjsembed KDE JavaScript].
KWord2.0 uses [[Development/Languages/Kross|Kross]] to provide scripting with [http://www.python.org/ Python], [http://www.ruby-lang.org/ Ruby] and [http://xmelegance.org/kjsembed KDE JavaScript].
 
With the 2.0 release the scripts Application Programming Interface (API) is unsupported and unfinished and known to change. Use the API at your own risk! When the API is stable you can depend on future versions not breaking your scripts, this support is not present in the 2.0 release of KWord.


===The Scripting Plugin===
===The Scripting Plugin===
Line 14: Line 21:
===Scripting Handbook===
===Scripting Handbook===


The [http://kross.dipe.org/dox/kword.html KWord Scripting Handbook] contains a full reference of all objects and methods accessible from within the scripting backends.
The [http://www.koffice.org/developer/apidocs/kword-plugins-scripting/index.html KWord Scripting Handbook] contains a full reference of the functionality accessible from within the scripting backends.


The Handbook is generated from the sourcecode using doxygen and the [http://websvn.kde.org/trunk/KDE/kdelibs/kross/docs/doxy2doc.py?view=markup doxy2doc.py] Python script as postprocessor to create visible output from the by doxygen produced XML files.
The Handbook is generated from the sourcecode using doxygen and KWord's [[Development/Tutorials/KWord_Scripting#Import_combined_Doxygen_XML_File|Import Doxygen XML File]] python script.


==Samples==
==Samples==
Line 23: Line 30:


Following Python script demonstrates how to load and save files;
Following Python script demonstrates how to load and save files;
<code python>
<syntaxhighlight lang="python">
import KWord
import KWord
KWord.document().openURL("/home/myuser/myDoc.odt")
KWord.document().openURL("/home/myuser/myDoc.odt")
KWord.document().saveAs("/home/myuser/myDocCopy.odt")
KWord.document().saveAs("/home/myuser/myDocCopy.odt")
KWord.document().saveAs("/home/myuser/myDocAsText.txt")
KWord.document().saveAs("/home/myuser/myDocAsText.txt")
</code>
</syntaxhighlight>


All slots and signals within the [http://websvn.kde.org/trunk/koffice/libs/kofficecore/KoDocumentAdaptor.h?view=markup KoDocumentAdaptor] are accessible as KWord.document().
All slots and signals within the [http://websvn.kde.org/trunk/koffice/libs/kofficecore/KoDocumentAdaptor.h?view=markup KoDocumentAdaptor] are accessible as KWord.document().
Line 36: Line 43:
The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_importfile.py?view=markup sample_importfile.py] Python script implements import of content from a text or html file.
The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_importfile.py?view=markup sample_importfile.py] Python script implements import of content from a text or html file.


<code python>
<syntaxhighlight lang="python">
import KWord
import KWord
doc = KWord.mainFrameSet().document()
doc = KWord.mainFrameSet().document()
Line 43: Line 50:
#doc.setHtml( ' '.join(f.readlines()) )
#doc.setHtml( ' '.join(f.readlines()) )
f.close()
f.close()
</code>
</syntaxhighlight>


The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_exportfile.py?view=markup sample_exportfile.py] Python script implements export of content to a text or html file.
The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_exportfile.py?view=markup sample_exportfile.py] Python script implements export of content to a text or html file.


<code python>
<syntaxhighlight lang="python">
import KWord
import KWord
doc = KWord.mainFrameSet().document()
doc = KWord.mainFrameSet().document()
Line 54: Line 61:
#f.write( doc.toHtml() )
#f.write( doc.toHtml() )
f.close()
f.close()
</code>
</syntaxhighlight>
 
=== Document Structure Viewer ===
 
The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_doctree.rb?view=markup sample_doctree.rb] QtRuby script implement a document structur viewer.
 
The viewer displays the framesets, frames, documents and there objects as tree where each node may provide additional functionality like a collection of properties, text or styles.
 
[[Image:kwordscriptingdoctree.jpg]]


=== Framesets, Frames and Shapes ===
=== Framesets, Frames and Shapes ===


The following python script adds a polygon shape and then prints the name and the ID of each shape.
The following python script adds a polygon shape and then prints the name and the ID of each shape.
<code python>
<syntaxhighlight lang="python">
import KWord
import KWord
KWord.addFrame("mypoly", "KoRegularPolygonShape")
KWord.addFrame("mypoly", "KoRegularPolygonShape")
Line 73: Line 72:
     f = KWord.frame(i)
     f = KWord.frame(i)
     print "%s %s" % (f.frameSet().name(),f.shapeId())
     print "%s %s" % (f.frameSet().name(),f.shapeId())
</code>
</syntaxhighlight>


The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_insertshape.py?view=markup sample_insertshape.py] Python script implements inserting of a shape into the document.
The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_insertshape.py?view=markup sample_insertshape.py] Python script implements inserting of a shape into the document.


<code python>
<syntaxhighlight lang="python">
import KWord
import KWord
textshape = KWord.addTextFrame("MyTextShape")
textshape = KWord.addTextFrame("MyTextShape")
textshape.document().setText("Some text")
textshape.document().setText("Some text")
</code>
</syntaxhighlight>


The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_allshapes.py?view=markup sample_allshapes.py] Python script just adds all shapes into the document.
The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_allshapes.py?view=markup sample_allshapes.py] Python script just adds all shapes into the document.


<code python>
<syntaxhighlight lang="python">
import KWord
import KWord
for shapeId in KWord.shapeKeys():
for shapeId in KWord.shapeKeys():
Line 93: Line 92:
         frame.setPosition(200, 50)
         frame.setPosition(200, 50)
         frame.resize(160, 80)
         frame.resize(160, 80)
</code>
</syntaxhighlight>


=== Text content ===
=== Text content ===
Line 100: Line 99:


The following python sample adds some text at the end of the main framesets document.
The following python sample adds some text at the end of the main framesets document.
<code python>
<syntaxhighlight lang="python">
import KWord
import KWord
doc = KWord.mainFrameSet().document()
doc = KWord.mainFrameSet().document()
cursor = doc.rootFrame().lastCursorPosition()
cursor = doc.rootFrame().lastCursorPosition()
cursor.insertHtml("<b>Some text</b>")
cursor.insertHtml("<b>Some text</b>")
</code>
</syntaxhighlight>


This python sample adds some text and sets the page header and the page footer.
This python sample adds some text and sets the page header and the page footer.
<code python>
<syntaxhighlight lang="python">
import KWord
import KWord
doc = KWord.mainFrameSet().document()
doc = KWord.mainFrameSet().document()
Line 114: Line 113:
KWord.firstPageHeaderFrameSet().document().setText("Header")
KWord.firstPageHeaderFrameSet().document().setText("Header")
KWord.firstPageFooterFrameSet().document().setText("Footer")
KWord.firstPageFooterFrameSet().document().setText("Footer")
</code>
</syntaxhighlight>


Python sample that prints the url and some metainformations of the document.
Python sample that prints the url and some metainformations of the document.
<code python>
<syntaxhighlight lang="python">
import KWord
import KWord
print KWord.document().url()
print KWord.document().url()
print KWord.document().documentInfoTitle()
print KWord.document().documentInfoTitle()
print KWord.document().documentInfoAuthorName()
print KWord.document().documentInfoAuthorName()
</code>
</syntaxhighlight>


The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_lists_html.py?view=markup sample_lists_html.py] Python script demonstrates how to create lists with HTML.
The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_lists_html.py?view=markup sample_lists_html.py] Python script demonstrates how to create lists with HTML.
Line 129: Line 128:


The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_tables.py?view=markup sample_tables.py] Python script demonstrates how to deal with tables.
The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_tables.py?view=markup sample_tables.py] Python script demonstrates how to deal with tables.
=== KoStore and XML ===
The following python sample does demonstrate how to print the element-names of all xml-files that are within the KWord KoStore backend (see [http://websvn.kde.org/trunk/koffice/libs/kokross/KoScriptingOdf.h?view=markup KoScriptingOdf.h]) for our current document.
<syntaxhighlight lang="python">
import KWord
store = KWord.store()
reader = store.open("META-INF/manifest.xml")
if not reader:
    raise "Failed to read the mainfest"
paths = []
for i in range( reader.count() ):
    if reader.type(i) == "text/xml":
        paths.append( reader.path(i) )
for p in paths:
    reader = store.open(p)
    if not reader:
        raise "Failed to read %s" % p
    def onElement():
        print reader.name()
    reader.connect("onElement()", onElement)
    reader.start()
</syntaxhighlight>


=== Variables ===
=== Variables ===
Line 134: Line 157:
The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_variables.py?view=markup sample_variables.py] Python script demonstrates how to handle variables.
The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_variables.py?view=markup sample_variables.py] Python script demonstrates how to handle variables.


<code python>
<syntaxhighlight lang="python">
import KWord
import KWord
doc = KWord.mainFrameSet().document()
doc = KWord.mainFrameSet().document()
for v in doc.variableNames():
for v in doc.variableNames():
     print "name=%s value=%s" % (v, doc.variableValue(v))
     print "name=%s value=%s" % (v, doc.variableValue(v))
</code>
</syntaxhighlight>


The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/variable_readfile.py?view=markup variable_readfile.py] Python script to read a variable from a file.
The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/variable_readfile.py?view=markup variable_readfile.py] Python script to read a variable from a file.
Line 149: Line 172:
The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_actions.py?view=markup sample_actions.py] Python script demonstrates usage of actions.
The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_actions.py?view=markup sample_actions.py] Python script demonstrates usage of actions.


<code python>
<syntaxhighlight lang="python">
import KWord
import KWord
KWord.shell().slotFileNew()
KWord.shell().slotFileNew()
KWord.mainWindow().setCaption("My Caption")
KWord.mainWindow().setCaption("My Caption")
</code>
</syntaxhighlight>


The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_toolactions.py?view=markup sample_toolactions.py] Python script demonstrates how to trigger actions the current tool provides.
The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_toolactions.py?view=markup sample_toolactions.py] Python script demonstrates how to trigger actions the current tool provides.


<code python>
<syntaxhighlight lang="python">
import KWord
import KWord
tool = KWord.tool()
tool = KWord.tool()
Line 163: Line 186:
     print "%s: %s" % (n, tool.actionText(n))
     print "%s: %s" % (n, tool.actionText(n))
     tool.triggerAction(n)
     tool.triggerAction(n)
</code>
</syntaxhighlight>


The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_progressbar.py?view=markup sample_progressbar.py] Python script demonstrates how to use the progressbar.
The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_progressbar.py?view=markup sample_progressbar.py] Python script demonstrates how to use the progressbar.


<code python>
<syntaxhighlight lang="python">
import KWord
import KWord
for i in range(1,101):
for i in range(1,101):
     KWord.shell().slotProgress(i)
     KWord.shell().slotProgress(i)
KWord.shell().slotProgress(-1)
KWord.shell().slotProgress(-1)
</code>
</syntaxhighlight>


The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/sample_onlinehelp.py?view=markup sample_onlinehelp.py] Python script uses the KHTML Part to display the KWord Scripting online help.
The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/onlinehelp.py?view=markup onlinehelp.py] Python script uses the KHTML Part to display the KWord Scripting online help.


<code python>
<syntaxhighlight lang="python">
import Kross
import Kross
forms = Kross.module("forms")
forms = Kross.module("forms")
Line 184: Line 207:
part = forms.loadPart(page, "libkhtmlpart", url)
part = forms.loadPart(page, "libkhtmlpart", url)
dialog.exec_loop()
dialog.exec_loop()
</code>
</syntaxhighlight>


== Scripts ==
== Scripts ==
Line 202: Line 225:
     doxygen kspreadscripting.doxyfile
     doxygen kspreadscripting.doxyfile
     cd xml
     cd xml
     xsltproc combine.xslt index.xml | importdoxyxml.py ../kspread.html
     xsltproc combine.xslt index.xml | importdoxyxml.py kspread.html


You are also able to just generate a combined doxygen XML file with;
You are also able to just generate a combined doxygen XML file with;
Line 228: Line 251:


The python script [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/exportfile.py?view=markup exportfile.py] allows to export content to text- or html-files.
The python script [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/exportfile.py?view=markup exportfile.py] allows to export content to text- or html-files.
=== XML Viewer ===
The python script [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/xmlviewer.py?view=markup xmlviewer.py] to view the ISO OpenDocumentText XML representation of the current document displayed in KWord.
The XML Viewer does also allow to open the XML of the current document with an external application like KWrite or KXMLEditor. The "Compare..." button enables to compare the current XML with the XML of another ODT file.
[[Image:kwordxmlviewer.jpg]]
=== Document Structure Viewer ===
The [http://websvn.kde.org/trunk/koffice/kword/plugins/scripting/scripts/doctree.rb?view=markup doctree.rb] QtRuby script implement a document structur viewer.
The viewer displays the framesets, frames, documents and there objects as tree where each node may provide additional functionality like a collection of properties, text or styles.
[[Image:kwordscriptingdoctree.jpg]]

Latest revision as of 08:41, 31 May 2019

Warning
This page needs a review and probably holds information that needs to be fixed.

Parts to be reviewed:

  • Port to KF5
  • Rename to Calligra Words

Intro

KWord2.0 uses Kross to provide scripting with Python, Ruby and KDE JavaScript.

With the 2.0 release the scripts Application Programming Interface (API) is unsupported and unfinished and known to change. Use the API at your own risk! When the API is stable you can depend on future versions not breaking your scripts, this support is not present in the 2.0 release of KWord.

The Scripting Plugin

The KWord Scripting Plugin implements a plugin to dynamic access the scripting functionality from within KWord.

  • The KWScriptingPart class implements a KPart component to integrate scripting as plugin into KWord.
  • The Scripting::Module class enables access to the KWord functionality from within the scripting backends.
  • The FrameSet and Frame classes are holding the content that is displayed on screen.
  • The TextDocument class represents a QTextDocument within the Scribe text-engine KWord uses to enable editing of text content. The TextCursor implements a control structure for the successive traversal of content within such a TextDocument .

Scripting Handbook

The KWord Scripting Handbook contains a full reference of the functionality accessible from within the scripting backends.

The Handbook is generated from the sourcecode using doxygen and KWord's Import Doxygen XML File python script.

Samples

Load and save documents

Following Python script demonstrates how to load and save files;

import KWord
KWord.document().openURL("/home/myuser/myDoc.odt")
KWord.document().saveAs("/home/myuser/myDocCopy.odt")
KWord.document().saveAs("/home/myuser/myDocAsText.txt")

All slots and signals within the KoDocumentAdaptor are accessible as KWord.document().

Import and export content

The sample_importfile.py Python script implements import of content from a text or html file.

import KWord
doc = KWord.mainFrameSet().document()
f = open("/home/myuser/mytextfile.txt", "r")
doc.setText( ' '.join(f.readlines()) )
#doc.setHtml( ' '.join(f.readlines()) )
f.close()

The sample_exportfile.py Python script implements export of content to a text or html file.

import KWord
doc = KWord.mainFrameSet().document()
f = open("/home/myuser/mytextfile.txt", "w")
f.write( doc.toText() )
#f.write( doc.toHtml() )
f.close()

Framesets, Frames and Shapes

The following python script adds a polygon shape and then prints the name and the ID of each shape.

import KWord
KWord.addFrame("mypoly", "KoRegularPolygonShape")
for i in range( KWord.frameCount() ):
    f = KWord.frame(i)
    print "%s %s" % (f.frameSet().name(),f.shapeId())

The sample_insertshape.py Python script implements inserting of a shape into the document.

import KWord
textshape = KWord.addTextFrame("MyTextShape")
textshape.document().setText("Some text")

The sample_allshapes.py Python script just adds all shapes into the document.

import KWord
for shapeId in KWord.shapeKeys():
    frame = KWord.addFrame("myshape", shapeId)
    if frame:
        frame.setTextRunAround(frame.RunThrough)
        frame.setPosition(200, 50)
        frame.resize(160, 80)

Text content

The sample_text.py Python script demonstrates usage of the text engine.

The following python sample adds some text at the end of the main framesets document.

import KWord
doc = KWord.mainFrameSet().document()
cursor = doc.rootFrame().lastCursorPosition()
cursor.insertHtml("<b>Some text</b>")

This python sample adds some text and sets the page header and the page footer.

import KWord
doc = KWord.mainFrameSet().document()
doc.lastCursor().insertHtml("Even more <b>Hello World</b>")
KWord.firstPageHeaderFrameSet().document().setText("Header")
KWord.firstPageFooterFrameSet().document().setText("Footer")

Python sample that prints the url and some metainformations of the document.

import KWord
print KWord.document().url()
print KWord.document().documentInfoTitle()
print KWord.document().documentInfoAuthorName()

The sample_lists_html.py Python script demonstrates how to create lists with HTML.

The sample_lists_cursor.py Python script demonstrates how to create lists with a cursor.

The sample_tables.py Python script demonstrates how to deal with tables.

KoStore and XML

The following python sample does demonstrate how to print the element-names of all xml-files that are within the KWord KoStore backend (see KoScriptingOdf.h) for our current document.

import KWord
store = KWord.store()
reader = store.open("META-INF/manifest.xml")
if not reader:
    raise "Failed to read the mainfest"
paths = []
for i in range( reader.count() ):
    if reader.type(i) == "text/xml":
        paths.append( reader.path(i) )
for p in paths:
    reader = store.open(p)
    if not reader:
        raise "Failed to read %s" % p
    def onElement():
        print reader.name()
    reader.connect("onElement()", onElement)
    reader.start()

Variables

The sample_variables.py Python script demonstrates how to handle variables.

import KWord
doc = KWord.mainFrameSet().document()
for v in doc.variableNames():
    print "name=%s value=%s" % (v, doc.variableValue(v))

The variable_readfile.py Python script to read a variable from a file.

KWord

The sample_cursor.rb Ruby script demonstrates how to control the cursor.

The sample_actions.py Python script demonstrates usage of actions.

import KWord
KWord.shell().slotFileNew()
KWord.mainWindow().setCaption("My Caption")

The sample_toolactions.py Python script demonstrates how to trigger actions the current tool provides.

import KWord
tool = KWord.tool()
for n in tool.actionNames():
    print "%s: %s" % (n, tool.actionText(n))
    tool.triggerAction(n)

The sample_progressbar.py Python script demonstrates how to use the progressbar.

import KWord
for i in range(1,101):
    KWord.shell().slotProgress(i)
KWord.shell().slotProgress(-1)

The onlinehelp.py Python script uses the KHTML Part to display the KWord Scripting online help.

import Kross
forms = Kross.module("forms")
dialog = forms.createDialog("KHTML Part")
page = dialog.addPage("", "")
url = "http://wiki.koffice.org"
part = forms.loadPart(page, "libkhtmlpart", url)
dialog.exec_loop()

Scripts

Import from a Text or HTML File

The python script importfile.py allows to import content from text- or html-files.

Import combined Doxygen XML File

The python script importdoxyxml.py implements import of combined doxygen XML files into KWord.

As example this got used to generate the KSpread Scripting API-Reference. This is done by running doxygen with the KSpread doxygen file.

We are able to produce from within the commandline the handbook like demonstrated bellow;

   cd kspread/plugins/scripting/docs
   doxygen kspreadscripting.doxyfile
   cd xml
   xsltproc combine.xslt index.xml | importdoxyxml.py kspread.html

You are also able to just generate a combined doxygen XML file with;

   cd kspread/plugins/scripting/docs
   doxygen kspreadscripting.doxyfile
   cd xml
   xsltproc combine.xslt index.xml > ~/mydoxygen.xml

Such a combined doxygen XML file can then be imported into our running KWord instance by running "Import Doxygen XML File" python script from the Tools/Scripts-menu.

Import File with OpenOffice.org UNO

The python script ooimport.py uses the PyUNO module to access OpenOffice.org and import content from any by OpenOffice.org supported fileformat. For this an optional hidden OpenOffice.org instance need to be started. Then the script connects as client to this OpenOffice.org server instance and controls it. If the script got executed and the connecting to the server failed, then it will startup such a hidden OpenOffice.org server instance and shuts it down again once the work is done.

If the script got executed from within KWord (e.g. by using the "Tools=>Script Manager") the following dialog is displayed. The user chooses the file he likes to import and may also able to change settings related to how the connection to OpenOffice.org should be established. Then a progressdialog will be displayed while in the background we try to connect with OpenOffice.org and let it load the file and pass the content back to KWord.

That way KWord is able to optional use the OpenOffice.org import-filters to import content from file formats like;

OpenDocument Text (*.odt), OpenDocument Text Template (*.ott), OpenOffice.org 1.0 Text Document (*.sxw), OpenOffice.org 1.0 Text Document Template (*.stw), Microsoft Word 95/97/2000/XP (*.doc), Microsoft Word 95/97/2000/XP Template (*.dot), Microsoft Word 2003 XML (*.xml), Rich Text Format (*.rtf), Text (*.txt), HTML Document (*.html *.htm), DocBook (*.xml), StarWriter 1.0 - 5.0 (*.sdw), StarWriter 3.0 - 5.0 Templates (*.vor), WordPerfect Document (*.wpd), Lotus WordPro Document (*.lwp), Ichitaro 8/9/10/11 (*.jtd), Ichitaro 8/9/10/11 Template (*.jtt), Hangul WP 97 (*.hwp), WPS 2000/Office 1.0 (*.wps), etc.

Export to a Text or HTML File

The python script exportfile.py allows to export content to text- or html-files.

XML Viewer

The python script xmlviewer.py to view the ISO OpenDocumentText XML representation of the current document displayed in KWord.

The XML Viewer does also allow to open the XML of the current document with an external application like KWrite or KXMLEditor. The "Compare..." button enables to compare the current XML with the XML of another ODT file.

Document Structure Viewer

The doctree.rb QtRuby script implement a document structur viewer.

The viewer displays the framesets, frames, documents and there objects as tree where each node may provide additional functionality like a collection of properties, text or styles.