open office操作word文档
前段时间工作需要使用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文档的更多相关文章
- C#操作Word文档(加密、解密、对应书签插入分页符)
原文:C#操作Word文档(加密.解密.对应书签插入分页符) 最近做一个项目,客户要求对已经生成好的RTF文件中的内容进行分页显示,由于之前对这方面没有什么了解,后来在网上也找了相关的资料,并结合自己 ...
- Java文件操作系列[3]——使用jacob操作word文档
Java对word文档的操作需要通过第三方组件实现,例如jacob.iText.POI和java2word等.jacob组件的功能最强大,可以操作word,Excel等格式的文件.该组件调用的的是操作 ...
- iText操作word文档总结
操作word文档的工具有很多,除了iText之外还有POI,但是POI擅长的功能是操作excel,虽然也可以操作word,但是能力有限,而且还有很多的bug,技术并不成熟,下面就重点介绍一种操作wor ...
- 利用Python操作Word文档【图片】
利用Python操作Word文档
- WPS Office for Mac如何修改Word文档文字排列?WPS office修改Word文档文字排列方向教程
Word文档如何改变文字的排列方向?最新版WPS Office for Mac修复了文字排版相关的细节问题,可以更快捷的进行Word编辑,WPS Office在苹果电脑中如何修改Word文档文字排列方 ...
- Java操作word文档使用JACOB和POI操作word,Excel,PPT需要的jar包
可参考文档: http://wibiline.iteye.com/blog/1725492 下载jar包 http://download.csdn.net/download/javashixiaofe ...
- VC操作WORD文档总结
一.写在开头 最近研究word文档的解析技术,我本身是VC的忠实用户,看到C#里面操作WORD这么舒服,同时也看到单位有一些需求,就想尝试一下,结果没想到里面的技术点真不少,同时网络上的共享资料很多, ...
- C# - 操作Word文档小实验
前言 本篇主要记录:VS2019 WinFrm桌面应用程序实现对Word文档的简单操作. 准备工作 搭建WinFrm前台界面 添加必要的控件,如下图 NuGet包管理器 安装Microsoft.Off ...
- QTP操作word文档
QTP可以对word文档进行操作,这里最主要展示的是向word文档写入内容,并保存的功能. Option explicit Dim wordApp Set wordApp = createobject ...
随机推荐
- 闲扯游戏编程之html5篇--山寨版《flappy bird》源码
新年新气象,最近事情不多,继续闲暇学习记点随笔,欢迎拍砖.之前的〈简单游戏学编程语言python篇〉写的比较幼稚和粗糙,且告一段落.开启新的一篇关于javascript+html5的从零开始的学习.仍 ...
- ios--个人资料修改
点击进行编辑  (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) ...
- Init
alloc负责分配对象空间,init负责初始化对象.init是实例方法,返回的是初始化后的对象的地址.init是NSObject的初始化方法. 子类不实现init,会执行由NSObject定义的ini ...
- Java中长度为0的数组与null的区别
有如下两个变量定义,这两种定义有什么区别呢? 1. int[] zero = new int[0]; 2. int[] nil = null; zero是一个长度为0的数组,我们称之为“空数组”,空数 ...
- 详解 IOS 7.1 程序启动原理
程序都是从Main方法入口的 IOS 也不例外 int main(int argc,char * argv[]) { @autoreleasepool { return UIApplicationMa ...
- linux常用vi命令
1:vi +n filename :打开文件,并将光标置于第n行首 2:在底行模式下,输入:set nu显示行号3:将光标移动到248行,命令:248G,即在命令行模式下输入248shitf+g4:复 ...
- ajax请求cookie有效性问题验证
与人讨论时遇到一个问题,就是: 浏览器中后台发起的一个异步ajax请求,服务器做响应时,附带了cookie信息,那么后续对同域名下其他页面请求时,该cookie是否有效,会一并随请求提交到web服务器 ...
- ios系统(苹果手机)按钮显示为圆角和渐变的问题
按钮在安卓手机上显示正常,但在苹果手机上会显示如下: 解决办法:给该按钮的样式加上:-webkit-appearance:none;这样按钮就会显示正常
- maven web 项目中启动报错java.lang.ClassNotFoundException: org.springframework.web.util.Log4jConfigListener
环境:Groovy/Grails Tool Suite 3.1.0.RELEASE(BASED ON ECLIPSE JUNO 3.8.1).JDK1.6.Maven3.05.Tomcat6 错误描述 ...
- 新浪ip地址转换接口
通过IP地址获取对应的地区信息通常有两种方法:1)自己写程序,解析IP对应的地区信息,需要数据库.2)根据第三方提供的API查询获取地区信息. 第一种方法,参见文本<通过纯真IP数据库获取IP地 ...