安卓在线浏览pdf

司徒墨竹
2023-12-01

在开发app的时候,无论是涉及文档还是协议等观看的功能,大多数的需求多要求我们进行可下载,可在线浏览的形式。同时因为iOS支持浏览器在线浏览这类文档,因此安卓的开发就被放置到首位了。现在安卓手机不支持浏览器直接打开pdf在线浏览的功能,所以在开发的过程中,就是采用了先下载后展示的形式。

一般pdf的显示有2种插件调用,mupdf和PDFview的显示。mupdf在开发中因为没有搞清楚如何做放大缩小的功能,所以暂时搁置了,在下载的时候采用了mupdf的代码,在显示的时候直接采用了PDFview的显示的代码。

直接代码展示:

一  插件类(下载服务端的路径,存储到本地文件的路径,然后跳转到用PDFview显示的类中(将本地的文件路径传至显示的类中))

public class CPPDF extends CSIIPlugin{
private MuPDFCore core;
private String mFileName;
private String urlpath = "";
private String Url = "";
public BaseActivity activity;
public void OnlinePdf (final PluginEntity entity){

//获取服务端传过来的下载pdf的地址
activity = (BaseActivity) entity.getActivity();
String params = entity.getParams().toString();
try {
JSONObject jsonObject = new JSONObject(params);
Url = jsonObject.getString("Url");
} catch (JSONException e) {
e.printStackTrace();
}
urlpath = Url;

loadDataThreah ldt = new loadDataThreah();
ldt.start();
}


class loadDataThreah extends Thread {
public void run() {
try {
showPDF(urlpath);


} catch (Exception e) {
e.printStackTrace();
}
}
}


// 从服务器下载PDF,然后存储到本地的文件中的一个路径,并且跳转到PDFview的类中(该类中就读取本地文件的路径)
public void showPDF(String urlpath) throws Exception {
int lastSlashPos = urlpath.lastIndexOf('/');
mFileName = new String(lastSlashPos == -1 ? urlpath
: urlpath.substring(lastSlashPos + 1));
URL u = new URL(urlpath);
// String path = createDir(mFileName+".pdf");
String path = createDir(mFileName);
byte[] buffer = new byte[1024 * 8];
int read;
int ava = 0;
long start = System.currentTimeMillis();
BufferedInputStream bin;
try {
HttpURLConnection urlcon = (HttpURLConnection) u.openConnection();
double fileLength = (double) urlcon.getContentLength();
bin = new BufferedInputStream(u.openStream());
BufferedOutputStream bout = new BufferedOutputStream(
new FileOutputStream(path));
while ((read = bin.read(buffer)) > -1) {
bout.write(buffer, 0, read);
ava += read;
int a = (int) Math.floor((ava / fileLength * 100));
// dialog.setProgress(a);
long speed = ava / (System.currentTimeMillis() - start);
System.out.println("Download: " + ava + " byte(s)"
+ "    avg speed: " + speed + "  (kb/s)");
}
bout.flush();
bout.close();
Uri uri = Uri.parse(path);
// Intent intent = new Intent(activity, MuPDFActivity.class);
Intent intent = new Intent(activity, PDFViewActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
intent.putExtra("MyFileName", mFileName);
activity.startActivity(intent);
} catch (IOException e) {
e.printStackTrace();
}


}


private String createDir(String filename) {
File sdcardDir = Environment.getExternalStorageDirectory();
// 得到一个路径,内容是sdcard的文件夹路径和名字
String path = sdcardDir.getPath() + "/MyMobileDownlod";
File path1 = new File(path);
if (!path1.exists())
// 若不存在,创建目录,可以在应用启动的时候创建
path1.mkdirs();
path = path + "/" + filename;
return path;
}
}

二  PDFview显示的类

 

/**
 * pdf的在线浏览的类
 */
public class PDFViewActivity extends BaseActivity {
private String MyFileName;//插件传回的地址
private String path;
private PDFView pdfView;//PDFview的控件
private String mFileName;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = getIntent();
MyFileName = intent.getStringExtra("MyFileName");
File sdcardDir = Environment.getExternalStorageDirectory();
// 得到一个路径,内容是sdcard的文件夹路径和名字
// path = sdcardDir.getPath() + "/MyMobileDownlod/"+MyFileName+".pdf";
path = sdcardDir.getPath() + "/MyMobileDownlod/"+MyFileName;
int lastSlashPos = path.lastIndexOf('/');
mFileName = new String(lastSlashPos == -1 ? path
: path.substring(lastSlashPos + 1));
pdfView = (PDFView) findViewById(R.id.pdfView);  
File file = new File(path);
        pdfView.fromFile(file)
                .defaultPage(1)//默认展示第一页
                .onPageChange(new OnPageChangeListener() {

@Override
public void onPageChanged(int page, int pageCount) {

}
})//监听页面切换
.swipeVertical(true)//垂直展示
                .load();

}




@Override
public void noticeReceiver(BaseActivity arg0, String arg1, String arg2,
ObserverCallback arg3) {

}


}

 

三 布局文件

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent" >  
  
    <com.joanzapata.pdfview.PDFView  
        android:id="@+id/pdfView"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent" />  
</FrameLayout>  

 

四 清单文件设置

<activity
            android:name="com.artifex.mupdf.PDFViewActivity"
            android:configChanges="orientation|keyboardHidden"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Light.NoTitleBar">
        </activity>

 

五  引用的PDFview的eclipse的jar包
已上传,其他的方面未涉及的可能还需要调整,请见谅。

 

 类似资料: