How Android loads PDF files locally

Source: Internet
Author: User

Most apps open PDF files by intent The tool that opens the PDF file on your phone to view the PDF file, and if the requirement is that the user has downloaded the pdf file in the app, it will not be opened locally via a third-party tool.

How is this need to be achieved? On the Internet to check some information, found a very useful PDF open Source Library.

It's also easy to use, first add the Pdfview reference

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

Referencing Pdfview in layouts

<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>

Next is to download the PDF file, in order to save the user resources, before each download to check if there is a local PDF file, if there is a direct open, do not download.

Here I wrote a loading dialog box that was used during the open process and during the download process.

if(Checkfileexist (title)) {Buildershow=NewCustomdialog (showpdfactivity. This); Layoutinflater Inflater=(Layoutinflater) Getsystemservice (Context.layout_inflater_service); View View= Inflater.inflate (R.layout.dialog_pdf_progress_new,NULL);            Buildershow.setcontentview (view);            Buildershow.show (); Isdownload=false;        Refushui (); }Else{isdownload=true; downloadpdf.getinstance (). Downloadpdf (showpdfactivity. This ,//download path); }

If there is a PDF file locally, start loading the PDF file,Refushui ();

     Public voidRefushui () {Try{pdfview.fromfile (NewFile (absolute path to the//pdf file,//title). Defaultpage (1). enableannotationrendering (false). OnLoad (NewOnloadcompletelistener () {@Override Public voidLoadComplete (intnbpages) {                            if(isdownload) {downloadpdf.getinstance (). Closedilaoig (); }                            if(Buildershow! =NULL&&buildershow.isshowing ())                            {Buildershow.dismiss (); }}). Scrollhandle (NULL). Load (); }Catch(Exception e) {e.printstacktrace (); }    }

Pdfview loading PDF files in two forms, one for reading from a file, and one for reading from the assets directory

    Private voiddisplayfromassets (String assetfilename) {pdfview.fromasset (assetfilename)//Set the PDF file address. Defaultpage (6)//set default to show page 1th. Onpagechange ( This)//set page Turn monitoring. OnLoad ( This)//Set Load monitoring. OnDraw ( This)//Drawing Monitoring. Showminimap (false)//when a PDF is zoomed in, does it generate a small map in the upper-right corner of the screen. swipevertical (false)//whether the page of a PDF document is a vertical page, the default is to scroll left and right. Enableswipe (true)//whether to allow page flipping, the default is to allow page flipping//. Pages (2, 3, 4, 5)//filter out 2, 3, 4, 5. Load (); }    Private voiddisplayfromfile (file file) {pdfview.fromfile (file)//Set the PDF file address. Defaultpage (6)//set default to show page 1th. Onpagechange ( This)//set page Turn monitoring. OnLoad ( This)//Set Load monitoring. OnDraw ( This)//Drawing Monitoring. Showminimap (false)//when a PDF is zoomed in, does it generate a small map in the upper-right corner of the screen. swipevertical (false)//whether the page of a PDF document is a vertical page, the default is to scroll left and right. Enableswipe (true)//whether to allow page flipping, the default is to allow//. Pages (2, 3, 4, 5)//filter out 2, 3, 4, 5. Load (); }

There is no PDF file locally and needs to be fetched from the server, downloadpdf.getinstance (). Downloadpdf (showpdfactivity. This,//download path );

 Public classDownloadpdf {Private Staticcontext Context; Private Staticfile file; Private StaticCustomdialog Builder =NULL ; Private StaticHandler Ddhandle; Private StaticDownloadpdf instance =NULL;  Public Staticdownloadpdf getinstance () {if(instance==NULL) {synchronized (downloadpdf.class){                if(instance==NULL) {instance=Newdownloadpdf (); }            }        }        returninstance; }     Public voiddownloadpdf (Final Context con, final string url, final string title, Final Handler ddhandler) {Ddhandle =Ddhandler; Context=con; Builder=NewCustomdialog (con); Layoutinflater Inflater=(Layoutinflater) Con.getsystemservice (Context.layout_inflater_service); View View= Inflater.inflate (R.layout.dialog_pdf_progress_new,NULL);        Builder.setcontentview (view);        Builder.show (); NewThread () {@Override Public voidrun () {Try{file=Getfilefromserver (Url,title); Sleep ( $); if(File! =NULL) { handler.sendemptymessage ( 2); }                } Catch(Exception e) {e.printstacktrace ();                    Builder.dismiss (); Handler.sendemptymessage (-1);    }}}.start (); }     Public voidClosedilaoig () {if(Builder! =NULL&&builder.isshowing ())        {Builder.dismiss (); }    } Public Static intlength;  Public StaticFile getfilefromserver (String path,string title) throws Exception {//if equal, indicates that the current sdcard is mounted on the phone and is available        if(Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {URL URL=NewURL (path); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setconnecttimeout ( the); Conn.setdoinput (true);            Conn.connect (); Length=conn.getcontentlength (); InputStream is=Conn.getinputstream (); //Store the PDF file under the specified folderFile FilePath =NewFile (// Specify folder path ); if(!filepath.exists ())            {Filepath.mkdir (); } File File=NewFile (FilePath, title+". pdf"); FileOutputStream Fos=Newfileoutputstream (file); Bufferedinputstream bis=NewBufferedinputstream ( is); byte[] buffer =New byte[1024x768]; intLen;  while(len = bis.read (buffer))! =-1) {fos.write (buffer,0, Len); Handler.sendemptymessage (0);            } fos.close ();            Bis.close ();  is. Close (); returnfile; } Else{handler.sendemptymessage (-1); return NULL; }    }    Private StaticHandler Handler =NewHandler () {@Override Public voidhandlemessage (Message msg) {super.handlemessage (msg); Switch(msg.what) { Case 0:                 Break;  Case-1:                //Download FailedToast.maketext (Context,"download failed, please try again later! ", Toast.length_short). Show ();  Break;  Case 2: Ddhandle.sendemptymessage ( -);  Break; default:                 Break; }        }    };}

As you can see, handler.sendemptymessage (2)when the PDF price is successfully downloaded, and when case is 2, it is transmitted by invoking the page of the tool class. Ddhandle sent a message again,

The call interface will call Refushui () again after receiving the message. This method to open the PDF file.

The above is my summary of the local loading PDF file method, if you are in the process of using a misunderstanding or wrong place, welcome harassment!

How Android loads PDF files locally

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.