Android: How to locally load pdf files, android: how to load pdf files

Source: Internet
Author: User

Android: How to locally load pdf files, android: how to load pdf files

Most apps open PDF files by using intent to enable the mobile phone to open PDF files to view the PDF files. If you need to download the PDF files in the app, you will not use a third-party tool, open locally.

How can this requirement be achieved? I checked some information online and found a useful open-source PDF library.

It is easy to use. First, add the reference of lateral view.

compile 'com.github.barteksc:android-pdf-viewer:2.4.0'

Reference lateral view in Layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/common_title" />

    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdf_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

The next step is to download the PDF file. To save user resources, check whether the local PDF file exists before each download. If yes, download the file directly.

Here I wrote a dialog box for loading, which is used during the opening and downloading processes.

If (CheckFileExist (title)) {
BuilderShow = new CustomDialog (ShowPDFActivity. This);
LayoutInflater inflater = (LayoutInflater) getSystemService(context.layout_inflater_service);
View the View = inflater. Inflate (R.l ayout. Dialog_pdf_progress_new, null);
BuilderShow. The setContentView (view);
BuilderShow. The show ();
IsDownload = false;
RefushUI ();
} else {
IsDownload = true;
Downloadpdf.getinstance ().downloadpdf (ShowPDFActivity. This, // download path);

}

If a PDF file exists locally, the file refushUI () is loaded ();

 

Public void refushUI () {
Try {
Pdfview.fromfile (new File(// absolute path to PDF File,// title))
DefaultPage (1)
EnableAnnotationRendering (false)
The onLoad (new OnLoadCompleteListener () {
@ Override
Public void loadComplete(int nbPages) {
If (isDownload) {
DownLoadPDF. GetInstance (). CloseDilaoig ();
}
If (builderShow! . = null && builderShow isShowing ()) {
BuilderShow. Dismiss ();
}
}
})
ScrollHandle (null)
The load ();
} the catch (Exception e) {
E.p rintStackTrace ();
}
}

 

Lateral view can load PDF files in two forms: reading from files and reading from the assets Directory.

Private void displayFromAssets(String assetFileName) {
Pdfview.fromasset (assetFileName) // set the address of the PDF file
.defaultpage (6) // set the default display page 1
.onpagechange (this) // set page-turning monitor
.onload (this) // sets the load listener
.ondraw (this) // drawing listening
.showminimap (false) // PDF whether to generate a minimap in the upper right corner of the screen when zooming in
. SwipeVertical (false) // PDF document page turning is vertical, the default is to slide left and right page turning
. EnableSwipe (true) // whether page turning is allowed, page turning is allowed by default
//. Pages (2, 3, 4, 5) // filter out 2, 3, 4, 5
The load ();
}

Private void displayFromFile(File) {
Pdfview.fromfile (file) // set the address of the PDF file
.defaultpage (6) // set the default display page 1
.onpagechange (this) // set page-turning monitor
.onload (this) // sets the load listener
.ondraw (this) // drawing listening
.showminimap (false) // PDF whether to generate a minimap in the upper right corner of the screen when zooming in
. SwipeVertical (false) // PDF document page turning is vertical, the default is to slide left and right page turning
. EnableSwipe (true) // whether page turning is allowed, the default is allowed
//. Pages (2, 3, 4, 5) // filter out 2, 3, 4, 5
The load ();
}

There is no PDF file locally, which must be obtained from the server. DownLoadPDF. getInstance (). downLoadPDF (showpdfacti.pdf. this, // download path );

 

Public class DownLoadPDF {
Private static Context Context;
Private static File;
Private static CustomDialog builder = null;
Private static Handler ddhandle;
Private static DownLoadPDF instance = null;
Public static DownLoadPDF getInstance () {
If (the instance = = null) {
Synchronized (DownLoadPDF. Class) {
If (the instance = = null) {
The instance = new DownLoadPDF ();
}
}
}
Return the instance.
}
Public void downLoadPDF(final Context con, final String url, final String title, final Handler ddhandler) {
Ddhandle = ddhandler;
The context = con;
The builder = new CustomDialog (con);
LayoutInflater inflater = (LayoutInflater) con.getsystemservice (context.layout_inflater_service);
View the View = inflater. Inflate (R.l ayout. Dialog_pdf_progress_new, null);
Builder. The setContentView (view);
Builder. The show ();

New Thread () {
@ Override
Public void the run () {
Try {
The file = getFileFromServer (url, title);
Sleep (200);
If (the file! = null) {
Handler. SendEmptyMessage (2);
}
} catch (Exception e) {
E.p rintStackTrace ();
Builder. Dismiss ();
Handler. SendEmptyMessage (1);
}
}
}. The start ();
}
Public void closeDilaoig () {
If (builder! = null && builder. IsShowing ()) {
Builder. Dismiss ();
}
Public static int length;
Public static File getFileFromServer(String path,String title)
Throws the Exception {
// if equal, the current sdcard is mounted on the phone and is available
If (Environment. GetExternalStorageState (.) equals (
Environment. MEDIA_MOUNTED)) {
URL URL = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openconnection ();
Conn. SetConnectTimeout (5000);
Conn. SetDoInput (true);
Conn. The connect ();
Length = conn. GetContentLength ();
InputStream is = conn. GetInputStream ();
// store the PDF file in the specified folder
File filePath = new File(// specify folder path);
If (! {filePath. The exists ())
FilePath. The mkdir ();
}
File = new File(filePath, title+".pdf");
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
Byte [] buffer = new byte[1024];
Int len.
While ((len = bis. Read (buffer))! = 1) {
Fos. Write (buffer, 0, len);
Handler. SendEmptyMessage (0);
}
Fos. Close ();
The bis. Close ();
Is the close ();
Return the file;
} else {
Handler. SendEmptyMessage (1);
Return null;
}
}
Private static Handler Handler = new Handler(){
@ Override
Public void handleMessage(Message MSG) {
Super. HandleMessage (MSG);
The switch (MSG. What) {
Case 0:
Break;
Case 1:
// download failed
Toast.maketext (context, "download failed, please try again later!" Toast), LENGTH_SHORT), show ();
Break;
Case 2:
Ddhandle. SendEmptyMessage (100);
Break;
Default:
Break;
}
}

};
} 

 

As you can see, handler is successfully downloaded at the pdf price. sendEmptyMessage (2); When case is 2, The ddhandle sent by calling the page of this tool class resends a message,

After receiving the message, the call interface will call refushUI () again to open the PDF file.

The above is my summary of the local PDF file loading method. If you do not understand or make any mistakes during use, please feel free to harass me!

 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.