1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Android打开pdf文件

Android打开pdf文件

时间:2024-03-07 06:07:22

相关推荐

Android打开pdf文件

转/article/136364.htm

Android的WebView做不到ios的WebView那样可以很方便的直接预览pdf文件。要实现利用WebView预览pdf我们可以使用谷歌文档服务:

这种方式国内网络环境是不用考虑的。当然也有替代的方案:我们可以使用mozilla开源的PDF.js。

Github

mozilla 官方demo

一 WebView设置:

二 实现方式

方式一: 使用mozilla部署在github pages上的Viewer

这种方式和使用google docs是差不多一样的,重要的是国内可以直接访问,但是会遇到跨域的问题。

方式二:下载PDF.js放到assets目录下

如果pdf文件不能跨域访问的话可以使用这种方式,先把文件下载到本地然后传入本地文件路径预览pdf:

PDF.js本身是一个比较大的库,如果全部放到本地的话apk差不多会增大5m左右。所以我们可以考虑吧PDF.js部署到服务端或者使用cdn的方式。

先下载,然后再打开.原文:/ming_147/article/details/53408233

public class PdfHttpDownloader {

private Context context;

public PdfHttpDownloader(Context context) {

this.context = context;

}

/**

* 打开pdf

* pdf:PDF url

* name:pdf文件的名字

*/

public void startPdfActivity(String pdf, String name) {

String terPath = getSDPath() + "/trader/" + name + ".PDF";

File file = new File(terPath);

if (file.exists()) {

Intent intent = getPdfFileIntent(terPath);

context.startActivity(intent);

} else {

downLoadPdf(pdf, name);

}

}

public Intent getPdfFileIntent(String path) {

Intent i = new Intent(Intent.ACTION_VIEW);

i.addCategory(Intent.CATEGORY_DEFAULT);

i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Uri uri = Uri.fromFile(new File(path));

i.setDataAndType(uri, "application/pdf");

return i;

}

public void downLoadPdf(final String pdf, final String name) {

Request request = new Request.Builder()

.url(pdf)

.get()

.build();

OkHttpClient http = new OkHttpClient();

http.newCall(request)

.enqueue(new com.squareup.okhttp.Callback() {

@Override

public void onFailure(Request request, IOException e) {

}

@Override

public void onResponse(Response response) {

InputStream is = null;

byte[] buf = new byte[1024];

int len = 0;

FileOutputStream fos = null;

String terPath = null;

File file = null;

try {

is = response.body().byteStream();

terPath = getSDPath() + "/trader/" + name + ".PDF";

file = new File(terPath);

fos = new FileOutputStream(file);

while ((len = is.read(buf)) != -1) {

fos.write(buf, 0, len);

}

fos.flush();

//下载成功

if (file.exists()) {

Intent intent = getPdfFileIntent(terPath);

context.startActivity(intent);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

if (is != null)

is.close();

} catch (IOException e) {

}

try {

if (fos != null)

fos.close();

} catch (IOException e) {

}

}

}

});

}

private String getSDPath() {

File sdDir = null;

boolean sdCardExist = Environment.getExternalStorageState()

.equals(Environment.MEDIA_MOUNTED); //判断sd卡是否存在

if (sdCardExist) {

sdDir = Environment.getExternalStorageDirectory();//获取跟目录

}

return sdDir.toString();

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。