前段时间工作需要使用open office往word中写文件,写图片,以及向footer也就是页尾中插入图片,已经封装成了类,直接调用即可,代码如下:

package com.test.common.util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import ooo.connector.BootstrapSocketConnector; import com.mysql.jdbc.StringUtils;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import com.sun.star.container.XNameAccess;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.lang.XMultiServiceFactory;
import com.sun.star.style.XStyle;
import com.sun.star.style.XStyleFamiliesSupplier;
import com.sun.star.text.HoriOrientation;
import com.sun.star.text.TextContentAnchorType;
import com.sun.star.text.WrapTextMode;
import com.sun.star.text.XSentenceCursor;
import com.sun.star.text.XText;
import com.sun.star.text.XTextContent;
import com.sun.star.text.XTextCursor;
import com.sun.star.text.XTextDocument;
import com.sun.star.uno.AnyConverter;
import com.sun.star.uno.Type;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext; /**
* 主要用openOffice 的API向加密的word文件中写入文字和在图片;
*
*
*/
public class OpenOfficeAPI {
private XComponentContext mxRemoteContext;
private XMultiComponentFactory mxRemoteServiceManager;
private XTextCursor mxDocCursor;
private XText mxDocText;
private XTextDocument mxDoc;
private XSentenceCursor xSentenceCursor;
private Object desktop;
private XComponent xEmptyWriterComponent;
/**
* open office的安装路径;
*/
private String OPENOFFICE_PATH ="C:/Program Files/OpenOffice 4/program/"; private static Log logger = LogFactory.getLog(OpenOfficeAPI.class); public OpenOfficeAPI(String openOfficePath)
{
this.OPENOFFICE_PATH=openOfficePath;
} /**
* get the remote service manager
*
* @return
* @throws java.lang.Exception
*/
private XMultiComponentFactory getRemoteServiceManager()
throws java.lang.Exception {
if (mxRemoteContext == null && mxRemoteServiceManager == null) {
// get the remote office context
mxRemoteContext = BootstrapSocketConnector
.bootstrap(OPENOFFICE_PATH);
if (logger.isInfoEnabled()) {
logger.info("Connected to a running office ...");
}
mxRemoteServiceManager = mxRemoteContext.getServiceManager();
String available = (mxRemoteServiceManager != null ? "available"
: "not available");
if (logger.isInfoEnabled()) {
logger.info("remote ServiceManager is " + available);
}
}
return mxRemoteServiceManager;
} /**
* 判断文件是否存在,并将文件路径格式化为:file:///D:/doc/myword.doc的形式;
*
* @param fileUrl
* @return
* @throws Exception
*/
private String formatFileUrl(String fileUrl) throws Exception {
try {
StringBuffer sUrl = new StringBuffer("file:///");
File sourceFile = new File(fileUrl);
sUrl.append(sourceFile.getCanonicalPath().replace('\\', '/'));
return sUrl.toString();
} catch (Exception e) {
if (logger.isInfoEnabled()) {
logger.info("formatFileUrl=" + e.toString() + "fileUrl="
+ fileUrl);
}
}
return "";
} /**
* get the interfaces to control the UNO
*
* @param docType
* @return
* @throws java.lang.Exception
*/
private XComponent newDocComponent(String fileUrl, String password)
throws java.lang.Exception {
mxRemoteServiceManager = this.getRemoteServiceManager();
// get the Desktop service
desktop = mxRemoteServiceManager.createInstanceWithContext(
"com.sun.star.frame.Desktop", mxRemoteContext);
// retrieve the current component and access the controller
XComponentLoader xComponentLoader = (XComponentLoader) UnoRuntime
.queryInterface(XComponentLoader.class, desktop);
// set the OpenOffice not open
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("Hidden", Boolean.TRUE);
if( !StringUtils.isNullOrEmpty(password)){
map.put("Password", password);
}
PropertyValue[] propertyValue = MakePropertyValue(map);
fileUrl = formatFileUrl(fileUrl);
return xComponentLoader.loadComponentFromURL(fileUrl, "_blank", 0,
propertyValue);
} /**
* 保存文件
*
* @param xDoc
* @param storeUrl
* @throws java.lang.Exception
*/
private void storeDocComponent(XComponent xDoc, String storeUrl,
String password) throws java.lang.Exception {
XStorable xStorable = (XStorable) UnoRuntime.queryInterface(
XStorable.class, xDoc);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("FilterName", "MS Word 97");
if(!StringUtils.isNullOrEmpty(password)){
map.put("Password", password);
}
PropertyValue[] storeProps = MakePropertyValue(map);
storeUrl = formatFileUrl(storeUrl);
xStorable.storeAsURL(storeUrl, storeProps);
} /**
* 关闭组件;
*
* @throws Exception
*/
private void close() throws Exception {
com.sun.star.util.XCloseable xCloseable = (com.sun.star.util.XCloseable) UnoRuntime
.queryInterface(com.sun.star.util.XCloseable.class, mxDoc);
if (xCloseable != null) {
xCloseable.close(false);
} else {
com.sun.star.lang.XComponent xComponent = (com.sun.star.lang.XComponent) UnoRuntime
.queryInterface(com.sun.star.lang.XComponent.class, mxDoc);
if (null != xComponent)
xComponent.dispose();
}
} /**
* 设置属性值;
*
* @param cName
* @param uValue
* @return
*/
private final PropertyValue[] MakePropertyValue(HashMap<String, Object> map) {
int total = 0;
if (null != map && map.size() > 0) {
total = map.size();
}
PropertyValue[] tempMakePropertyValue = new PropertyValue[total];
Iterator iter = map.entrySet().iterator();
int i = 0;
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String key = entry.getKey().toString();
Object val = entry.getValue();
tempMakePropertyValue[i] = new PropertyValue();
tempMakePropertyValue[i].Name = key;
tempMakePropertyValue[i].Value = val;
i = i + 1;
}
return tempMakePropertyValue;
} /**
* 插入字符串到word文件中;
* @param fileUrl:word文件物理路径
     * @param content:文件中插入的内容
   * @param password:打开word文件的密码
* @throws java.lang.Exception
*/
public void insertStrToWord(String fileUrl, String content, String password)
throws Exception {
try {
xEmptyWriterComponent = newDocComponent(fileUrl, password);
mxDoc = (XTextDocument) UnoRuntime.queryInterface(
XTextDocument.class, xEmptyWriterComponent);
mxDocText = mxDoc.getText();
mxDocCursor = mxDocText.createTextCursor();
xSentenceCursor = (XSentenceCursor) UnoRuntime.queryInterface(
XSentenceCursor.class, mxDocCursor);
mxDocText.insertString(xSentenceCursor, content, true);
// 保存;
storeDocComponent(xEmptyWriterComponent, fileUrl, password);
} catch (Exception e) {
if (logger.isInfoEnabled()) {
logger.info("插入字符串到word文件中" + e);
}
} finally {
close();
} } /**
* 插入图片到word文件中;
* @param fileUrl:word文件物理路径
     * @param imgUrl:文件中要插入的图片的物理路径
   * @param password:打开word文件的密码
    * @param width:插入的图片在word文件中的宽度
   * @param height:插入的图片在word文件中的高度
     * @throws java.lang.Exception
*/
public void insertImgToWord(String fileUrl, String imgUrl, Integer width,
Integer height, String password) throws Exception { try {
xEmptyWriterComponent = newDocComponent(fileUrl, password);
mxDoc = (XTextDocument) UnoRuntime.queryInterface(
XTextDocument.class, xEmptyWriterComponent);
mxDocText = mxDoc.getText();
mxDocCursor = mxDocText.createTextCursor();
xSentenceCursor = (XSentenceCursor) UnoRuntime.queryInterface(
XSentenceCursor.class, mxDocCursor);
// 图片textcontent
XMultiServiceFactory xMSFDoc = (XMultiServiceFactory) UnoRuntime
.queryInterface(XMultiServiceFactory.class,
xEmptyWriterComponent);
Object oGraphic = xMSFDoc
.createInstance("com.sun.star.text.TextGraphicObject");
XTextContent xTextContent = (XTextContent) UnoRuntime
.queryInterface(XTextContent.class, oGraphic);
// 图片属性设置;
XPropertySet xPropSet = (XPropertySet) UnoRuntime.queryInterface(
XPropertySet.class, oGraphic);
xPropSet.setPropertyValue("AnchorType",
TextContentAnchorType.AT_PARAGRAPH_value);
imgUrl = formatFileUrl(imgUrl);
xPropSet.setPropertyValue("GraphicURL", imgUrl);
xPropSet.setPropertyValue("Width", new Integer(width * 10));
xPropSet.setPropertyValue("Height", new Integer(height * 10));
// 插入图片;
mxDocText.insertTextContent(xSentenceCursor, xTextContent, true);
// 保存;
storeDocComponent(xEmptyWriterComponent, fileUrl, password);
} catch (Exception e) {
if (logger.isInfoEnabled()) {
logger.info("插入图片到word文件中" + e);
}
} finally {
close();
} } /**
* 插入图片到word页尾中;
* @param fileUrl:word文件绝对路径
* @param password:word文件密码,如果无密码则空;如果有密码,则新生成的newFileUrl,也用该密码加密
* @param imgUrl:插入图片文件绝对路径
* @param width:图片在word中展示的宽度
* @param height:图片在word中展示的高度
* @param newFileUrl:新生成文件的绝对路径
* @throws java.lang.Exception
* @return 返回1:生成成功;返回0:生成异常;
*/
public int insertImgToFooter(String fileUrl,String password,String imgUrl, Integer width,
Integer height, String newFileUrl) throws Exception {
int rev=1;
try {
xEmptyWriterComponent = newDocComponent(fileUrl, password);
mxDoc = (XTextDocument) UnoRuntime.queryInterface(
XTextDocument.class, xEmptyWriterComponent);
XStyleFamiliesSupplier StyleFam = (XStyleFamiliesSupplier) UnoRuntime
.queryInterface(XStyleFamiliesSupplier.class, mxDoc);
XNameAccess StyleFamNames = StyleFam.getStyleFamilies();
XNameAccess PageStyles = (XNameAccess) AnyConverter.toObject(
new Type(XNameAccess.class),
StyleFamNames.getByName("PageStyles"));
XStyle StdStyle = (XStyle) AnyConverter.toObject(new Type(
XStyle.class), PageStyles.getByName("Standard"));
XPropertySet PropSet = (XPropertySet) UnoRuntime.queryInterface(
XPropertySet.class, StdStyle);
PropSet.setPropertyValue("FooterIsOn", new Boolean(true));
// Pegando o HeaderXText
XText footerText = (com.sun.star.text.XText) UnoRuntime
.queryInterface(com.sun.star.text.XText.class,
PropSet.getPropertyValue("FooterTextLeft")); XMultiServiceFactory xMSFDoc = (XMultiServiceFactory) UnoRuntime
.queryInterface(XMultiServiceFactory.class, mxDoc);
Object oGraphic = xMSFDoc
.createInstance("com.sun.star.text.TextGraphicObject");
// Getting the cursor on the document
XTextCursor xTextCursor = footerText.createTextCursor();
XTextContent xTextContent = (XTextContent) UnoRuntime
.queryInterface(XTextContent.class, oGraphic); xTextCursor.gotoStart(false);
// isReplace
footerText.insertTextContent(xTextCursor, xTextContent, false);
XPropertySet xPropSet = (com.sun.star.beans.XPropertySet) UnoRuntime
.queryInterface(XPropertySet.class, oGraphic);
// Setting the anchor type
xPropSet.setPropertyValue("AnchorType",
TextContentAnchorType.AT_PARAGRAPH);
imgUrl = formatFileUrl(imgUrl);
// Setting the graphic url
xPropSet.setPropertyValue("GraphicURL", imgUrl);
// Setting the horizontal position
xPropSet.setPropertyValue("TextWrap", WrapTextMode.DYNAMIC);
xPropSet.setPropertyValue("HoriOrient", HoriOrientation.LEFT);
// Setting the width
xPropSet.setPropertyValue("Width", width * 10);
// Setting the height
xPropSet.setPropertyValue("Height", height * 10); // 保存;
storeDocComponent(xEmptyWriterComponent, newFileUrl, password);
} catch (Exception e) {
if (logger.isInfoEnabled()) {
logger.info("插入图片到word页尾中" + e);
}
rev=0;
} finally {
close();
}
return rev; } }

open office操作word文档的更多相关文章

  1. C#操作Word文档(加密、解密、对应书签插入分页符)

    原文:C#操作Word文档(加密.解密.对应书签插入分页符) 最近做一个项目,客户要求对已经生成好的RTF文件中的内容进行分页显示,由于之前对这方面没有什么了解,后来在网上也找了相关的资料,并结合自己 ...

  2. Java文件操作系列[3]——使用jacob操作word文档

    Java对word文档的操作需要通过第三方组件实现,例如jacob.iText.POI和java2word等.jacob组件的功能最强大,可以操作word,Excel等格式的文件.该组件调用的的是操作 ...

  3. iText操作word文档总结

    操作word文档的工具有很多,除了iText之外还有POI,但是POI擅长的功能是操作excel,虽然也可以操作word,但是能力有限,而且还有很多的bug,技术并不成熟,下面就重点介绍一种操作wor ...

  4. 利用Python操作Word文档【图片】

    利用Python操作Word文档

  5. WPS Office for Mac如何修改Word文档文字排列?WPS office修改Word文档文字排列方向教程

    Word文档如何改变文字的排列方向?最新版WPS Office for Mac修复了文字排版相关的细节问题,可以更快捷的进行Word编辑,WPS Office在苹果电脑中如何修改Word文档文字排列方 ...

  6. Java操作word文档使用JACOB和POI操作word,Excel,PPT需要的jar包

    可参考文档: http://wibiline.iteye.com/blog/1725492 下载jar包 http://download.csdn.net/download/javashixiaofe ...

  7. VC操作WORD文档总结

    一.写在开头 最近研究word文档的解析技术,我本身是VC的忠实用户,看到C#里面操作WORD这么舒服,同时也看到单位有一些需求,就想尝试一下,结果没想到里面的技术点真不少,同时网络上的共享资料很多, ...

  8. C# - 操作Word文档小实验

    前言 本篇主要记录:VS2019 WinFrm桌面应用程序实现对Word文档的简单操作. 准备工作 搭建WinFrm前台界面 添加必要的控件,如下图 NuGet包管理器 安装Microsoft.Off ...

  9. QTP操作word文档

    QTP可以对word文档进行操作,这里最主要展示的是向word文档写入内容,并保存的功能. Option explicit Dim wordApp Set wordApp = createobject ...

随机推荐

  1. mysqlnd cannot connect 连接错误处理方法

    mysqlnd cannot connect to MySQL 4.1+ using the old insecure authentication. Please use an administra ...

  2. Bat文件, Services

    创建Bat文件自启动Windows Service; Services: sc stop/delete/query/find "service name"; Service Fol ...

  3. Python、Ruby中的SWIG使用案例

    案例一:Python通过SWIG使用C码 linux系统 照着文档[1]做就是了~! 案例二:Python程序调用张华平博士最新发布的中文分词库“NLPIR – ICTCLAS2013”为例~! wi ...

  4. 调试python程序

    pdb 关键步骤 python -m pdb ***.py n 单步

  5. SELF, self in CORE DATA

    Predicate SELF Represents the object being evaluated. CORE DATA Retrieving Specific Objects If your ...

  6. 开篇----JavaScript细节的那些事儿

    JavaScript现在已经是全世界浏览器通用的语言,目前也完全可以在服务器端做开发,如Node.js,市面上好的JavaScript的书有很多,有的还是经典之作,值得收藏. 趁此东风,打算接下来写一 ...

  7. IONIC 开发的Android应用程序签名(或重新签名)详解

    完全通过DOS命令来完成apk签名 给apk签名一共要用到3个工具,或者说3个命令,分别是:keytool.jarsigner和zipalign,下面是对这3个工具的简单介绍:            ...

  8. Windows Server 2012 没有远程桌面授权服务器可以提供许可证,远程会话被中断

    今天在登录公司内部的服务器的时候,无法进行远程访问. 弹出错误信息:没有远程桌面授权服务器可以提供许可证,远程会话被中断 经过网上的寻找,原来是server 2012 远程登录只提供120天的使用期限 ...

  9. 2016年中国大学生程序设计竞赛(合肥)-重现赛1001 HDU 5961

    传递 Time Limit: 12000/6000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total Submiss ...

  10. SQL Server COM 组件创建实例失败

    SQL Server COM 组件创建实例失败   SQL2008数据库总会出现从 IClassFactory 为 CLSID 为 {17BCA6E8-A95D-497E-B2F9-AF6AA4759 ...