Android studio pdf viewer

Android studio pdf viewer

This is repo with version 1.x of AndroidPdfViewer. Version 1.x uses different engine for drawing document on canvas, so if you don’t like 2.x version, try this. This version is still updated and supported.

Library for displaying PDF documents on Android, with animations , gestures , zoom and double tap support. It is based on PdfiumAndroid for decoding PDF files. Works on API 11 and higher. Licensed under Apache License 2.0.

What’s new in 1.6.0?

  • Add change from AndroidPdfViewer 2.4.0 which replaces RenderingAsyncTask with Handler to simplify code and work with testing frameworks

Add to build.gradle:

Library is available in jcenter repository, probably it’ll be in Maven Central soon.

Include PDFView in your layout

Load a PDF file

All available options with default values:

  • enableSwipe is optional, it allows you to block changing pages using swipe
  • pages is optional, it allows you to filter and order the pages of the PDF as you need
  • onDraw is also optional, and allows you to draw something on a provided canvas, above the current page

Use ScrollBar class to place scrollbar view near PDFView

in layout XML (it’s important that the parent view is RelativeLayout):

in activity or fragment

scrollBar.setHorizontal(true); or app:sb_horizontal=»true» may be used to set ScrollBar in horizontal mode.

ScrollBarPageIndicator is added to scrollbar automatically and is shown while dragging scrollbar handler, displaying number of page on current position. Its position is automatically calculated based on ScrollBar‘s position.

Version 1.5.0 introduced document sources, which are just providers for PDF documents. Every provider implements DocumentSource interface. Predefined providers are available in com.github.barteksc.pdfviewer.source package and can be used as samples for creating custom ones.

Predefined providers can be used with shorthand methods:

Custom providers may be used with pdfView.fromSource(DocumentSource) method.

By default, generated bitmaps are compressed with RGB_565 format to reduce memory consumption. Rendering with ARGB_8888 can be forced by using pdfView.useBestQuality(true) method.

Double tap zooming

There are three zoom levels: min (default 1), mid (default 1.75) and max (default 3). On first double tap, view is zoomed to mid level, on second to max level, and on third returns to min level. If you are between mid and max levels, double tapping causes zooming to max and so on.

Zoom levels can be changed using following methods:

Why resulting apk is so big?

Android PdfViewer depends on PdfiumAndroid, which is set of native libraries (almost 16 MB) for many architectures. Apk must contain all this libraries to run on every device available on market. Fortunately, Google Play allows us to upload multiple apks, e.g. one per every architecture. There is good article on automatically splitting your application into multiple apks, available here. Most important section is Improving multiple APKs creation and versionCode handling with APK Splits, but whole article is worth reading. You only need to do this in your application, no need for forking PdfiumAndroid or so.

If you have any suggestions on making this lib better, write me, create issue or write some code and send pull request.

Created with the help of android-pdfview by Joan Zapata

Источник

Android studio pdf viewer

AndroidPdfViewer 1.x is available on AndroidPdfViewerV1 repo, where can be developed independently. Version 1.x uses different engine for drawing document on canvas, so if you don’t like 2.x version, try 1.x.

Library for displaying PDF documents on Android, with animations , gestures , zoom and double tap support. It is based on PdfiumAndroid for decoding PDF files. Works on API 11 (Android 3.0) and higher. Licensed under Apache License 2.0.

What’s new in 2.8.0?

  • Add handling of invalid pages, inspired by pull request #433. Exception on page opening crashed application until now, currently OnPageErrorListener set with Configurator#onPageError() is called. Invalid page color ( Color class) can be set using Configurator#invalidPageColor()
  • Implement canScrollVertically() and canScrollHorizontally() methods to work e.g. with SwipeRefreshLayout
  • Fix bug when Configurator#load() method was called before view has been measured, which resulted in empty canvas

2.8.1 fixes bug with rendering PDFView in Android Studio Layout Editor

2.8.2 fixes not loaded pages when using animated PDFView#jumpTo()

Читайте также:  Как включить инженерное меню андроид

Changes in 2.0 API

  • Configurator#defaultPage(int) and PDFView#jumpTo(int) now require page index (i.e. starting from 0)
  • OnPageChangeListener#onPageChanged(int, int) is called with page index (i.e. starting from 0)
  • removed scrollbar
  • added scroll handle as a replacement for scrollbar, use with Configurator#scrollHandle()
  • added OnPageScrollListener listener due to continuous scroll, register with Configurator#onPageScroll()
  • default scroll direction is vertical, so Configurator#swipeVertical() was changed to Configurator#swipeHorizontal()
  • removed minimap and mask configuration

Add to build.gradle:

Library is available in jcenter repository, probably it’ll be in Maven Central soon.

Include PDFView in your layout

Load a PDF file

All available options with default values:

  • pages is optional, it allows you to filter and order the pages of the PDF as you need

Scroll handle is replacement for ScrollBar from 1.x branch.

From version 2.1.0 putting PDFView in RelativeLayout to use ScrollHandle is not required, you can use any layout.

To use scroll handle just register it using method Configurator#scrollHandle() . This method accepts implementations of ScrollHandle interface.

There is default implementation shipped with AndroidPdfViewer, and you can use it with .scrollHandle(new DefaultScrollHandle(this)) . DefaultScrollHandle is placed on the right (when scrolling vertically) or on the bottom (when scrolling horizontally). By using constructor with second argument ( new DefaultScrollHandle(this, true) ), handle can be placed left or top.

You can also create custom scroll handles, just implement ScrollHandle interface. All methods are documented as Javadoc comments on interface source.

Version 2.3.0 introduced document sources, which are just providers for PDF documents. Every provider implements DocumentSource interface. Predefined providers are available in com.github.barteksc.pdfviewer.source package and can be used as samples for creating custom ones.

Predefined providers can be used with shorthand methods:

Custom providers may be used with pdfView.fromSource(DocumentSource) method.

By default, generated bitmaps are compressed with RGB_565 format to reduce memory consumption. Rendering with ARGB_8888 can be forced by using pdfView.useBestQuality(true) method.

Double tap zooming

There are three zoom levels: min (default 1), mid (default 1.75) and max (default 3). On first double tap, view is zoomed to mid level, on second to max level, and on third returns to min level. If you are between mid and max levels, double tapping causes zooming to max and so on.

Zoom levels can be changed using following methods:

Why resulting apk is so big?

Android PdfViewer depends on PdfiumAndroid, which is set of native libraries (almost 16 MB) for many architectures. Apk must contain all this libraries to run on every device available on market. Fortunately, Google Play allows us to upload multiple apks, e.g. one per every architecture. There is good article on automatically splitting your application into multiple apks, available here. Most important section is Improving multiple APKs creation and versionCode handling with APK Splits, but whole article is worth reading. You only need to do this in your application, no need for forking PdfiumAndroid or so.

Why I cannot open PDF from URL?

Downloading files is long running process which must be aware of Activity lifecycle, must support some configuration, data cleanup and caching, so creating such module will probably end up as new library.

How can I show last opened page after configuration change?

You have to store current page number and then set it with pdfView.defaultPage(page) , refer to sample app

How can I fit document to screen width (eg. on orientation change)?

Use this code snippet:

If you have any suggestions on making this lib better, write me, create issue or write some code and send pull request.

Created with the help of android-pdfview by Joan Zapata

About

Android view for displaying PDFs rendered with PdfiumAndroid

Источник

Android Simple PDFViewer Examples

In this tutorial we will look at how to implement simple PDF Readers using ListView, GridView and recyclerview. We scan the device for a list of all the PDF documents in the device then list them in the adapterview. When the user clicks a single PDF Document, we render it in a new activity.

Example 1: Android GridView PDF View – List,Render,Page,Zoom

This is an android view pdf document programmitically tutorial and example.

We use pdf view android library called barteksc/AndroidPdfViewer, an open source pdf viewer library that is avaialble for free in android studio.

We create our project using android studio and we have the source available for download at the end of the tutorial.

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 and display in 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 and view it 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.

You may use the later versions of this library.

Our GridView will contain custom CardViews so we need to add the CardView dependency as well.

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.

android.permission.READ_EXTERNAL_STORAGE allows us read files from the device’s external storage. Please make sure you add this as failure to do so will result in you being unable to read the external storage at runtime.

Moreover we will register two activities: one our main activity and the other the PDFViewer Activity.

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.

This is a data object that represents a single PDF document. The PDF will have the name and path as it’s properties.

We then generate their getters and setters.

STEP 4 : Our CustomAdapter class

Because we are working a custom gridview as our adapterview.It therefore needs its adapter.
Therefore We will derive from baseadapter, an abstract class from which other adapters like ArrayAdapter do derive.

This class shall inflate our model layout into CardView view items of our gridview. So basically this gridview will contain cardviews with PDF documents.

This adapter class is also responsible for adapting our dataset into those respective views. A single cardview is comprising of image and text.

First a Context object as well as an arraylist of PDF Documents is passed to us via the constructor:

We also open activity,pdf activity when an item is clicked. We will create a method to do that for us:

As you can see we are using an intent, first instantiating, passing in the context as well as the target class.

Then using the putExtra() we pass the PATH and start the activity to open it.

STEP 5 : Our MainActivity

This is our main activity. It will be extending the AppCompatActivity .

This activity is responsible for listing our pdf documents in a list of gridview. The user can the scroll through those pdf documents.

We will start by referencing the gridview by its id:

We are showing a gridview with cardviews with images and text. The images are the pdf icons while the textviews will show the pdf document name.

When the user clicks the pdf document, we render the document in a new activity.

We will also be retrieving our pdf documents from the device and hold them in an arraylist here.

We will have a method called getPDFs() . This method will read all PDF files from the Download’s directory in our external storage. In that way we can get the PDF names and their paths and assign them to a PDFDoc instance. Then return an arraylist of PDFDocs.

To do this first we get the downlaod’s folder:

Then ensure it actually exists:

Then read all the files inside it into a file array:

We will use the endsWith() method to filter out PDF documents:

STEP 5 : Our PDF Activity

This is the activity that actually renders the pdf document. The PDFs will be loaded from the device external storage and this activity will display them for viewing.

The path of the PDF document will be passed from the main activity via intent.

Then we load the pdf document via the path.

  • This activity renders our PDF document.
  • It receives the path to the PDF from our MainActivity and renders it.
Читайте также:  Европейские роскошные автомобили андроид

As an Activity this class will also derive from AppCompatActivity:

We will reference the PDFView from our layout:

Beware that newer versions of PDF don’t require you to specify the ScrollBar as we did here.

We will unpack or retrieve data that was sent via Intent from our MainActivity then use the getExtras() to get the path that was passed.

We will create a file from that path:

Then check if that file can be read:

And load our PDF file into the PDFView:

STEP 6 : Our Layouts

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

We have a RelativeLayout as our root layout.

We then specify the PDFView element in our XML document. This will be responsible for rendering or viewing our pdf document.

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.

Example 2: Android PDF Reader with ListView.

This is a tutorial about implementing a basic PDF Reader using ListView and third party PDF Rendering library.

We will list PDF items from external storage into a ListView. When you click a PDF item, a new PDF Reader activity is opened and you can read the PDF with advanced capabilities like zooming, scrolling, swiping and pagination.

Gradle Scripts

Given we are using a third party PDF Renderer, we need to add dependencies in the app level build.gradle .

1. Build.gadle

  • Go over and dependencies. We are using android-pdf-viewer library.

LAYOUTS

We’ll work with 4 layouts:

1. activity_main.xml

  • Our MainActivity layout.
  • Root layout is CordinatorLayout .
  • This layout defines:
    1. appbar
    2. Toolbar
    3. FloatingActionButton.
  • We also include our content_main.xml here.

2. content_main.xml

  • Still part of our MainActivity layout.
  • Root layout is RelativeLayout
  • It gets included inside the activity_main.xml .
  • Will hold our ListView onto which our PDFs will be displayed.

3. model.xml

  • Will model our custom rows for our listview.
  • The listview should contain images and text. The images will be an icon to indicate a PDF. Thus the user knows the list contains PDFs.
  • At the root tag is a android.support.v7.widget.CardView .

4. activity_pdf.xml

  • Now this layout will be our PDF render layout.
  • It’s our PDF Viewer layout.

JAVA CLASSES

Let’s now look at our 4 Java classes.

1. PDFDoc.java

This is our data object. Our POJO class.

POJO stands for Plain Old Java Object. We use this class to represent our data entity. In this case a PDF document.

This class will hold the PDF’s:

2. CustomAdapter.java

This is our adapter class. It will derive from android.widget.BaseAdapter . This is what makes the class an adapter.

Then we’ll override a couple of methods given that BaseAdapter is an abstract class.

An adapter class basically adapts data to custom views. Like in our case we have a ListView with images and text. well that’s a custom listview. So we need the adapter class to help in binding the data to this listview.

We also handle OnClick event for our ListView here. Hence opening the PDF Activity to view/read the PDF document.

3. PDFActivity.java

This is class is an activity because we derive from android.support.v7.app.AppCompatActivity , which is a support version of android.app.activity .

This class is our PDF Renderer/PDF Viewer. Users will read PDF documents here.

The first activity( MainActivity ) will be responsible for listing pdf documents. This activity, however, will be responsible or viewing them.

4. MainActivity.java

This is our launcher activity. This means when the app is run it is this activity that gets executed by default.

This class derives from android.support.v7.app.AppCompatActivity .

We proceed and override the OnCreate(0 method.

We will read our android external storage to obtain PDF documents from downloads directory here.

We will then list these pdf documents in the mainactivity.

AndroidManifest.xml

Add this permission in your androidmanifest:

Download

Download code below.

Download the source code here.

Oclemy

Thanks for stopping by. My name is Oclemy(Clement Ochieng) and we have selected you as a recipient of a GIFT you may like ! Together with Skillshare we are offering you PROJECTS and 1000s of PREMIUM COURSES at Skillshare for FREE for 1 MONTH. To be eligible all you need is by sign up right now using my profile .

Источник

Оцените статью