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 ...
随机推荐
- 通过CSS实现小动物
此例演示的是通过CSS实现动物头像,效果如下: 好了,上代码: html代码: <html> <head> <meta charset="utf-8" ...
- JQuery的一些简单操作02
一.遍历 1.向下遍历,children.find children只能向下遍历儿子节点的所有元素,find遍历当前元素下面的所有子节点 2.向上遍历,parent,parents,parentsUn ...
- js版扫雷(可直接运行试玩)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 在Visual Studio中使用Git命令提示符
VS2015自带了Git插件,但有时候我觉得Git控制台命令更方便些. VS中本身不能把Git Bush作为浮动窗集成进来,但我们可以通过Power Shell来使用Git命令. ---------- ...
- 使用Navicat修改SQLite数据库提示:no such collation sequence: LOCALIZED
今天在修改Android应用里用到的一个SQLite数据库文件,使用Navicat修改SQLite数据库提示:“no such collation sequence: LOCALIZED”错误,折腾了 ...
- 如何开发、调试Hybrid项目-- 入门篇
前言 随着移动浪潮的兴起,各种APP层出不穷,极速的业务扩展提升了团队对开发效率的要求,这个时候使用IOS&Andriod开发一个APP似乎成本有点过高了,而H5的低成本.高效率.跨平台等特性 ...
- HTML5+CSS3学习小记
1.用网络图片作为背景图片: body{ background-image: url(http://b.hiphotos.baidu.com/album/h%3D900%3Bcrop%3D0%2C0% ...
- MTP in Android详解
MTP in Android详解 最近好长一段时间没有做笔记了,今天主要学习一下MTP相关的知识. MTP的全称是Media Transfer Protocol(媒体传输协议),它是微软公司提出的一套 ...
- mvc3 上传图片
这是在Control里使用的代码,是在后台管理需要上传图片时使用的,不过我在这犯了一个错误, Request.Files[inputName];inputName名字中的大小写<input ty ...
- throw与throws的区别
throws语句 throws总是出现在一个函数头中,用来标明该成员函数可能抛出的各种异常.对大多数Exception子类来说,Java 编译器会强迫你声明在一个成员函数中抛出的异常的 ...