This example demonstrates how to initialize a WPS Writer instance, create a document, manipulate text, register an event, and save the file.
from pywpsrpc.rpcwpsapi import (createWpsRpcInstance, wpsapi)
from pywpsrpc import RpcIter
# 1. Create RPC instance
hr, rpc = createWpsRpcInstance()
# 2. Launch WPS Application
hr, app = rpc.getWpsApplication()
# 3. Create a new document
hr, doc = app.Documents.Add()
# 4. Manipulate text
selection = app.Selection
selection.InsertAfter("Hello, world")
selection.Font.Bold = True
selection.EndKey()
selection.InsertParagraph()
selection.MoveDown()
selection.TypeText("pywpsrpc~")
# 5. Register an event (e.g., DocumentBeforeSave)
def onDocumentBeforeSave(doc):
print("onDocumentBeforeSave called for doc: ", doc.Name)
# Return (Cancel, SaveAsUI). Returning (True, False) cancels the save.
return True, False
rpc.registerEvent(app,
wpsapi.DIID_ApplicationEvents4,
"DocumentBeforeSave",
onDocumentBeforeSave)
# 6. Save and Quit
doc.SaveAs2("test.docx")
app.Quit(wpsapi.wdDoNotSaveChanges)