我们都知道安卓打开office资源可以用浏览器打开,但是需要翻墙,而iOS打开只需要自带的webview就能打开。真是坑人啊
我找了半天找到poi,然后自己改了下,实现了office资源的展示。下面就为大家来介绍我的思路
工具:eclipse,android-poi.jar
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;
这么几个poi的类public void convert2Html(String fileName, String outPutFile)
throws TransformerException, IOException,
ParserConfigurationException,OutOfMemoryError{
HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(
fileName));
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.newDocument());
// 设置图片路径
wordToHtmlConverter.setPicturesManager(new PicturesManager() {
public String savePicture(byte[] content, PictureType pictureType,
String suggestedName, float widthInches, float heightInches) {
// 相对html路径
return suggestedName;
}
});
// 保存图片
List<Picture> pics = wordDocument.getPicturesTable().getAllPictures();
File file1 = new File(savePath);
if (pics != null) {
for (int i = 0; i < pics.size(); i++) {
Picture pic = (Picture) pics.get(i);
try {
pic.writeImageContent(new FileOutputStream(new File(file1
.getPath() + "/" + pic.suggestFullFileName())));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
wordToHtmlConverter.processDocument(wordDocument);
Document htmlDocument = wordToHtmlConverter.getDocument();
ByteArrayOutputStream out = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(out);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, streamResult);
out.close();
// 保存html文件
writeFile(new String(out.toByteArray()), outPutFile);
}
// 将html文件保存到sd卡
public void writeFile(String content, String path) {
FileOutputStream fos = null;
BufferedWriter bw = null;
try {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
fos = new FileOutputStream(file);
bw = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));
bw.write(content);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fos != null)
fos.close();
} catch (IOException ie) {
}
}
}
filename是文件路径,ouputfile是转化后的文件保存路径。
// WebView加载显示本地html文件
webView.loadUrl("file://" + savePath + docName + ".html");
现在这个方法支持doc文件,docx文件不支持,还没找到方法。
2.打开ppt文件(这个功能可能有点简单,只是单纯的展示作用)
思路:ppt文件--转化为多张图片--用webview来展示(原因:由于功能需求:做成展示功能,所以ppt里面的东西不能点击,播放声音)
用到的poi的类有
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.usermodel.SlideShow;
将ppt转换为图片
初始化slide和slideshow
//path文件路径
ppt = new SlideShow(new File(path));
//ppt总页数
pgsize = ppt.getPageSize();
slide = ppt.getSlides();
slideCount = slide.length;
转化png
/**
* 生成图片
*/
private void addImageView(final int pos) {
final Bitmap bmp = Bitmap.createBitmap((int) pgsize.getWidth(), (int) pgsize.getHeight(), Config.RGB_565);
Canvas canvas = new Canvas(bmp);
Paint paint = new Paint();
paint.setColor(android.graphics.Color.WHITE);
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
canvas.drawPaint(paint);
final Graphics2D graphics2d = new Graphics2D(canvas);
final AtomicBoolean isCanceled = new AtomicBoolean(false);
// render
Thread runnable = new Thread() {
@Override
public void run() {
try {
if(slide==null){
return;
}
slide[pos].draw(graphics2d, isCanceled, handler, pos);
Message msg = handler.obtainMessage();
// msg.obj = imageView;
// imageView.setTag(bmp);
write(Bitmap2Bytes(bmp), pos);
msg.what = 3;
msg.arg1 = pos;
handler.sendMessage(msg);
if(bmp!=null&&!bmp.isRecycled()){
bmp.recycle();
}
} catch (Exception e) {
Message msg = handler.obtainMessage();
try {
slide[pos + 1].draw(graphics2d, isCanceled, handler, pos);
// msg.obj = imageView;
// imageView.setTag(bmp);
try {
write(Bitmap2Bytes(bmp), pos + 1);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
msg.what = 3;
msg.arg1 = pos + 1;
handler.sendMessage(msg);
if (bmp != null && !bmp.isRecycled()) {
bmp.recycle();
}
} catch (Exception e2) {
msg.what = 3;
msg.arg1 = pos + 1;
handler.sendMessage(msg);
}
} catch (OutOfMemoryError e) {
// Toast.makeText(getActivity(), "打开异常,请重新打开",
// Toast.LENGTH_LONG).show();
System.gc();
}
}
};
runnable.start();
}
这个poi有些图片会生成不出来,所以有时候就会缺失,但是大部分的ppt都是能够完整生成出来的。
最后图片在一个file里面,按生成的顺序,里面的排列也是按顺序来的,所以可以直接用webview展示
private void loadWebView() {
File fiele = new File(pptPath);
File[] files = fiele.listFiles();
if (files.length != 0) {
loadingdialog.dismiss();
String data = "<html>" + "<body align=center>" +
getImagesHtml(files) + "</body>" +
"</html>";
Log.e("网页html", data);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.loadDataWithBaseURL("file://" + pptPath, data, "text/html", "UTF-8", null);
}
}
private String getImagesHtml(File[] file) {
String data = "";
for (File file2 : file) {
data += "<img" + " src=file://" + file2.getAbsolutePath() + " width=" + pgsize.getWidth() + " height="
+ (pgsize.getHeight() + ScreenSizeUtil.Dp2Px(getActivity(), 48)) + " display:block; margin:0 auto;" + "><br/>";
}
return data;
}
3.打开pdf资源
直接上主代码
package org.ebookdroid.core;
import java.io.File;
import java.util.List;
import java.util.concurrent.atomic.Atomic