如何在libreoffice writer中使用python宏插入Italic或Bold等文本

时间:2015-03-07 08:42:27

标签: python fonts macros libreoffice uno

前提:
我在libreoffice编写器中工作,需要通过python宏向另一个我知道正在侦听TCP端口的程序发送指令。

我期待收听程序的回复,并希望将回复的数据插入到斜体中的libreoffice文档中。

1 个答案:

答案 0 :(得分:0)

此代码允许将数据作为常规打开文本插入到光标当前所在的表格或单元格开头的单元格中,以斜体显示,然后重置为普通文本以供后续输入。 对于粗体文本,请参阅com.sun.star.awt.FontWeight

def fs2_Unclear_upper(*args):
    import socket, time
    class FontSlant():
        from com.sun.star.awt.FontSlant import (NONE, ITALIC,)
#get the doc from the scripting context which is made available to all scripts
    desktop = XSCRIPTCONTEXT.getDesktop()
    model = desktop.getCurrentComponent()
    text = model.Text
    tRange = text.End
    cursor = desktop.getCurrentComponent().getCurrentController().getViewCursor()
# your cannot insert simple text and text into a table with the same method
# so we have to know if we are in a table or not.
# oTable and oCurCell will be null if we are not in a table
    oTable = cursor.TextTable
    oCurCell = cursor.Cell
    import os
    from configobj import ConfigObj
    configuration_dir = os.environ["HOME"]
    config_filename = configuration_dir + "/fs2.cfg"
    if  os.access(config_filename, os.R_OK):
        pass
    else:
        return None
    cfg = ConfigObj(config_filename)
    #define values to use from the configuration file
    tcp_port = int(cfg["control"]["TCP_PORT"])
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(0.5)
    try:
        sock.connect(("localhost", tcp_port))
    except:
        return None
    sock.settimeout(0.5)
    try:
        sock.send(bytes('get_time\n', 'UTF-8'))
    except:
        return None
    try:
        time.sleep(0.2)
        s_list = sock.recv(1024).decode('UTF-8')
        s_list = s_list.split("\n")
    except:
        return None
    lines_in_response = len(s_list)
    if lines_in_response is None:
        return None
    time_stamp = s_list[0]
    insert_text = "[Unclear " + time_stamp + "]"
    Text_Italic = FontSlant.ITALIC
    Text_None = FontSlant.NONE
    cursor.CharPosture=Text_Italic
    if oCurCell == None: # Are we inserting into a table or not?
        text.insertString(cursor, insert_text, 0)
    else:
        cell = oTable.getCellByName(oCurCell.CellName)
        cell.insertString(cursor, insert_text, False)
    cursor.CharPosture=Text_None
    sock.close()
    return None 

普通 BOLD 更改上面的代码以使用以下内容:

class FontWeight():
    from com.sun.star.awt.FontWeight import (NORMAL, BOLD,)

Text_Bold = FontWeight.BOLD
Text_Normal = FontWeight.NORMAL
cursor.CharWeight=Text_Bold

cursor.CharWeight=Text_Normal

替换处理上面倾斜和姿势的代码