我正在编写一个在C#中使用LibreOffice CLI
的程序。
我想加载LibreOffice
Writer一些预定义的已保存文件,然后关闭LibreOffice Writer。
我可以用空白加载Writer,但是没有得到如何打开某个特定文件,并且在做了一些工作后使用程序关闭了编写器。
任何帮助都将受到高度赞赏。
这是代码
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.uno;
using unoidl.com.sun.star.bridge;
using unoidl.com.sun.star.frame;
using uno.util;
using unoidl.com.sun.star.text;
using unoidl.com.sun.star.util;
public static void Main()
{
XComponentContext context = null;
context = Bootstrap.bootstrap();
if (context != null)
Console.WriteLine("Connected");
XTextDocument newDoc = openWriter(context);
}
private static XTextDocument openWriter(XComponentContext xContext)
{
//define variables
unoidl.com.sun.star.frame.XComponentLoader xCLoader;
unoidl.com.sun.star.text.XTextDocument xDoc = null;
unoidl.com.sun.star.lang.XComponent xComp = null;
try
{
// get the remote office service manager
unoidl.com.sun.star.lang.XMultiComponentFactory xMCF =
xContext.getServiceManager();
Object oDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
xCLoader = ((XComponentLoader)oDesktop);
//UnoRuntime.queryInterface(com.sun.star.frame.XComponentLoader.class,oDesktop);
unoidl.com.sun.star.beans.PropertyValue[] szEmptyArgs = new unoidl.com.sun.star.beans.PropertyValue[0];
string strDoc = @"private:factory/swriter";
xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, szEmptyArgs);
xDoc = ((XTextDocument)xComp);
}
catch (System.Exception e)
{
}
return xDoc;
}
答案 0 :(得分:0)
在查看OpenOffice文档(https://www.openoffice.org/api/docs/common/ref/com/sun/star/frame/XComponentLoader.html)时,似乎原因在于如何设置strDoc的值。 如果要打开现有文件,则必须相应设置strDoc的值。 老实说,我不知道UNC规范是否正确,但我将进行检查。
答案 1 :(得分:0)
对于 Open
,只需使用:
string strDoc = @"file:///c:/Users/admin/file.doc"; // This is the file URI
xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, szEmptyArgs);
xDoc = ((XTextDocument)xComp);
对于 Close
使用如下所示的内容:
XCloseable xCloseable;
XModifiable xModifiable;
try
{
xModifiable = (XModifiable)xComponent;
xModifiable.setModified(false);
xCloseable = (XCloseable)xComponent;
xCloseable.close(true);
// This closes all instances, even ones you didn't create
// If you don't write this, you'll find 'soffice.bin' still lingering in taskmgr
XDesktop xDesktop = (XDesktop)xCLoader;
if(xDesktop != null)
xDesktop.terminate();
}
catch(InvalidCastException)
{
// Add handler
}
catch(CloseVetoException)
{
// Add handler
}