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/.
12 from os
.path
import basename
, abspath
15 from com
.sun
.star
.beans
import PropertyValue
16 from com
.sun
.star
.connection
import NoConnectException
19 The purpose of this example is to open a specified text document and save this
20 file to a specified URL. The type of the saved file is "writer8".
23 PROG
= "$OFFICE_PROGRAM_PATH/python {}".format(basename(sys
.argv
[0]))
24 SOFFICE_CONNECTION_URI
= "uno:socket,host=localhost,port=2083;urp;StarOffice.ComponentContext"
27 def connect_soffice():
28 """Connect to remote running LibreOffice
30 :return: an object representing the remote LibreOffice instance.
32 local_context
= uno
.getComponentContext()
33 resolver
= local_context
.ServiceManager
.createInstanceWithContext(
34 "com.sun.star.bridge.UnoUrlResolver", local_context
37 remote_context
= resolver
.resolve(SOFFICE_CONNECTION_URI
)
38 except NoConnectException
:
39 raise Exception("Cannot establish a connection to LibreOffice.")
41 return remote_context
.ServiceManager
.createInstanceWithContext(
42 "com.sun.star.frame.Desktop", remote_context
46 def save_doc(src
, dest
):
47 src_url
= "file://{}".format(abspath(src
)).replace("\\", "/")
48 dest_url
= "file://{}".format(abspath(dest
)).replace("\\", "/")
50 soffice
= connect_soffice()
51 doc
= soffice
.loadComponentFromURL(
52 src_url
, "_blank", 0, (PropertyValue(Name
="Hidden", Value
=True),)
56 PropertyValue(Name
="Overwrite", Value
=True),
57 PropertyValue(Name
="FilterName", Value
="writer8"),
60 doc
.storeAsURL(dest_url
, save_opts
)
61 print("Document", src
, "saved under", dest
)
64 print("Document closed!")
68 parser
= argparse
.ArgumentParser(description
="Document Saver", prog
=PROG
)
69 parser
.add_argument("src", help="Path to a Word document to be saved, e.g. path/to/hello.doc")
70 parser
.add_argument("dest", help="Save the document to here, e.g. path/to/hello.odt")
72 args
= parser
.parse_args()
73 save_doc(args
.src
, args
.dest
)
76 if __name__
== "__main__":
80 # vim: set shiftwidth=4 softtabstop=4 expandtab: