如何在 libreoffice writer 中使用 python 宏将文本插入斜体或粗体等
Posted
技术标签:
【中文标题】如何在 libreoffice writer 中使用 python 宏将文本插入斜体或粗体等【英文标题】:How do I insert text as Italic or Bold etc with a python macro in libreoffice writer 【发布时间】:2015-03-07 08:42:26 【问题描述】:前提: 我在 libreoffice writer 工作,需要通过 python 宏向我知道正在侦听 TCP 端口的另一个程序发送指令。
我期待监听程序的回复,并希望将回复的数据插入到 libreoffice 文档中斜体。
【问题讨论】:
那么到目前为止你编码了什么? 我编写了答案!刚刚注册,我最初发布了问题的答案,但被告知我必须将它们分开,这就是我所做的。 我明白了。在我进行审查的那一刻看不到这一点。不要忘记尽快检查自己的答案。 【参考方案1】:此代码允许将数据作为普通打开的文本插入或插入到当前光标所在的表格中的单元格或单元格的开头,斜体,然后重置为普通文本以供后续输入。 粗体字请参考 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
替换上面处理倾斜和姿势的代码
【讨论】:
以上是关于如何在 libreoffice writer 中使用 python 宏将文本插入斜体或粗体等的主要内容,如果未能解决你的问题,请参考以下文章
如何将 python 源代码添加到 libreoffice writer?
如何在 libreoffice writer 中编写 python 宏来发送接收数据
如何在 Libreoffice writer 的标题下添加边框
如何在 libreoffice writer 中使用 python 宏将文本插入斜体或粗体等