Android WebView显示Pdf、2007 word Excel,要求转换成html显示.

公司要求做客户端程序使用webview显示本地文件. 我使用的是poi3.8 可对2007Word无从下手,word中包含表格和图片... pdf用什么解析好点???有做过类似项目的哥们搭把手...感激不尽...

先在服务器上转完再显示,可以用jacob不过要在服务器上装Libre office 或 openoffice 或 wps(Linux)、office(office),不过我只用过windows上的.
jacob和poi一样的,只不过poi不依赖office软件,jacob依赖;而jacob可以做图片的显示,这个要比poi强大一些,而且poi更出名些.

这是我之前做的,也是参考别人的,你可以看看,希望对你有帮助。

package com.word;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class WordReadActivity extends Activity {
private ListView listV=null;
private List<File> list=null;
private int a[] ={R.drawable.doc,R.drawable.dir};
private ArrayList<HashMap<String,Object>> recordItem;

private File PresentFile;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.browse);
        listV=(ListView)this.findViewById(R.id.list);
        list_files();
    }
    private void list_files(){
     File path=android.os.Environment.getExternalStorageDirectory();
     PresentFile = path;
     File[] file=path.listFiles();
     fill(file);
    }
    private void fill(File[] file){
     SimpleAdapter adapter=null;
     recordItem = new ArrayList<HashMap<String,Object>>();
     list=new ArrayList<File>();
     for(File f: file){
      if(Invalid(f) ==1){
       list.add(f);
       HashMap<String,Object> map= new HashMap<String,Object>();
       map.put("picture", a[0]);
       map.put("name", f.getName());
       recordItem.add(map);       
      }
      if(Invalid(f)==0){
       list.add(f);
       HashMap<String,Object> map= new HashMap<String,Object>();
       map.put("picture", a[1]);
       map.put("name", f.getName());
       recordItem.add(map); 
      }
     }
     adapter = new SimpleAdapter(this, recordItem, R.layout.item, new String[]{"picture", "name"}, new int[]{R.id.picture, R.id.text});
  listV.setAdapter(adapter);
  listV.setAdapter(adapter);
  listV.setOnItemClickListener(new Clicker());
    }
    private int Invalid(File f){
     if(f.isDirectory()){
      return 0;
     }else{
      String filename=f.getName().toLowerCase();
      if(filename.endsWith(".doc")){
       return 1;
      }
      return 2;
     }
    }

    private class Clicker implements OnItemClickListener{
  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
    long arg3) {
   Intent i= new Intent();
   String nameStr=null;
   i.setClass(WordReadActivity.this, ViewFile.class);
   Bundle bundle = new Bundle();
   File file= list.get(arg2);
   PresentFile=file;
   if(file.isDirectory()){
    File[] files=file.listFiles();
    fill(files);
   }else{
    nameStr=file.getAbsolutePath();
    bundle.putString("name", nameStr);
    i.putExtras(bundle);
    startActivity(i);
    finish();
   }
  }
    }
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
  if(keyCode==KeyEvent.KEYCODE_BACK){
   if(PresentFile.isDirectory()){
    if(PresentFile.equals(android.os.Environment.getExternalStorageDirectory())){
     this.finish();
    }else{
     PresentFile=PresentFile.getParentFile();
     File file=PresentFile;
     File[] files=file.listFiles();
     fill(files);
    }
   }
   if(PresentFile.isFile()){
    if(PresentFile.getParentFile().isDirectory()){
     PresentFile = PresentFile.getParentFile();
        File file = PresentFile;
        File[] files = file.listFiles();
        fill(files);
    }
   }
  }
  return false;
}
}

这个是先开始读取sdcard的目录,用LIstview显示,如果你只需要一个Button点击进入的话,就直接传一个文件名用Bundle带参传值过去就好了。。

package com.word;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.hwpf.usermodel.TableIterator;
import org.apache.poi.hwpf.usermodel.TableRow;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
public class ViewFile extends Activity{
private String nameStr = null;
private Range range = null;
private HWPFDocument hwpf = null;
private String htmlPath;
private String picturePath;
private WebView view; 
private List pictures; 
private TableIterator tableIterator; 
private int presentPicture = 0; 
private int screenWidth; 
private FileOutputStream output; 
private File myFile;

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  setContentView(R.layout.view);  
  view = (WebView)findViewById(R.id.show);  
  screenWidth = this.getWindowManager().getDefaultDisplay().getWidth() - 10;  
  Intent intent = this.getIntent();
  Bundle bundle = intent.getExtras();
  nameStr = bundle.getString("name");

  getRange();   
  makeFile();  
  readAndWrite();
// String url="http://www.baidu.com";
  String uri="file:///mnt/sdcard/doc/doc.html";
// String url="content://com.android.htmlfileprovider/sdcard/doc/doc.html";
  view.loadUrl(uri);
// view.loadUrl("content://com.android.htmlfileprovider/" + htmlPath);
  System.out.println("htmlPath" + htmlPath);
}

public boolean onCreateOptionsMenu(Menu menu){  
  super.onCreateOptionsMenu(menu);
  menu.add(0, 0, 0, "关于文件").setIcon(this.getResources().getDrawable(R.drawable.importdb));
  menu.add(0, 1, 1, "关于作者").setIcon(this.getResources().getDrawable(R.drawable.exportdb));
  return true;
}

public boolean onOptionsItemSelected(MenuItem item){  
  switch(item.getItemId()){
  case 0:
   showDialog(0);
   break;
  case 1:
   showDialog(1);
   break;
  }
  return super.onOptionsItemSelected(item);
}

protected Dialog onCreateDialog(int id){
  switch(id){
  case 0:
   return buildDialogProgram(ViewFile.this);
  case 1:
   return buildDialogAuthor(ViewFile.this);
  }
  return null;
}

private Dialog buildDialogAuthor(Context context){

  AlertDialog.Builder builder = new AlertDialog.Builder(context);
  builder.setIcon(this.getResources().getDrawable(R.drawable.dslab));
  builder.setTitle("关于我们");
  builder.setMessage("提示");
  builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener(){
   public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub
    dialog.dismiss();
   }

  });
  return builder.create();

}

private Dialog buildDialogProgram(Context context){

  AlertDialog.Builder builder = new AlertDialog.Builder(context);
  builder.setTitle("关于文件");
  builder.setIcon(this.getResources().getDrawable(R.drawable.importdb));
  String programInfo = "word" + hwpf.characterLength() + "\n";
  programInfo = programInfo + "段落个数:" + range.numParagraphs() + "\n";
  programInfo = programInfo + "图片个数:" + pictures.size() + "\n";

  builder.setMessage(programInfo);
  builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {

   public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub
    dialog.dismiss();
   }
  });

  return builder.create();
}

public void makeFile(){

  String sdStateString = android.os.Environment.getExternalStorageState();

     if(sdStateString.equals(android.os.Environment.MEDIA_MOUNTED)){
      try{
       File sdFile = android.os.Environment.getExternalStorageDirectory();

       String path = sdFile.getAbsolutePath() + File.separator + "doc";

       String temp = path + File.separator + "doc.html";

       File dirFile = new File(path);
       if(!dirFile.exists()){
        dirFile.mkdir();
       }

       File myFile = new File(path + File.separator + "doc.html");

       if(!myFile.exists()){
        myFile.createNewFile();
       }

       htmlPath = myFile.getAbsolutePath();
      }
      catch(Exception e){

      }
     }
}

/*用来在sdcard上创建图片*/
public void makePictureFile(){
  String sdString = android.os.Environment.getExternalStorageState();

  if(sdString.equals(android.os.Environment.MEDIA_MOUNTED)){
   try{
    File picFile = android.os.Environment.getExternalStorageDirectory();

    String picPath = picFile.getAbsolutePath() + File.separator + "doc";

    File picDirFile = new File(picPath);

    if(!picDirFile.exists()){
     picDirFile.mkdir();
    }
    File pictureFile = new File(picPath + File.separator + presentPicture + ".jpg");

    if(!pictureFile.exists()){
     pictureFile.createNewFile();
    }

    picturePath = pictureFile.getAbsolutePath();

   }
   catch(Exception e){
    System.out.println("PictureFile Catch Exception");
   }
  }
}

public void onDestroy(){
  super.onDestroy();
}
/*读取word中的内容写到sdcard上的.html文件中*/
public void readAndWrite(){

  try{
   myFile = new File(htmlPath);
   output = new FileOutputStream(myFile);
   String head = "<html><body>";
   String tagBegin = "<p>";
   String tagEnd = "</p>";


   output.write(head.getBytes());

   int numParagraphs = range.numParagraphs();

   for(int i = 0; i < numParagraphs; i++){
    Paragraph p = range.getParagraph(i);

    if(p.isInTable()){
     int temp = i;
     if(tableIterator.hasNext()){
      String tableBegin = "<table style=\"border-collapse:collapse\" border=1 bordercolor=\"black\">";
      String tableEnd = "</table>";
      String rowBegin = "<tr>";
      String rowEnd = "</tr>";
      String colBegin = "<td>";
      String colEnd = "</td>";

      Table table = tableIterator.next();

      output.write(tableBegin.getBytes());

      int rows = table.numRows();

      for( int r = 0; r < rows; r++){
       output.write(rowBegin.getBytes());
       TableRow row = table.getRow(r);
       int cols = row.numCells();
       int rowNumParagraphs = row.numParagraphs();
       int colsNumParagraphs = 0;
       for( int c = 0; c < cols; c++){
        output.write(colBegin.getBytes());
        TableCell cell = row.getCell(c);
        int max = temp + cell.numParagraphs();
        colsNumParagraphs = colsNumParagraphs + cell.numParagraphs();
        for(int cp = temp; cp < max; cp++){
         Paragraph p1 = range.getParagraph(cp);
         output.write(tagBegin.getBytes());
         writeParagraphContent(p1);
         output.write(tagEnd.getBytes());
         temp++;
        }
        output.write(colEnd.getBytes());
       }
       int max1 = temp + rowNumParagraphs;
       for(int m = temp + colsNumParagraphs; m < max1; m++){
        Paragraph p2 = range.getParagraph(m);
        temp++;
       }
       output.write(rowEnd.getBytes());
      }
      output.write(tableEnd.getBytes());
     }
     i = temp;
    }
    else{
     output.write(tagBegin.getBytes());
     writeParagraphContent(p);
     output.write(tagEnd.getBytes());
    }
   }
   String end = "</body></html>";
   output.write(end.getBytes());
   output.close();
  }
  catch(Exception e){
   System.out.println("readAndWrite Exception");
  }
}
/*以段落的形式来往html文件中写内容*/
public void writeParagraphContent(Paragraph paragraph){
  Paragraph p = paragraph;
  int pnumCharacterRuns = p.numCharacterRuns();

  for( int j = 0; j < pnumCharacterRuns; j++){

   CharacterRun run = p.getCharacterRun(j);

   if(run.getPicOffset() == 0 || run.getPicOffset() >= 1000){
    if(presentPicture < pictures.size()){
     writePicture();
    }
   }
   else{
    try{
     String text = run.text();
     if(text.length() >= 2 && pnumCharacterRuns < 2){
      output.write(text.getBytes());
     }
     else{
      int size = run.getFontSize();
      int color = run.getColor();
      String fontSizeBegin = "<font size=\"" + decideSize(size) + "\">";
      String fontColorBegin = "<font color=\"" + decideColor(color) + "\">";
      String fontEnd = "</font>";
      String boldBegin = "<b>";
      String boldEnd = "</b>";
      String islaBegin = "<i>";
      String islaEnd = "</i>";

      output.write(fontSizeBegin.getBytes());
      output.write(fontColorBegin.getBytes());

      if(run.isBold()){
       output.write(boldBegin.getBytes());
      }
      if(run.isItalic()){
       output.write(islaBegin.getBytes());
      }

      output.write(text.getBytes());

      if(run.isBold()){
       output.write(boldEnd.getBytes());
      }
      if(run.isItalic()){
       output.write(islaEnd.getBytes());
      }
      output.write(fontEnd.getBytes());
      output.write(fontEnd.getBytes());
     }
    }
    catch(Exception e){
     System.out.println("Write File Exception");
    }
   }
  }
}
/*将word中的图片写入到.jpg文件中*/
public void writePicture(){
  Picture picture = (Picture)pictures.get(presentPicture);

  byte[] pictureBytes = picture.getContent();

  Bitmap bitmap = BitmapFactory.decodeByteArray(pictureBytes, 0, pictureBytes.length);

  makePictureFile();
  presentPicture++;

  File myPicture = new File(picturePath);

  try{

   FileOutputStream outputPicture = new FileOutputStream(myPicture);

   outputPicture.write(pictureBytes);

   outputPicture.close();
  }
  catch(Exception e){
   System.out.println("outputPicture Exception");
  }

  String imageString = "<img src=\"" + picturePath + "\"";

  if(bitmap.getWidth() > screenWidth){
   imageString = imageString + " " + "width=\"" + screenWidth + "\"";
  }
  imageString = imageString + ">";

  try{
   output.write(imageString.getBytes());
  }
  catch(Exception e){
   System.out.println("output Exception");
  }
}
/*处理word和html字体的转换*/
public int decideSize(int size){

  if(size >= 1 && size <= 8){
   return 1;
  }
  if(size >= 9 && size <= 11){
   return 2;
  }
  if(size >= 12 && size <= 14){
   return 3;
  }
  if(size >= 15 && size <= 19){
   return 4;
  }
  if(size >= 20 && size <= 29){
   return 5;
  }
  if(size >= 30 && size <= 39){
   return 6;
  }
  if(size >= 40){
   return 7;
  }
  return 3;
}
/*处理word和html颜色的转换*/
private String decideColor(int a){
  int color = a;
  switch(color){
  case 1:
   return "#000000";
  case 2:
   return "#0000FF";
  case 3:
  case 4:
   return "#00FF00";
  case 5:
  case 6:
   return "#FF0000";
  case 7:
   return "#FFFF00";
  case 8:
   return "#FFFFFF";
  case 9:
   return "#CCCCCC";
  case 10:
  case 11:
   return "#00FF00";
  case 12:
   return "#080808";
  case 13:
  case 14: 
   return "#FFFF00";
  case 15: 
   return "#CCCCCC";
  case 16:
   return "#080808";
  default:
   return "#000000";
  }
}

private void getRange(){
  FileInputStream in = null;
  POIFSFileSystem pfs = null;

   try {
    in = new FileInputStream(nameStr);
    pfs = new POIFSFileSystem(in);
    hwpf = new HWPFDocument(pfs);
   } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

  range = hwpf.getRange();

  pictures = hwpf.getPicturesTable().getAllPictures();

  tableIterator = new TableIterator(range);

}
/*处理点击返回按钮*/
public boolean onKeyDown(int keyCode, KeyEvent event) {
     if (keyCode == KeyEvent.KEYCODE_BACK) {
      Intent intent = new Intent();
      intent.setClass(ViewFile.this, WordReadActivity.class);
      startActivity(intent);
      this.finish();
     }
  return false; 
  }
}

你好,我对android不太熟,但是对于java解析pdf,我刚做了一个相关的项目。
建议你学习一下xpdf,和icepdf,这些都是比较好的抽取文本的程序,但是我认为抽取pdf都会有偏差的,对于里面的表格一类的不好弄。
相对于你说的word,excel相对来说网上的资料比较多一点了,比较容易一点。

我也是在做用poi显示word和excel的内容。
目前我已经做到了支持office2003的标准,因为2007之后加入了ooxml之后比较麻烦,poi也是在ooxml纳入国际文档标准后才开始支持新版本的。
针对doc文件,poi里面支持的包是hwpf
真的对docx文件,poi里面的包是xwpf
可恶的是hwpf包里面有convert可以直接从doc转换成html。而xwpf里面没有
目前我的思路是docx文件转成doc文件,然后用doc的converter
或者是docx转换为标准的document文件(或者xml格式),然后用document转换为html
我也还是新手,你那边有解决方案说一下

这么一了死代码就搞定了???你玩我啊

楼主解决这个问题了么请问 ? 我刚好也需要在APP中集成这个功能,求帮助

楼主解决了吗,我用最新的poi 3.10 在android项目中不能运行

楼主解决了吗 求解决方案或者demo很着急先谢谢楼主了

Android WebView好像只能查看html文档吧?
Android WebView好像只能查看html文档吧?

我也是在做用poi显示word和excel的内容。
目前我已经做到了支持office2003的标准,因为2007之后加入了ooxml之后比较麻烦,poi也是在ooxml纳入国际文档标准后才开始支持新版本的。
针对doc文件,poi里面支持的包是hwpf
真的对docx文件,poi里面的包是xwpf
可恶的是hwpf包里面有convert可以直接从doc转换成html。而xwpf里面没有
目前我的思路是docx文件转成doc文件,然后用doc的converter
或者是docx转换为标准的document文件(或者xml格式),然后用document转换为html
我也还是新手,你那边有解决方案说一下

公司要求做客户端程序使用webview显示本地文件. 我使用的是poi3.8 可对2007Word无从下手,word中包含表格和图片... pdf用什么解析好点???有做过类似项目的哥们搭把手...感激不尽...

jacob依赖;而jacob可以做图片的显示,这个要比poi强大一些

楼主怎么解决的。。。

亲。你在android上把excel转成html完成了嘛。。我最近也在做这些。。如果完成了麻烦搭把手啊。。谢谢了。。我邮箱411747165@qq.com