summaryrefslogtreecommitdiff
path: root/odk
diff options
context:
space:
mode:
authorChenxiong Qi <qcxhome@gmail.com>2022-09-18 15:27:31 +0800
committerHossein <hossein@libreoffice.org>2022-12-03 01:48:39 +0000
commit8f34b0d40e149b7274a1aa4ce0b33ddbf825ee52 (patch)
tree59a0066a3f521c34c866dd32e8a544eabfcff834 /odk
parentf1eaad31122024034d8e7299780eeb123204b20a (diff)
tdf#143123 Port Text Java examples to Python
The examples inside odk/examples/java/Text are ported to Python: BookmarkInsertion.java -> BookmarkInsertion.py GraphicsInserter.java -> GraphicsInserter.py HardFormatting.java -> HardFormatting.py StyleCreation.java -> StyleCreation.py SWriter.java -> SWriter.py StyleInitialization.java -> StyleInitialization.py TextDocumentStructure.java -> TextDocumentStructure.py TextReplace.java -> TextReplace.py WriterSelector.java -> WriterSelector.py Code format is checked with 'pycodestyle': pycodestyle --ignore=E501,E722 odk/examples/python/Text/*.py Some Java methods are merged when ported to Python. Signed-off-by: Chenxiong Qi <qcxhome@gmail.com> Change-Id: Ic903cfa24ef32f8edaafd7e6e2e0c757b4b1be0a Reviewed-on: https://gerrit.libreoffice.org/c/core/+/141425 Tested-by: Hossein <hossein@libreoffice.org> Reviewed-by: Hossein <hossein@libreoffice.org>
Diffstat (limited to 'odk')
-rw-r--r--odk/examples/examples.html48
-rw-r--r--odk/examples/python/Text/BookmarkInsertion.py160
-rw-r--r--odk/examples/python/Text/GraphicsInserter.py100
-rw-r--r--odk/examples/python/Text/HardFormatting.py110
-rw-r--r--odk/examples/python/Text/SWriter.py210
-rw-r--r--odk/examples/python/Text/StyleCreation.py94
-rw-r--r--odk/examples/python/Text/StyleInitialization.py109
-rw-r--r--odk/examples/python/Text/TextDocumentStructure.py79
-rw-r--r--odk/examples/python/Text/TextReplace.py106
-rw-r--r--odk/examples/python/Text/WriterSelector.py67
10 files changed, 1083 insertions, 0 deletions
diff --git a/odk/examples/examples.html b/odk/examples/examples.html
index 2b23080961fb..6cfcc045ad1f 100644
--- a/odk/examples/examples.html
+++ b/odk/examples/examples.html
@@ -461,6 +461,54 @@
</tr>
<tr>
<td>
+ <table class="table4">
+ <tbody>
+ <tr class="thead">
+ <td class="cell20">Text Document Examples</td>
+ <td class="cell80">Description</td>
+ </tr>
+ <tr>
+ <td class="cell20"><a href="python/Text/" title="link to the source directory of the Python Text examples">BookmarkInsertion</a></td>
+ <td class="cell80">This application opens an empty text document and enters an example text. Afterwards, some bookmarks will be inserted.</td>
+ </tr>
+ <tr>
+ <td class="cell20"><a href="python/Text/" title="link to the source directory of the Python Text examples">HardFormatting</a></td>
+ <td class="cell80">This program opens an empty text document and enters an example text, some text attributes will be inspected, and the <a href="%DOXYGEN_PREFIX1%/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1beans.html#PropertyState" title="link into the IDL reference to the enum com.sun.star.beans.PropertyState">PropertyState</a> will be checked from the selection.</td>
+ </tr>
+ <tr>
+ <td class="cell20"><a href="python/Text/" title="link to the source directory of the Python Text examples">SWriter</a></td>
+ <td class="cell80">This program opens an empty text document and enters some text, and a text table, a colored text, and text frame will be inserted.</td>
+ </tr>
+ <tr>
+ <td class="cell20"><a href="python/Text/" title="link to the source directory of the Python Text examples">StyleCreation</a></td>
+ <td class="cell80">This program opens an empty text document. Then a new paragraph style will be created, and applied.</td>
+ </tr>
+ <tr>
+ <td class="cell20"><a href="python/Text/" title="link to the source directory of the Python Text examples">StyleInitialization</a></td>
+ <td class="cell80">This program opens an empty text document and enters an example text. The paragraph collection will be used, in order to apply a different paragraph style on the paragraphs.</td>
+ </tr>
+ <tr>
+ <td class="cell20"><a href="python/Text/" title="link to the source directory of the Python Text examples">TextDocumentStructure</a></td>
+ <td class="cell80">This program opens an empty text document and enters an example text. Document structure will be printed out. Looping through the paragraphs and their portions in a more Pythonic way instead of calling the methods of <a href="%DOXYGEN_PREFIX1%/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1container_1_1XEnumeration.html" title="link to the IDL reference to the interface com.sun.star.container.XEnumeration">XEnumeration</a> interface.</td>
+ </tr>
+ <tr>
+ <td class="cell20"><a href="python/Text/" title="link to the source directory of the Python Text examples">TextReplace</a></td>
+ <td class="cell80">The program opens an empty text document and enters an example text, and some English spelled words will be replaced with US spelled words.</td>
+ </tr>
+ <tr>
+ <td class="cell20"><a href="python/Text/" title="link to the source directory of the Python Text examples">GraphicsInserter</a></td>
+ <td class="cell80">The GraphicsInserter creates a graphics object on an empty text document by setting its position, width, height, and URL.</td>
+ </tr>
+ <tr>
+ <td class="cell20"><a href="python/Text/" title="link to the source directory of the Python Text examples">WriterSelector</a></td>
+ <td class="cell80">This program gives you information on the selected objects, e.g. text range, text frame or graphics.</td>
+ </tr>
+ </tbody>
+ </table>
+ </td>
+ </tr>
+ <tr>
+ <td>
<table class="table3">
<tr>
<td colspan="3">
diff --git a/odk/examples/python/Text/BookmarkInsertion.py b/odk/examples/python/Text/BookmarkInsertion.py
new file mode 100644
index 000000000000..5b801f6121ea
--- /dev/null
+++ b/odk/examples/python/Text/BookmarkInsertion.py
@@ -0,0 +1,160 @@
+# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
+#
+# This file is part of the LibreOffice project.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+
+import officehelper
+import sys
+import traceback
+
+
+FIRST_PARAGRAPH = (
+ "He heard quiet steps behind him. That didn't bode well. Who could be following "
+ "him this late at night and in this deadbeat part of town? And at this "
+ "particular moment, just after he pulled off the big time and was making off "
+ "with the greenbacks. Was there another crook who'd had the same idea, and was "
+ "now watching him and waiting for a chance to grab the fruit of his labor?"
+)
+
+SECOND_PARAGRAPH = (
+ "Or did the steps behind him mean that one of many bloody officers in town was "
+ "on to him and just waiting to pounce and snap those cuffs on his wrists? He "
+ "nervously looked all around. Suddenly he saw the alley. Like lightning he "
+ "darted off to the left and disappeared between the two warehouses almost "
+ "falling over the trash can lying in the middle of the sidewalk. He tried to "
+ "nervously tap his way along in the inky darkness and suddenly stiffened: it was "
+ "a dead-end, he would have to go back the way he had come"
+)
+
+THIRD_PARAGRAPH = (
+ "The steps got louder and louder, he saw the black outline of a figure coming "
+ "around the corner. Is this the end of the line? he thought pressing himself "
+ "back against the wall trying to make himself invisible in the dark, was all "
+ "that planning and energy wasted? He was dripping with sweat now, cold and wet, "
+ "he could smell the brilliant fear coming off his clothes. Suddenly next to him, "
+ "with a barely noticeable squeak, a door swung quietly to and fro in the night's "
+ "breeze."
+)
+
+
+def create_example_text(component):
+ """Create example text
+
+ :param component: object which implements com.sun.star.text.XTextDocument interface.
+ """
+ try:
+ cursor = component.getText().createTextCursor()
+ cursor.setString(FIRST_PARAGRAPH)
+ cursor.collapseToEnd()
+ cursor.setString(SECOND_PARAGRAPH)
+ cursor.collapseToEnd()
+ cursor.setString(THIRD_PARAGRAPH)
+ cursor.gotoStart(False)
+ except:
+ traceback.print_exc()
+
+
+def find_first(document, search_str):
+ """Find the text
+
+ :param document: object which implements com.sun.star.text.XTextDocument interface.
+ :param str search_str: the search string.
+ :return: object representing the searched text, which implements com.sun.star.text.XTextRange interface.
+ :rtype: com.sun.star.uno.XInterface
+ """
+ try:
+ descriptor = document.createSearchDescriptor()
+ descriptor.setSearchString(search_str)
+ descriptor.setPropertyValue("SearchRegularExpression", True)
+ return document.findFirst(descriptor)
+ except:
+ traceback.print_exc()
+ return None
+
+
+def insert_bookmark(document, text_range, bookmark_name):
+ """Insert bookmark
+
+ :param document: object which implements om.sun.star.text.XTextDocument interface.
+ :param text_range: object representing the text range bookmark is inserted for.
+ This object should implement com.sun.star.text.XTextRange interface.
+ :param str bookmark_name: bookmark name.
+ """
+ try:
+ bookmark = document.createInstance("com.sun.star.text.Bookmark")
+ bookmark.setName(bookmark_name)
+ document.getText().insertTextContent(text_range, bookmark, True)
+ print("Insert bookmark:", bookmark_name)
+ except:
+ traceback.print_exc()
+
+
+def mark_list(component, mlist, prefix):
+ """Mark the matched text
+
+ :param component: object which implements com.sun.star.text.XTextDocument interface.
+ :param list[str] mlist: list of patterns to search text from document.
+ :param str prefix: prefix used to construct bookmark name.
+ """
+ try:
+ for i, search_str in enumerate(mlist):
+ search = find_first(component, search_str)
+ if not search:
+ continue
+ insert_bookmark(component, search, f"{prefix}{i}")
+ except:
+ traceback.print_exc()
+ sys.exit(1)
+
+
+def get_desktop():
+ desktop = None
+ try:
+ remote_context = officehelper.bootstrap()
+ srv_mgr = remote_context.getServiceManager()
+ if srv_mgr is None:
+ print("Can't create a desktop. No connection, no remote office servicemanager available!")
+ else:
+ desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context)
+ print("Connected to a running office ...")
+ except:
+ traceback.print_exc()
+ sys.exit(1)
+ return desktop
+
+
+def main():
+ desktop = get_desktop()
+ if desktop is None:
+ return
+
+ # Open an empty text document.
+ try:
+ doc = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, tuple([]))
+ except:
+ traceback.print_exc()
+ sys.exit(1)
+
+ create_example_text(doc)
+
+ mOffending = ["negro(e|es)?", "bor(ed|ing)?", "bloody?", "bleed(ing)?"]
+ mBad = ["possib(le|ilit(y|ies))", "real(ly)+", "brilliant"]
+
+ sOffendPrefix = "Offending"
+ sBadPrefix = "BadStyle"
+
+ mark_list(doc, mOffending, sOffendPrefix)
+ mark_list(doc, mBad, sBadPrefix)
+
+ print("Done")
+
+
+if __name__ == "__main__":
+ main()
+
+
+# vim: set shiftwidth=4 softtabstop=4 expandtab:
diff --git a/odk/examples/python/Text/GraphicsInserter.py b/odk/examples/python/Text/GraphicsInserter.py
new file mode 100644
index 000000000000..3d09aedd5a13
--- /dev/null
+++ b/odk/examples/python/Text/GraphicsInserter.py
@@ -0,0 +1,100 @@
+# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
+#
+# This file is part of the LibreOffice project.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+
+import argparse
+import sys
+import traceback
+from os.path import isfile, dirname, join
+
+import officehelper
+from com.sun.star.beans import PropertyValue
+from com.sun.star.text.TextContentAnchorType import AT_PARAGRAPH
+
+LOG_FILE = join(dirname(__file__), "log.txt")
+
+
+def insert_graphic(filename):
+ remote_context = officehelper.bootstrap()
+ srv_mgr = remote_context.getServiceManager()
+ desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context)
+
+ doc_url = "private:factory/swriter"
+ doc = desktop.loadComponentFromURL(doc_url, "_blank", 0, tuple())
+
+ log_file = open(LOG_FILE, "w")
+
+ text = doc.getText()
+ cursor = text.createTextCursor()
+
+ try:
+ graphic = doc.createInstance("com.sun.star.text.TextGraphicObject")
+ except:
+ traceback.print_exc(file=log_file)
+ return
+
+ log_file.write("inserting graphic\n")
+ try:
+ text.insertTextContent(cursor, graphic, True)
+ except:
+ print("Could not insert Content")
+ traceback.print_exc()
+ return
+
+ log_file.write("adding graphic\n")
+ try:
+ graphic_url = f"file://{filename}".replace("\\", "/")
+ print("insert graphic: %s", graphic_url)
+ graphic_provider = srv_mgr.createInstanceWithContext(
+ "com.sun.star.graphic.GraphicProvider", remote_context
+ )
+ loaded_graphic = graphic_provider.queryGraphic(
+ (PropertyValue(Name="URL", Value=graphic_url),)
+ )
+
+ # Setting the graphic url
+ graphic.setPropertyValue("Graphic", loaded_graphic)
+
+ # Set properties for the inserted graphic
+ graphic.setPropertyValue("AnchorType", AT_PARAGRAPH)
+ # Setting the horizontal position
+ graphic.setPropertyValue("HoriOrientPosition", 5500)
+ # Setting the vertical position
+ graphic.setPropertyValue("VertOrientPosition", 4200)
+ # Setting the width
+ graphic.setPropertyValue("Width", 4400)
+ # Setting the height
+ graphic.setPropertyValue("Height", 4000)
+ except:
+ print("Couldn't set property 'GraphicURL'")
+ traceback.print_exc(file=log_file)
+
+ log_file.close()
+
+
+def is_file(value):
+ if not isfile(value):
+ raise argparse.ArgumentTypeError(f"File {value} is not an image file.")
+ return value
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("image", type=is_file, help="Path to an image file.")
+ args = parser.parse_args()
+ try:
+ insert_graphic(args.image)
+ except:
+ traceback.print_exc()
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
+
+# vim: set shiftwidth=4 softtabstop=4 expandtab:
diff --git a/odk/examples/python/Text/HardFormatting.py b/odk/examples/python/Text/HardFormatting.py
new file mode 100644
index 000000000000..9a9734c60bae
--- /dev/null
+++ b/odk/examples/python/Text/HardFormatting.py
@@ -0,0 +1,110 @@
+# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
+#
+# This file is part of the LibreOffice project.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+
+import officehelper
+import sys
+import traceback
+
+from com.sun.star.awt import Size
+from com.sun.star.awt.FontWeight import BOLD
+from com.sun.star.beans.PropertyState import AMBIGUOUS_VALUE
+from com.sun.star.beans.PropertyState import DEFAULT_VALUE
+from com.sun.star.beans.PropertyState import DIRECT_VALUE
+from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
+
+
+def get_desktop():
+ desktop = None
+ try:
+ remote_context = officehelper.bootstrap()
+ srv_mgr = remote_context.getServiceManager()
+ if srv_mgr is None:
+ print("Can't create a desktop. No connection, no remote office servicemanager available!")
+ else:
+ desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context)
+ except:
+ traceback.print_exc()
+ sys.exit(1)
+ return desktop
+
+
+def main():
+ desktop = get_desktop()
+ if desktop is None:
+ return
+
+ try:
+ doc = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, tuple())
+
+ text = doc.getText()
+ cursor = text.createTextCursor()
+
+ text.insertString(cursor, "Headline", False)
+ text.insertControlCharacter(cursor, PARAGRAPH_BREAK, False)
+ text.insertString(cursor, "A very short paragraph for illustration only", False)
+
+ # Start 'Hard formatting'
+ # the text range not the cursor contains the 'parastyle' property
+ text_range = text.getEnd()
+ text_range.gotoStart(False)
+ text_range.gotoEndOfParagraph(True)
+
+ # Later, we will go through words in this text range
+ text_range = text_range.getText().getStart()
+ # Display the current text attributes
+ print("Parastyle:", text_range.getPropertyValue("ParaStyleName"))
+ print("Fontname: ", text_range.getPropertyValue("CharFontName"))
+ print("Weight: ", text_range.getPropertyValue("CharWeight"))
+
+ # Move around
+ text_range.gotoNextWord(False)
+ text_range.gotoNextWord(False)
+ text_range.gotoEndOfWord(True)
+ # And set text attributes
+ text_range.setPropertyValue("CharWeight", BOLD)
+ text_range.setPropertyValue("CharColor", 255)
+ # Then, display the text attributes
+ print("Parastyle:", text_range.getPropertyValue("ParaStyleName"))
+ print("Fontname: ", text_range.getPropertyValue("CharFontName"))
+ print("Weight: ", text_range.getPropertyValue("CharWeight"))
+
+ # the PropertyState contains information where the attribute is set,
+ # is a text part hard formatted or not.
+ check_property_state(text_range, text_range.getPropertyState("CharWeight"))
+
+ print("Increase the selection with three characters")
+ text_range.goRight(3, True)
+ check_property_state(text_range, text_range.getPropertyState("CharWeight"))
+
+ print("Set the default value on the selection")
+ text_range.setPropertyToDefault("CharWeight")
+ # Then, check again
+ check_property_state(text_range, text_range.getPropertyState("CharWeight"))
+ except:
+ traceback.print_exc()
+ sys.exit(1)
+
+ print("Done")
+
+
+def check_property_state(text_range, prop_state):
+ if prop_state == DIRECT_VALUE:
+ print("-> The selection", f"'{text_range.getString()}'", "completely hard formatted")
+ elif prop_state == DEFAULT_VALUE:
+ print("-> The selection", f"'{text_range.getString()}'", "isn't hard formatted")
+ elif prop_state == AMBIGUOUS_VALUE:
+ print("-> The selection", f"'{text_range.getString()}'", "isn't completely hard formatted")
+ else:
+ print("No PropertyState found")
+
+
+if __name__ == "__main__":
+ main()
+
+# vim: set shiftwidth=4 softtabstop=4 expandtab:
diff --git a/odk/examples/python/Text/SWriter.py b/odk/examples/python/Text/SWriter.py
new file mode 100644
index 000000000000..3af42f352e70
--- /dev/null
+++ b/odk/examples/python/Text/SWriter.py
@@ -0,0 +1,210 @@
+# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
+#
+# This file is part of the LibreOffice project.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+
+import officehelper
+import sys
+import traceback
+
+from com.sun.star.awt import Size
+from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
+from com.sun.star.text.TextContentAnchorType import AS_CHARACTER
+
+
+def main():
+ try:
+ # Step 1: bootstrap UNO and get the remote component context. The
+ # context can be used to get the service manager.
+ remote_context = officehelper.bootstrap()
+ print("Connected to a running office ...")
+ srv_mgr = remote_context.getServiceManager()
+ desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context)
+
+ # Step 2: open an empty document. In this case it's a writer document.
+ # For this purpose an instance of com.sun.star.frame.Desktop is
+ # created. It's interface XDesktop provides the XComponentLoader,
+ # which is used to open the document via loadComponentFromURL
+ print("Opening an empty Writer document")
+ doc_url = "private:factory/swriter"
+ doc = desktop.loadComponentFromURL(doc_url, "_blank", 0, tuple())
+ except Exception as e:
+ print(f"d", file=sys.stderr)
+ traceback.print_exc()
+ sys.exit(1)
+
+ generate(doc)
+
+
+def generate(doc):
+ # Step 3: insert some text
+ text = doc.getText()
+ cursor = text.createTextCursor()
+
+ text.insertString(cursor, "The first line in the newly created text document.\n", False)
+ text.insertString(cursor, "Now we're in the second line\n", False)
+
+ # Step 4: insert a text table
+ insert_table(doc, text, cursor)
+
+ # Step 5: insert a colored text
+ try:
+ cursor.setPropertyValue("CharColor", 255)
+ cursor.setPropertyValue("CharShadowed", True)
+ except:
+ print("Couldn't change the color", file=sys.stderr)
+ traceback.print_exc()
+
+ try:
+ text.insertControlCharacter(cursor, PARAGRAPH_BREAK, False)
+ except Exception as e:
+ print(f"Couldn't insert break: {e}", file=sys.stderr)
+ traceback.print_exc()
+
+ print("Inserting colored Text")
+ text.insertString(cursor, " This is a colored Text - blue with shadow\n", False)
+
+ try:
+ text.insertControlCharacter(cursor, PARAGRAPH_BREAK, False)
+ except Exception as e:
+ print(f"Couldn't insert break: {e}", file=sys.stderr)
+ traceback.print_exc()
+
+ # Step 6: insert a text frame
+ insert_frame_with_text(doc, text, cursor)
+
+ try:
+ text.insertControlCharacter(cursor, PARAGRAPH_BREAK, False)
+ except Exception as e:
+ print(f"Couldn't insert break: {e}", file=sys.stderr)
+ traceback.print_exc()
+
+ try:
+ cursor.setPropertyValue("CharColor", 65536)
+ cursor.setPropertyValue("CharShadowed", False)
+ except Exception as e:
+ print(f"Couldn't change the color: {e}", file=sys.stderr)
+
+ text.insertString(cursor, " That's all for now !!", False)
+
+ print("done")
+
+
+def insert_table(doc, text, cursor):
+ print("Inserting a text table")
+ try:
+ text_table = doc.createInstance("com.sun.star.text.TextTable")
+ except Exception as e:
+ print(f"Couldn't create instance of TextTable: {e}", file=sys.stderr)
+ traceback.print_exc()
+ return
+
+ # initialize the text table with 4 columns an 4 rows
+ text_table.initialize(4, 4)
+
+ try:
+ text.insertTextContent(cursor, text_table, False)
+ except Exception as e:
+ print(f"Couldn't insert the table: {e}", file=sys.stderr)
+ traceback.print_exc()
+ return
+
+ # Get the first row
+ rows = text_table.getRows()
+ first_row = rows[0]
+
+ try:
+ # Set properties of the text table
+ text_table.setPropertyValue("BackTransparent", False)
+ text_table.setPropertyValue("BackColor", 13421823)
+ # Set properties of the first row
+ first_row.setPropertyValue("BackTransparent", False)
+ first_row.setPropertyValue("BackColor", 6710932)
+ except Exception as e:
+ print(f"Couldn't change the color: {e}", file=sys.stderr)
+ traceback.print_exc()
+
+ print("Write text in the table headers")
+ insert_into_cell("A1", "FirstColumn", text_table)
+ insert_into_cell("B1", "SecondColumn", text_table)
+ insert_into_cell("C1", "ThirdColumn", text_table)
+ insert_into_cell("D1", "SUM", text_table)
+
+ print("Insert something in the text table")
+ data = (
+ ("A2", 22.5, False),
+ ("B2", 5615.3, False),
+ ("C2", -2315.7, False),
+ ("D2", "sum <A2:C2>", True),
+ ("A3", 21.5, False),
+ ("B3", 615.3, False),
+ ("C3", -315.7, False),
+ ("D3", "sum <A3:C3>", True),
+ ("A4", 121.5, False),
+ ("B4", -615.3, False),
+ ("C4", 415.7, False),
+ ("D4", "sum <A4:C4>", True),
+ )
+ for cell_name, value, is_formula in data:
+ cell = text_table.getCellByName(cell_name)
+ if is_formula:
+ cell.setFormula(value)
+ else:
+ cell.setValue(value)
+
+
+def insert_frame_with_text(doc, text, cursor):
+ try:
+ text_frame = doc.createInstance("com.sun.star.text.TextFrame")
+ frame_size = Size()
+ frame_size.Height = 400
+ frame_size.Width = 15000
+ text_frame.setSize(frame_size)
+ except Exception as e:
+ print(f"Couldn't create instance: {e}", file=sys.stderr)
+ traceback.print_exc()
+ return
+
+ # Change the AnchorType
+ try:
+ text_frame.setPropertyValue("AnchorType", AS_CHARACTER)
+ except Exception as e:
+ print(f"Couldn't change the color: {e}", file=sys.stderr)
+ traceback.print_exc()
+
+ print("Insert the text frame")
+
+ try:
+ text.insertTextContent(cursor, text_frame, False)
+ except Exception as e:
+ print(f"Couldn't insert the frame: {e}", file=sys.stderr)
+ traceback.print_exc()
+
+ frame_text = text_frame.getText()
+ frame_cursor = frame_text.createTextCursor()
+ s = "The first line in the newly created text frame."
+ text_frame.insertString(frame_cursor, s, False)
+ s = "\nWith this second line the height of the frame raises."
+ text_frame.insertString(frame_cursor, s, False)
+
+
+def insert_into_cell(cell_name: str, content: str, text_table):
+ cell = text_table.getCellByName(cell_name)
+ cursor = cell.createTextCursor()
+ try:
+ cursor.setPropertyValue("CharColor", 16777215)
+ except Exception as e:
+ print(f"Fail to set CharColor property: {e}", file=sys.stderr)
+ traceback.print_exc()
+ # inserting some Text
+ cell.setString(content)
+
+
+if __name__ == "__main__":
+ main()
+
+# vim: set shiftwidth=4 softtabstop=4 expandtab:
diff --git a/odk/examples/python/Text/StyleCreation.py b/odk/examples/python/Text/StyleCreation.py
new file mode 100644
index 000000000000..629b530e9f83
--- /dev/null
+++ b/odk/examples/python/Text/StyleCreation.py
@@ -0,0 +1,94 @@
+# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
+#
+# This file is part of the LibreOffice project.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+
+import officehelper
+import sys
+import traceback
+
+from com.sun.star.awt.FontWeight import BOLD
+from com.sun.star.style.BreakType import PAGE_AFTER
+from com.sun.star.style.ParagraphAdjust import CENTER
+
+NEW_STYLE_NAME = "myheading"
+
+
+def create_style(component):
+ properties = component.createInstance("com.sun.star.style.ParagraphStyle")
+ properties.setPropertyValue("CharFontName", "Liberation Sans")
+ print("set name of the font to 'Liberation Sans'")
+
+ properties.setPropertyValue("CharHeight", float(36))
+ print("Change the height of th font to 36")
+
+ properties.setPropertyValue("CharWeight", float(BOLD))
+ print("set the font attribute 'Bold'")
+
+ properties.setPropertyValue("CharAutoKerning", True)
+ print("set the paragraph attribute 'AutoKerning'")
+
+ properties.setPropertyValue("ParaAdjust", CENTER)
+ print("set the paragraph adjust to LEFT")
+
+ properties.setPropertyValue("ParaFirstLineIndent", 0)
+ print("set the first line indent to 0 cm")
+
+ properties.setPropertyValue("BreakType", PAGE_AFTER)
+ print("set the paragraph attribute Breaktype to PageAfter")
+
+ # insert the new Paragraph style in the Paragraph style collection
+ style_families = component.getStyleFamilies()
+ paragraph_style_col = style_families["ParagraphStyles"]
+ paragraph_style_col[NEW_STYLE_NAME] = properties
+ print("create new paragraph style, with the values from the Propertyset")
+
+
+def apply_style(component):
+ text_range = component.getText().getStart()
+ # change the value from the property 'ParaStyle' to apply the Paragraph style
+ # To run the sample with StarOffice 5.2 you'll have to change
+ # 'ParaStyleName' to 'ParaStyle' in the next line
+ text_range.setPropertyValue("ParaStyleName", NEW_STYLE_NAME)
+ print("apply the new paragraph style")
+
+
+def get_desktop():
+ desktop = None
+ try:
+ remote_context = officehelper.bootstrap()
+ srv_mgr = remote_context.getServiceManager()
+ if srv_mgr is None:
+ print("Can't create a desktop. No connection, no remote office servicemanager available!")
+ else:
+ desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context)
+ except:
+ traceback.print_exc()
+ sys.exit(1)
+ return desktop
+
+
+def main():
+ desktop = get_desktop()
+ if desktop is None:
+ return
+
+ try:
+ doc = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, tuple())
+ create_style(doc)
+ apply_style(doc)
+ except:
+ traceback.print_exc()
+ sys.exit(1)
+
+ print("Done")
+
+
+if __name__ == "__main__":
+ main()
+
+# vim: set shiftwidth=4 softtabstop=4 expandtab:
diff --git a/odk/examples/python/Text/StyleInitialization.py b/odk/examples/python/Text/StyleInitialization.py
new file mode 100644
index 000000000000..a4d29b34431e
--- /dev/null
+++ b/odk/examples/python/Text/StyleInitialization.py
@@ -0,0 +1,109 @@
+# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
+#
+# This file is part of the LibreOffice project.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+
+import officehelper
+import sys
+import traceback
+
+from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
+
+
+def get_desktop():
+ desktop = None
+ try:
+ remote_context = officehelper.bootstrap()
+ srv_mgr = remote_context.getServiceManager()
+ if srv_mgr is None:
+ print("Can't create a desktop. No connection, no remote office servicemanager available!")
+ else:
+ desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context)
+ except:
+ traceback.print_exc()
+ sys.exit(1)
+ return desktop
+
+
+def main():
+ desktop = get_desktop()
+ if desktop is None:
+ return
+
+ try:
+ doc_url = "private:factory/swriter"
+ doc = desktop.loadComponentFromURL(doc_url, "_blank", 0, tuple())
+
+ text = doc.getText()
+ cursor = text.createTextCursor()
+
+ try:
+ cursor.setPropertyValue("CharFontName", "Arial")
+ except:
+ pass
+ text.insertString(cursor, "Headline", False)
+
+ try:
+ cursor.setPropertyValue("CharFontName", "Liberation Sans")
+ except:
+ pass
+ text.insertControlCharacter(cursor, PARAGRAPH_BREAK, False)
+ text.insertString(cursor, "A very short paragraph for illustration only", False)
+
+ # The text range not the cursor contains the 'ParaStyleName' property
+ text_range = text.getEnd()
+ # To run the sample with StarOffice 5.2 you'll have to change
+ # 'ParaStyleName' to 'ParaStyle' in the next line
+ print("Current Parastyle:", text_range.getPropertyValue("ParaStyleName"))
+
+ # There are two way to travel through the paragraphs, with a paragraph
+ # cursor, or an enumeration. You find both ways in this example
+
+ # The first way, with the paragraph cursor
+ # Object text_range supports interface com.sun.star.text.XParagraphCursor
+ text_range.gotoStart(False)
+ text_range.gotoEndOfParagraph(True)
+
+ # The second way, with the paragraph enumeration
+ paragraph_enumeration = text.createEnumeration()
+ while paragraph_enumeration.hasMoreElements():
+ paragraph = paragraph_enumeration.nextElement()
+ paragraph_text = paragraph.getAnchor().getString()
+ # Create a cursor from this paragraph
+ paragraph_cursor = paragraph.getAnchor().getText().createTextCursor()
+
+ # Goto the start and end of the paragraph
+ paragraph_cursor.gotoStart(False)
+ paragraph_cursor.gotoEnd(True)
+
+ portion_enumeration = paragraph.createEnumeration()
+ while portion_enumeration.hasMoreElements():
+ word = portion_enumeration.nextElement()
+ print("Content of the paragraph:", word.getString())
+
+ # Find a paragraph style by a specific font name and apply the found
+ # style to paragraph.
+ style_families = doc.getStyleFamilies()
+ styles = style_families["ParagraphStyles"]
+ for style_name in styles.getElementNames():
+ style = styles[style_name]
+ font_name = style.getPropertyValue("CharFontName").lower()
+ if font_name == "liberation mono":
+ text_range.setPropertyValue("ParaStyleName", style_name)
+ print("Apply the paragraph style:", style_name)
+ break
+ except:
+ traceback.print_exc()
+
+ print("Done")
+
+
+if __name__ == "__main__":
+ main()
+
+
+# vim: set shiftwidth=4 softtabstop=4 expandtab:
diff --git a/odk/examples/python/Text/TextDocumentStructure.py b/odk/examples/python/Text/TextDocumentStructure.py
new file mode 100644
index 000000000000..da677113a188
--- /dev/null
+++ b/odk/examples/python/Text/TextDocumentStructure.py
@@ -0,0 +1,79 @@
+# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
+#
+# This file is part of the LibreOffice project.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+
+import officehelper
+import sys
+import traceback
+
+from com.sun.star.awt.FontWeight import BOLD
+from com.sun.star.beans.PropertyState import AMBIGUOUS_VALUE
+from com.sun.star.beans.PropertyState import DEFAULT_VALUE
+from com.sun.star.beans.PropertyState import DIRECT_VALUE
+
+
+def main():
+ try:
+ remote_context = officehelper.bootstrap()
+ srv_mgr = remote_context.getServiceManager()
+ desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context)
+
+ doc_url = "private:factory/swriter"
+ doc = desktop.loadComponentFromURL(doc_url, "_blank", 0, tuple())
+ text = doc.getText()
+ create_example_data(text)
+ display_structure(text)
+ except:
+ traceback.print_exc()
+ sys.exit(1)
+
+ print("done")
+
+
+def create_example_data(text):
+ try:
+ text.setString("This is an example sentence")
+ cursor = text.getStart()
+ cursor.gotoNextWord(False)
+ cursor.gotoNextWord(False)
+ cursor.gotoEndOfWord(True)
+ cursor.setPropertyValue("CharWeight", BOLD)
+ print("create example data")
+ except:
+ traceback.print_exc()
+
+
+def display_structure(text):
+ print("Document structure:")
+ # Create an enumeration of all paragraphs
+ paragraph_enum = text.createEnumeration()
+ # Loop through all paragraphs of the document
+ for element in paragraph_enum:
+ if not element.supportsService("com.sun.star.text.Paragraph"):
+ print("The text portion isn't a text paragraph")
+ continue
+
+ print("This is a Paragraph")
+ for portion in element.createEnumeration():
+ print("Text from the portion:", f"{portion.getString()}")
+ print("Name of the font:", portion.getPropertyValue("CharFontName"))
+ char_weight = portion.getPropertyState("CharWeight")
+ if char_weight == AMBIGUOUS_VALUE:
+ print(" - The text range contains more than one different attributes")
+ elif char_weight == DIRECT_VALUE:
+ print(" - The text range contains hard formats")
+ elif char_weight == DEFAULT_VALUE:
+ print(" - The text range doesn't contains hard formats")
+ else:
+ pass # Do nothing
+
+
+if __name__ == "__main__":
+ main()
+
+# vim: set shiftwidth=4 softtabstop=4 expandtab:
diff --git a/odk/examples/python/Text/TextReplace.py b/odk/examples/python/Text/TextReplace.py
new file mode 100644
index 000000000000..78d301998fe4
--- /dev/null
+++ b/odk/examples/python/Text/TextReplace.py
@@ -0,0 +1,106 @@
+# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
+#
+# This file is part of the LibreOffice project.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+
+import officehelper
+import sys
+import traceback
+
+from com.sun.star.awt import Size
+from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
+from com.sun.star.text.TextContentAnchorType import AS_CHARACTER
+
+
+def get_desktop():
+ desktop = None
+ try:
+ remote_context = officehelper.bootstrap()
+ srv_mgr = remote_context.getServiceManager()
+ if srv_mgr is None:
+ print("Can't create a desktop. No connection, no remote office servicemanager available!")
+ else:
+ desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context)
+ except:
+ traceback.print_exc()
+ sys.exit(1)
+ return desktop
+
+
+def main():
+ desktop = get_desktop()
+ if desktop is None:
+ return
+
+ print("Opening an empty Writer document")
+
+ try:
+ doc = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, tuple())
+ except:
+ traceback.print_exc()
+ sys.exit(1)
+
+ create_example_data(doc)
+
+ british_words = ["colour", "neighbour", "centre", "behaviour", "metre", "through"]
+ us_words = ["color", "neighbor", "center", "behavior", "meter", "thru"]
+
+ try:
+ replace_descriptor = doc.createReplaceDescriptor()
+ print("Change all occurrences of ...")
+ for british_word, us_word in zip(british_words, us_words):
+ replace_descriptor.setSearchString(british_word)
+ replace_descriptor.setReplaceString(us_word)
+ # Replace all words
+ replaced_cnt = doc.replaceAll(replace_descriptor)
+ if replaced_cnt > 0:
+ print("Replaced", british_word, "with", us_word)
+ except:
+ traceback.print_exc()
+
+ print("Done")
+
+
+def create_example_data(doc):
+ try:
+ text = doc.getText()
+ cursor = text.createTextCursor()
+ text.insertString(cursor, "He nervously looked all around. Suddenly he saw his ", False)
+
+ text.insertString(cursor, "neighbour ", True)
+ cursor.setPropertyValue("CharColor", 255) # Set the word blue
+
+ cursor.gotoEnd(False) # Go to last character
+ cursor.setPropertyValue("CharColor", 0)
+ content = (
+ "in the alley. Like lightning he darted off to the left and disappeared between the "
+ "two warehouses almost falling over the trash can lying in the "
+ )
+ text.insertString(cursor, content, False)
+
+ text.insertString(cursor, "centre ", True)
+ cursor.setPropertyValue("CharColor", 255) # Set the word blue
+
+ cursor.gotoEnd(False) # Go to last character
+ cursor.setPropertyValue("CharColor", 0)
+ text.insertString(cursor, "of the sidewalk.", False)
+
+ text.insertControlCharacter(cursor, PARAGRAPH_BREAK, False)
+ content = (
+ "He tried to nervously tap his way along in the inky darkness and suddenly stiffened: "
+ "it was a dead-end, he would have to go back the way he had come."
+ )
+ text.insertString(cursor, content, False)
+ cursor.gotoStart(False)
+ except:
+ traceback.print_exc()
+
+
+if __name__ == "__main__":
+ main()
+
+# vim: set shiftwidth=4 softtabstop=4 expandtab:
diff --git a/odk/examples/python/Text/WriterSelector.py b/odk/examples/python/Text/WriterSelector.py
new file mode 100644
index 000000000000..f822fded0631
--- /dev/null
+++ b/odk/examples/python/Text/WriterSelector.py
@@ -0,0 +1,67 @@
+# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
+#
+# This file is part of the LibreOffice project.
+#
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+
+import sys
+import traceback
+import officehelper
+
+
+def main():
+ try:
+ remote_context = officehelper.bootstrap()
+ print("Connected to a running office ...")
+ srv_mgr = remote_context.getServiceManager()
+ desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context)
+
+ print("Opening an empty Writer document")
+ doc_url = "private:factory/swriter"
+ doc = desktop.loadComponentFromURL(doc_url, "_blank", 0, tuple())
+
+ text = doc.getText()
+ text.setString("Please select something in this text and press then \"return\" in the shell "
+ "where you have started the example.\n")
+
+ # Returned object supports service com.sun.star.text.TextDocumentView and com.sun.star.view.OfficeDocumentView
+ # Both of them implements interface com::sun::star::view::XViewSettingsSupplier
+ obj = doc.getCurrentController()
+ obj.getViewSettings().setPropertyValue("ZoomType", 0)
+
+ print()
+ input("Please select something in the test document and press "
+ "then \"return\" to continues the example ... ")
+
+ frame = desktop.getCurrentFrame()
+ selection = frame.getController().getSelection()
+
+ if selection.supportsService("com.sun.star.text.TextRanges"):
+ for selected in selection:
+ print("You have selected a text range:", f'"{selected.getString()}".')
+
+ if selection.supportsService("com.sun.star.text.TextGraphicObject"):
+ print("You have selected a graphics.")
+
+ if selection.supportsService("com.sun.star.text.TexttableCursor"):
+ print("You have selected a text table.")
+
+ # When object returned from loadComponentFromURL does not support a service
+ # that implements XCloseable interface, fallback to call
+ # XComponent.dispose.
+ try:
+ doc.close(False)
+ except:
+ doc.dispose()
+ except:
+ traceback.print_exc()
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
+
+# vim: set shiftwidth=4 softtabstop=4 expandtab: