android webview 显示doc,pdf文件
2018-06-06 本文已影响143人
tmyzh
项目需要在app中直接显示doc,pdf文件。要么是文件需要像pdf阅读App一样阅读,可以采用下面方案一,要么是注册协议,帮助这些单页(无奈,后台不给html页面直接丢给一个文件)可以采用方案二,三。
方案一: 使用自定义控件展示doc,pdf文件
这个不是本文的重点,推荐GitHub上的PDFview控件,链接如下
PDFView
方案二:使用POI加载显示doc和pdf文件
思路:
- 1 下载doc和pdf文件
- 2 调用poi将word文档转成html格式并保存到本地
- 3 用webview控件展示本地html(为什么会考虑用webview的方式加载,没办法ios可以很直接简单的用webview加载文件,google加油吧)
要加载入项目的两个Jar包 poi-3.9-20121203.jar和poi-scratchpad-3.9-20121203,下载地址Jar包
代码如下
package com.example.office;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
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;
import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MainActivity extends Activity {
private String docPath = "/mnt/sdcard/documents/";
private String docName = "test.doc";
private String savePath = "/mnt/sdcard/documents/";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String name = docName.substring(0, docName.indexOf("."));
try {
if(!(new File(savePath+name).exists()))
new File(savePath+name).mkdirs();
convert2Html(docPath+docName,savePath+name+".html");
} catch (Exception e){
e.printStackTrace();
}
//WebView加载显示本地html文件
WebView webView = (WebView)this.findViewById(R.id.office);
WebSettings webSettings = webView.getSettings();
webSettings.setLoadWithOverviewMode(true);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
webView.loadUrl("file:/"+savePath+name+".html");
}
/**
* word文档转成html格式
* */
public void convert2Html(String fileName, String outPutFile)
throws TransformerException, IOException,
ParserConfigurationException {
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 )
{
String name = docName.substring(0,docName.indexOf("."));
return name+"/"+suggestedName;
}
} );
//保存图片
List<Picture> pics=wordDocument.getPicturesTable().getAllPictures();
if(pics!=null){
for(int i=0;i<pics.size();i++){
Picture pic = (Picture)pics.get(i);
System.out.println( pic.suggestFullFileName());
try {
String name = docName.substring(0,docName.indexOf("."));
pic.writeImageContent(new FileOutputStream(savePath+ name + "/"
+ 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) {
}
}
}
}
有问题欢迎在评论区留言
方案三:与方案二类似,方法更简单,非常骚气,但是需要一些html基础
思路:
- 1 将doc,pdf文件直接打开另存为html文件,注意编码格式。
- 2 将html存放assets目录下
- 3 webview加载本地html文件
web.loadUrl("file:///android_asset/test.html");
需要注意一点
word文件平铺过大时,webview加载要么需要横向滑动才能显示完全,要么web.getSettings().setLoadWithOverviewMode(true);使得一屏幕显示,但是无法控制文件换行导致字体过小,两个效果都不行
解决方案
在本地html head标签里面加一个meta属性,web页面适配移动端屏幕
<meta name="eqMobileViewport" content="width=320,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
这样就能很好的显示