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 abspath
, basename
15 from com
.sun
.star
.beans
import PropertyValue
16 from com
.sun
.star
.connection
import NoConnectException
18 PROG
= "$OFFICE_PROGRAM_PATH/python {}".format(basename(sys
.argv
[0]))
19 SOFFICE_CONNECTION_URI
= "uno:socket,host=localhost,port=2083;urp;StarOffice.ComponentContext"
22 def connect_soffice():
23 """Connect to remote running LibreOffice
25 :return: an object representing the remote LibreOffice instance.
27 local_context
= uno
.getComponentContext()
28 resolver
= local_context
.ServiceManager
.createInstanceWithContext(
29 "com.sun.star.bridge.UnoUrlResolver", local_context
32 remote_context
= resolver
.resolve(SOFFICE_CONNECTION_URI
)
33 except NoConnectException
:
34 raise Exception("Cannot establish a connection to LibreOffice.")
36 return remote_context
.ServiceManager
.createInstanceWithContext(
37 "com.sun.star.frame.Desktop", remote_context
41 def print_(doc_path
, printer
, pages
):
42 soffice
= connect_soffice()
43 doc_url
= "file://{}".format(abspath(doc_path
)).replace("\\", "/")
44 # Load a Writer document, which will be automatically displayed
45 doc
= soffice
.loadComponentFromURL(doc_url
, "_blank", 0, tuple([]))
47 doc
.setPrinter((PropertyValue(Name
="Name", Value
=printer
),))
49 PropertyValue(Name
="Pages", Value
=pages
),
57 parser
= argparse
.ArgumentParser(description
="Document Printer", prog
=PROG
)
58 parser
.add_argument("printer", help="Printer name")
59 parser
.add_argument("doc_path", help="Path to a document to be printed")
60 parser
.add_argument("pages", help="Page range to be printed, e.g. 1-3")
62 args
= parser
.parse_args()
63 print_(args
.doc_path
, args
.printer
, args
.pages
)
66 if __name__
== "__main__":
70 # vim: set shiftwidth=4 softtabstop=4 expandtab: