前两天用到PDF加载功能,需求是从url加载,本以为很简单的事,只需一个webview就解决了,没想到webview不支持,网上找了一些解决方案都不太理想,于是想自己封装一个。
开源的库基本没有支持url加载的(或者我没找到),我的实现思路是先把文件下载下来,再从已加载本地file的形式加载出来,开源库选择
/AndroidPdfViewer
传送门
点击打开链接
核心代码
public void loadFromUrl(){
final String SDPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/PDFViewCache/";
int index = fileUrl.lastIndexOf("/");
String fileName = fileUrl.substring(index);
final File file = new File(SDPath, fileName);
if(file.exists()){
//文件存在
if(onFileDownloadCompleteListener!=null){
onFileDownloadCompleteListener.onDownloadComplete(file);
}
PDFView.this.fromFile(file);
load();
}else{
DownloadUtil.get().download(fileUrl, SDPath, new DownloadUtil.OnDownloadListener() {
@Override
public void onDownloadSuccess(File file) {
if(onFileDownloadCompleteListener!=null){
onFileDownloadCompleteListener.onDownloadComplete(file);
}
PDFView.this.fromFile(file);
load();
}
@Override
public void onDownloading(int progress) {
}
@Override
public void onDownloadFailed() {
}
});
}
}
先判断文件是否已经缓存了,如果缓存了则直接加载,如果没缓存就下载文件并显示
使用方法
Step 1. Add the JitPack repository to your build file
Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Step 2. Add the dependency
dependencies {
compile 'com.github.shxdos:AndroidPdfViewer:2.7.0-beta.2'
}
pdfView.fromUrl("http://www.anweitong.com/upload/document/standard/national_standards/138793918364316200.pdf") .enableSwipe(true) // allows to block changing pages using swipe .defaultPage(0) .onLoad(this) // called after document is loaded and starts to be rendered .onPageChange(this) .swipeHorizontal(false) .enableAntialiasing(true) .onFileDownload(this) .loadFromUrl();github地址 https://github.com/shxdos/AndroidPdfViewer