小结下最近做的东西吧。因为是做一个素材管理的东西,因此需要处理各种各样的素材,音频、视频、图片、pdf、ppt等等。遇到一个需求就是将PPT转成 图片组,google一下,在java里是可以jcom之类的开源库实现,本质上都是通过jni调用office的COM接口来实现。我们就需要这么一个 小功能,拖这么大个开源库进来实在没有必要。最后决定自己写个动态链接库,通过jni来调用。
先写工具类,
public class PPTUtils {
public PPTUtils() {
}
public static native void convertPPT2IMG(String pptFileName, String tmpDir);
public static void loadLibrary() {//加载动态库
String dllFileName = "pptDll";
try {
String OsName = System.getProperty("os.name");
if (OsName.contains("Windows")) {
dllFileName += ".dll";
} else {
dllFileName += ".so";
}
//加载动态链接库
System.load(dllFileName);
}
catch (Exception e) {
// LOG.error("can not load " + dllFileName + ", " + e.getMessage());
e.printStackTrace();
}
}
}
编译一下,执行javah PPTUtils生成头文件PPTUtils.h。接下来用vc写个动态链接库,记的将MSPPT.OLB(在office安装目录下)加入工程,新建一个ppt2img.cpp:
#include "stdafx.h"
#include "PPTUtils.h"
#include "msppt.h"
JNIEXPORT void JNICALL Java_com_starnet_dmb_util_PPTUtils_convertPPT2IMG(JNIEnv *env,
jclass clazz, jstring pptFileName, jstring tmpDir){
//初始化com
if (CoInitialize( NULL ) == E_INVALIDARG)
{
AfxMessageBox(_T("初始化Com失败!"));
return;
}
_Application app;
Presentations prsts;
_Presentation prst;
//jstring转成char *
const char *ppt;
ppt = env->GetStringUTFChars(pptFileName,0);
const char *tmp;
tmp=env->GetStringUTFChars(tmpDir,0);
if(!app.CreateDispatch(_T("PowerPoint.Application"))){
AfxMessageBox(_T("初始化PowerPoint失败!"));
return;
}
prsts = app.GetPresentations();
prst = prsts.Open(_T(ppt),false,false,false);
prst.SaveAs(_T(tmp),17,false);
app.ReleaseDispatch();
app.Quit();
env->ReleaseStringUTFChars(pptFileName,ppt);
env->ReleaseStringUTFChars(tmpDir,tmp);
CoUninitialize();
}