cid#1640468 Dereference after null check
[LibreOffice.git] / odk / examples / python / Text / TextDocumentStructure.py
blobe082bd8345ed786ec2ee8e74b18ec00d6ff36607
1 # -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
3 # This file is part of the LibreOffice project.
5 # This Source Code Form is subject to the terms of the Mozilla Public
6 # License, v. 2.0. If a copy of the MPL was not distributed with this
7 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
10 import officehelper
11 import sys
12 import traceback
14 from com.sun.star.awt.FontWeight import BOLD
15 from com.sun.star.beans.PropertyState import AMBIGUOUS_VALUE
16 from com.sun.star.beans.PropertyState import DEFAULT_VALUE
17 from com.sun.star.beans.PropertyState import DIRECT_VALUE
20 def main():
21 try:
22 remote_context = officehelper.bootstrap()
23 srv_mgr = remote_context.getServiceManager()
24 desktop = srv_mgr.createInstanceWithContext("com.sun.star.frame.Desktop", remote_context)
26 doc_url = "private:factory/swriter"
27 doc = desktop.loadComponentFromURL(doc_url, "_blank", 0, tuple())
28 text = doc.getText()
29 create_example_data(text)
30 display_structure(text)
31 except Exception:
32 traceback.print_exc()
33 sys.exit(1)
35 print("done")
38 def create_example_data(text):
39 try:
40 text.setString("This is an example sentence")
41 cursor = text.getStart()
42 cursor.gotoNextWord(False)
43 cursor.gotoNextWord(False)
44 cursor.gotoEndOfWord(True)
45 cursor.setPropertyValue("CharWeight", BOLD)
46 print("create example data")
47 except Exception:
48 traceback.print_exc()
51 def display_structure(text):
52 print("Document structure:")
53 # Create an enumeration of all paragraphs
54 paragraph_enum = text.createEnumeration()
55 # Loop through all paragraphs of the document
56 for element in paragraph_enum:
57 if not element.supportsService("com.sun.star.text.Paragraph"):
58 print("The text portion isn't a text paragraph")
59 continue
61 print("This is a Paragraph")
62 for portion in element.createEnumeration():
63 print("Text from the portion:", f"{portion.getString()}")
64 print("Name of the font:", portion.getPropertyValue("CharFontName"))
65 char_weight = portion.getPropertyState("CharWeight")
66 if char_weight == AMBIGUOUS_VALUE:
67 print(" - The text range contains more than one different attributes")
68 elif char_weight == DIRECT_VALUE:
69 print(" - The text range contains hard formats")
70 elif char_weight == DEFAULT_VALUE:
71 print(" - The text range doesn't contains hard formats")
72 else:
73 pass # Do nothing
76 if __name__ == "__main__":
77 main()
79 # vim: set shiftwidth=4 softtabstop=4 expandtab: