原文链接Linux上使用python调用WPS二次开发接口 - C++ Programerwww.cryfeifei.cn
环境Ubuntu18.04
WPS For Linux
Python3
简介
目前WPS for Linux已经支持二次开发。这次我们使用Python3来进行调用。 目前 “社区的小伙伴”(我们团队的某个开发)把WPS的c++的接口封装成python的库了。 上github的链接
这次使用这个库来进行调用。
流程
有两种方式来调用,一个是自己手动来,一个是用pip来安装这个库,本次使用pip库
sudo dpkg -i wps-office_11.1.0.9505_amd64.deb // 安装wps
pip3 install pywpsrpc -i https://pypi.tuna.tsinghua.edu.cn/simple
把库安装好,记得打开WPS,把WPS设置成多组件的模式 上面库有个demo,可以直接新建一个 1.py
# First import the module you want
# rpcwpsapi contains the interfaces for WPS
# rpcwppapi is for WPP
# and rpcetapi for ET
# the common module contains the shared interfaces, you can not use it alone.
# you always need the createXXXRpcInstance, so first import
# take wps for example here
from pywpsrpc.rpcwpsapi import (createWpsRpcInstance, wpsapi)
# use the RpcProxy to make things easy...
from pywpsrpc import RpcProxy
# now create the rpc instance
hr, rpc = createWpsRpcInstance()
# all the calls returns the error code as the first value
# you can check it for fails
# 0 means all fines, you can use the common module's S_OK,
# FAILED or SUCCEEDED to check
# recommend use the RpcProxy instead
# get the application and you get everything...
# here we use the RpcProxy to wrap the application
# otherwise, you have to call Release on each instance
# and handle the hr for every call...
app = RpcProxy(rpc.getWpsApplication())
# Add blank doc e.g.
doc = app.Documents.Add()
# append text...
selection = app.Selection
selection.InsertAfter("Hello, world")
# bold the "Hello, world"
selection.Font.Bold = True
# get a notify about saving
#rpc.registerEvent(app.rpc_object,
# wpsapi.DIID_ApplicationEvents4,
# "DocumentBeforeSave",
# onDocumentBeforeSave)
#def onDocumentBeforeSave(doc, saveAsUi, cancel):
# to discard the saving, return cancel as True
# return saveAsUi, cancel
# save the doc, onDocumentBeforeSave will be called
doc.SaveAs2("test.docx")
# Quit the application if you don't need anymore
# use wpsapi.wdDoNotSaveChanges to ignore the changes
app.Quit(wpsapi.wdDoNotSaveChanges)
运行这个py
python3 ./1.py
然后会发现当前文件夹生成一个新的文档 test.docx.
更多的api可以上github去查看,当然什么保存成pdf就更没有问题了。
这个demo相当简单。代码更好懂了。你会发现API跟msdn的方法基本一致。这也是WPS的兼容mso的地方,不过目前应该只有WPS在Linux上有这种级别的API开放给大家。