Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Keep the code below in the LO user directory. To find this location, go to Tools -> Options -> LibreOffice -> Paths and look at AutoCorrect for example. The user directory is kept when updating versions.

For how to run python macros, see https://wiki.openoffice.org/wiki/Python_as_a_macro_language. Primarily, this involves putting the code in a new directoryuser/Scripts/python (case must match).

To set up a toolbar button to run the macro, go to Tools -> Customize.

import datetime
import uno
from com.sun.star.beans import PropertyValue

def export_pdf_with_timestamp():
    oDoc = XSCRIPTCONTEXT.getDocument()
    sURL = oDoc.getURL()
    ext_len = len(".odt")
    timestamp = "{:%Y-%m-%d_%H-%M-%S}".format(datetime.datetime.now())
    outfilename = "%s_%s.pdf" % (sURL[:-ext_len], timestamp)
    ctx = XSCRIPTCONTEXT.getComponentContext()
    smgr = ctx.ServiceManager
    frame = oDoc.getCurrentController().getFrame()
    dispatcher = smgr.createInstanceWithContext(
        "com.sun.star.frame.DispatchHelper", ctx)
    props = tuple(PropertyValue() for dummy in range(2))
    props[0].Name = "URL"
    props[0].Value = outfilename
    props[1].Name = "FilterName"
    props[1].Value = "writer_pdf_Export"
    dispatcher.executeDispatch(frame, ".uno:ExportToPDF", "", 0, props)

g_exportedScripts = export_pdf_with_timestamp,