Home GridView PDF – List,Render,Page,Zoom

GridView PDF – List,Render,Page,Zoom

GridView PDF – List,Render,Page,Zoom


Language :
Platform :
Type :


Everybody knows PDFs, Portable Document Format. Am probably everybody has or uses them.Alot of information is rendered in PDFs and since android devices are the most popular devices around,we need a way of rendering these PDFs in our device.

Okay, there are PDF readers like Adobe and Foxit, but why not make yours as a side project while learning android development.Hey,with the wealth of libraries android has, its easier than you may think. You may make a quality PDF reader for yourself.

This is an example to introduce us by giving us a way to load PDFs into a GridView and render them. Then you can swipe through the pages,scroll, zoom a page etc.

Here's a summary of what we do :

  • Read all PDF files from our SDCard into our GridView.
  • We shall display PDF icons alongside the PDF name.
  • We display these in a nice CardView in our custom gridview.
  • When the user clicks a single PDF from our gridview, we open the corresponding PDF in a new activity.
  • There the user can scroll to read all the pages, or swipe side by side to move to next page.
  • Moreover he can zoom in and out.

 

STEP BY STEP

STEP 1 : Our Build.Gradle

  • We are using Android PDF Viewer library so we need to add it as a dependency in our app level build.gradle.
  • Moreover our Custom GridView has CardViews as our viewitems so lets add the appropriate support libraries.

 

@@ -0,0 +1,29 @@
apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.1"

    defaultConfig {
        applicationId "com.tutorials.hp.gridviewpdf"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.1.1'
    compile 'com.android.support:design:24.1.1'
    compile 'com.android.support:cardview-v7:24.1.1'
    compile 'com.github.barteksc:android-pdf-viewer:1.4.0'
}

 

 

 

 

STEP 2 : Our AndroidManifest.xml

  • Given that we shall be reading our PDF documents from our File System in android device/emulator,lets add the permission for reading from external storage.

 

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.tutorials.hp.gridviewpdf">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".PDF_Activity"></activity>
    </application>

</manifest>
\ No newline at end of file

 

 

 

STEP 3 : Our PDFDoc class

  • What are we working with ? PDF Documents. Yes, so lets do that in an Object Oriented way.Lets create a POJO data object to represent a PDF document with its properties like name and file path.

 

package com.tutorials.hp.gridviewpdf;

import android.net.Uri;

/**
 * Created by Oclemy on 8/6/2016 for ProgrammingWizards Channel and http://www.camposha.com.
 */
public class PDFDoc {
    String name,path;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }
}

 

 

 

 

STEP 4 : Our CustomAdapter class

  • We are working a custom gridview as our adapterview.It therefore needs its adapter.
  • We derive from baseadapter.
  • This class shall inflate our model layout into CardView viewitems of our gridview.
  • It shall also adapt our dataset into their respective views.
  • We also open activity,pdf activity when an item is clicked.

 

package com.tutorials.hp.gridviewpdf;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by Oclemy on 7/28/2016 for ProgrammingWizards Channel and http://www.camposha.com.
 */
public class CustomAdapter extends BaseAdapter {

    Context c;
    ArrayList<PDFDoc> pdfDocs;

    public CustomAdapter(Context c, ArrayList<PDFDoc> pdfDocs) {
        this.c = c;
        this.pdfDocs = pdfDocs;
    }

    @Override
    public int getCount() {
        return pdfDocs.size();
    }

    @Override
    public Object getItem(int i) {
        return pdfDocs.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if(view==null)
        {
            //INFLATE CUSTOM LAYOUT
            view= LayoutInflater.from(c).inflate(R.layout.model,viewGroup,false);
        }

        final PDFDoc pdfDoc= (PDFDoc) this.getItem(i);

        TextView nameTxt= (TextView) view.findViewById(R.id.nameTxt);
        ImageView img= (ImageView) view.findViewById(R.id.pdfImage);

        //BIND DATA
        nameTxt.setText(pdfDoc.getName());
        img.setImageResource(R.drawable.pdf_icon);

        //VIEW ITEM CLICK
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               openPDFView(pdfDoc.getPath());
            }
        });
        return view;
    }

    //OPEN PDF VIEW
    private void openPDFView(String path)
    {
        Intent i=new Intent(c,PDF_Activity.class);
        i.putExtra("PATH",path);
        c.startActivity(i);
    }
}

 

 

 

 

STEP 5 : Our MainActivity

  • Okay, here's our launcher activity.
  • Lets initialize views like GridView here.
  • We also set the instance ofthe basedapter subclass we called CustomAdapter to our GridView.

 

package com.tutorials.hp.gridviewpdf;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.GridView;

import java.io.File;
import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final GridView gv= (GridView) findViewById(R.id.gv);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gv.setAdapter(new CustomAdapter(MainActivity.this,getPDFs()));

            }
        });
    }

    private ArrayList<PDFDoc> getPDFs()

    {
        ArrayList<PDFDoc> pdfDocs=new ArrayList<>();
        //TARGET FOLDER
        File downloadsFolder= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

        PDFDoc pdfDoc;

        if(downloadsFolder.exists())
        {
            //GET ALL FILES IN DOWNLOAD FOLDER
            File[] files=downloadsFolder.listFiles();

            //LOOP THRU THOSE FILES GETTING NAME AND URI
            for (int i=0;i<files.length;i++)
            {
                File file=files[i];

                if(file.getPath().endsWith("pdf"))
                {
                    pdfDoc=new PDFDoc();
                    pdfDoc.setName(file.getName());
                    pdfDoc.setPath(file.getAbsolutePath());

                    pdfDocs.add(pdfDoc);
                }

            }
        }

        return pdfDocs;
    }


}

 

 

 

STEP 5 : Our PDF Activity

  • This activity renders our PDF document.
  • It receives the path to the PDF from our MainActivity and renders it.

 

@@ -0,0 +1,52 @@
package com.tutorials.hp.gridviewpdf;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.ScrollBar;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;

import java.io.File;

public class PDF_Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdf);

        //PDFVIEW SHALL DISPLAY OUR PDFS
        PDFView pdfView= (PDFView) findViewById(R.id.pdfView);
        //SCROLLBAR TO ENABLE SCROLLING
        ScrollBar scrollBar = (ScrollBar) findViewById(R.id.scrollBar);
        pdfView.setScrollBar(scrollBar);
        //VERTICAL SCROLLING
        scrollBar.setHorizontal(false);
        //SACRIFICE MEMORY FOR QUALITY
        //pdfView.useBestQuality(true)

        //UNPACK OUR DATA FROM INTENT
        Intent i=this.getIntent();
        String path=i.getExtras().getString("PATH");

        //GET THE PDF FILE
        File file=new File(path);

            if(file.canRead())
            {
                //LOAD IT
                pdfView.fromFile(file).defaultPage(1).onLoad(new OnLoadCompleteListener() {
                    @Override
                    public void loadComplete(int nbPages) {
                        Toast.makeText(PDF_Activity.this, String.valueOf(nbPages), Toast.LENGTH_LONG).show();
                    }
                }).load();

            }


    }
}

 

 

 

STEP 6 : Our Layouts

  • Here's our PDF Activity layout. All XML Layouts and source code are in the link above so please download it and run.

 

@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.tutorials.hp.gridviewpdf.PDF_Activity">

    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_toLeftOf="@+id/scrollBar"/>

    <com.github.barteksc.pdfviewer.ScrollBar
        android:id="@+id/scrollBar"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

 

 

How To Download and Run

  • Download the project above.
  • You'll get a zipped file,extract it.
  • Open the Android Studio.
  • Now close, already open project
  • From the Menu bar click on File >New> Import Project
  • Now Choose a Destination Folder, from where you want to import project.
  • Choose an Android Project.
  • Now Click on “OK“.
  • Done, your importing Project.
  • Obviously you must have the PDFs you wanna display.

 

More

  • Visit our channel for more examples like these.
    Visist our Facebook Page

Oclemy,Cheers.

Leave a Reply

Your email address will not be published. Required fields are marked *

thirteen + 16 =

5 comments

Vinod Patil April 30, 2017 at 1:48 pm

Hello Sir…….
I frequently read your tutorials they are very easy and they help me a lot.
Can you please make simple tutorial using PdfViewPager library to display pdf from asset folder with zooming feature. The reason behind choosing this library is that size of resulting apk is very small as compared to library you have used in your tutorial…. Please make this tutorial …. Here is the link for library – https://github.com/voghDev/PdfViewPager …..Thanks in advance

Reply
Vinod Patil April 30, 2017 at 1:49 pm

Hello Sir…….
I frequently read your tutorials they are very easy and they help me a lot.
Can you please make simple tutorial using PdfViewPager library to display pdf from asset folder with zooming feature. The reason behind choosing this library is that size of resulting apk is very small as compared to library you have used in your tutorial…. Please make this tutorial …. Here is the link for library – https://github.com/voghDev/PdfViewPager …..Thanks in advance

Reply
Oclemy May 2, 2017 at 4:19 am

Great.

Reply
ash May 31, 2017 at 1:50 pm

i cant download the project even after sharing. Can u please provide me with the link to download. Thanks

Reply
Oclemy May 31, 2017 at 2:10 pm Reply

Leave a Comment

four × four =