feat: add save doc func

This commit is contained in:
zzs 2025-03-25 16:43:02 +08:00
parent 9d4df1df84
commit 8e896cf683

View File

@ -56,7 +56,7 @@ def DebugCallReplace():
调试调用
"""
Replace({"h1": "P1", "h2": "P2", "h3": "P3"})
Replace({"bb1": "P1", "bb2": "P2", "bb3": "P3", "bb4": "P4"})
def DebugCallReplaceList():
@ -521,9 +521,63 @@ def ReplaceTextAndInsertTableRow(json_str):
Replace(data["text"])
BatchInsertRow(data["table"])
model = XSCRIPTCONTEXT.getDocument()
controller = model.getCurrentController()
controller.refresh()
def returnWithJSON(data):
return json.dumps(data, ensure_ascii=False)
def SaveDocument():
# 获取当前文档对象
model = XSCRIPTCONTEXT.getDocument()
try:
# 检查文档是否支持保存XStorable 接口)
from com.sun.star.frame import XStorable
xstorable = model.uno_getAdapter(XStorable)
# 调用保存方法(覆盖原文件)
xstorable.store()
return True
except Exception as e:
print("保存失败:", e)
return False
def replace_bookmarks_with_controls():
doc = XSCRIPTCONTEXT.getDocument()
bookmarks = doc.getBookmarks()
controller = doc.getCurrentController()
for name in reversed([bm.getName() for bm in bookmarks]):
try:
bookmark = bookmarks.getByName(name)
anchor = bookmark.getAnchor()
# 获取书签内容
cursor = anchor.getText().createTextCursorByRange(anchor)
original_text = cursor.getString()
# 创建文本控件并设置内容
text_control = doc.createInstance("com.sun.star.text.TextField.Input")
text_control.setPropertyValue("Content", original_text)
# text_control.setPropertyValue("BookmarkName", name) # 正确属性名
# 替换原书签内容为控件
cursor.setString("")
anchor.getText().insertTextContent(cursor, text_control, False)
# 重新插入原书签到控件后
new_cursor = cursor.getText().createTextCursorByRange(cursor)
new_cursor.goRight(1, False)
doc.getBookmarks().addNew(name, new_cursor)
except Exception as e:
print(f"错误:{str(e)}")
g_exportedScripts = (
Replace,
ReplaceWithJSON,
@ -542,5 +596,7 @@ g_exportedScripts = (
DebugCallLocateBookmarkLo2,
DebugCallInsertBookmark,
DebugCallUpdateBookmark,
DebugCallDeleteBookmark
DebugCallDeleteBookmark,
replace_bookmarks_with_controls,
SaveDocument
)