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 ...
随机推荐
- CreateFile函数详解
CreateFile函数详解 CreateFile The CreateFile function creates or opens the following objects and returns ...
- easyui propertygrid 动态绑定
从$.fn.datagrid.defaults继承,覆盖默认值 $.fn.propertygrid.defaults propertygrid 提供用户一个接口,浏览和编辑对象属性,propertyg ...
- SQL Server简单语句/待整理
数据库对象:表Table,视图View,存储过程Stored Procedure,触发器Trigger 关系:1关系=1二维表,1关系有1关系名.1关系=1表对象 属性/字段: 二维表中垂直方向的列 ...
- C++ dynamic_cast对指针类型的转换
C8-3 三角形还是长方形? (100.0/100 points) 题目描述 在多态概念中,基类的指针既可以指向基类的对象,又可以指向派生类的对象.我们可以使用dynamic_cast类型转换操作符来 ...
- Direct3D 10学习笔记(四)——Windows编程
本篇将简单整理基本的Windows应用程序的实现,并作为创建Direct3D 10应用程序的铺垫.具体内容参照< Introduction to 3D Game Programming with ...
- 传入的表格格式数据流(TDS)远程过程调用(RPC)协议流不正确。此 RPC 请求中提供了过多的参数。最多应为 2100
出现这个问题的背景是,判断一批激活码在系统中是否已经存在,很傻的一个作法是,把这一批激活码,以in(in (‘ddd‘,‘aaa‘))的形式来处理,导致问题的出现. 后来,查找资料,http://bb ...
- <转>你相信外星人的存在吗
来自为知笔记(Wiz)
- check_env函数解析
又是一个比较长的函数,是用来检查文件权限,目录条件的.具体代码如下: check_env() { # Check user privilege. #检查用户权限 check_user root # C ...
- 火车头wordpress免费万能发布模块和接口
火车头wordpress免费万能发布模块和接口实测可以用 http://www.ggfenxiang8.com/?p=263
- Linux chroot 并使用之前系统设备节点
/********************************************************************************* * Linux chroot 并使 ...