Open pdf file android studio

Open a PDF in an Android App

PDF documents are the de facto standard for archiving, transferring, and presenting documents online. Android developers frequently need to display PDF documents within their applications, so in this article, we’ll look at different solutions for doing exactly that.

We’ll begin with the basic PDF support provided by the Android SDK library, move on to MuPDF, and finally look at rendering PDFs with the Android PdfViewer library.

Displaying PDFs Using the Android SDK

The Android SDK has had basic support for PDF files since API level 21 (Android 5.0). This API resides in a package, android.graphics.pdf , and it supports basic low-level operations, such as creating PDF files and rendering pages to bitmaps. The Android SDK doesn’t provide a UI for interacting with PDF documents, so you’ll need to write your own UI to handle user interaction if you wish to use it as a basis for a PDF viewer in your app.

The main API entry point is PdfRenderer , which provides an easy way to render single pages into bitmaps:

You can now set these rendered bitmaps into an ImageView or build your own UI that handles multi-page documents, scrolling, and zooming.

Now, we’ll introduce two libraries that support basic, ready-to-use UIs for displaying documents.

Displaying PDFs with MuPDF

One of the most widely known PDF libraries is MuPDF. It’s available either as a commercial solution or under an open source (AGPL) license.

MuPDF provides a small and fast viewer with a basic UI. Embedding it in your app is simple:

You can now open the MuPDF viewer activity by launching an intent with a document URI:

Using DocumentActivity is enough for most basic use cases. MuPDF ships with its entire source code, so you can build any required functionality on top of it.

ℹ️ Note: MuPDF also supports other document formats on top of PDF, such as XPS, CBZ, EPUB, and FictionBook 2.

Rendering PDFs with the Android PdfViewer Library

Android PdfViewer is a library for displaying PDF documents. It has basic support for page layouts, zooming, and touch gestures. It’s available under the Apache License, Version 2.0 and, as such, is free to use, even in commercial apps.

Integration is simple. Start with adding a library dependency to your build.gradle file:

Then add the main PDFView to the layout where you wish to view the PDFs:

Now you can load the document in your activity:

PSPDFKit for Android

The above solutions are free or open source libraries with viewer capabilities. However, the PDF spec is fairly complex, and it defines many more features on top of the basic document viewing capabilities. We at PSPDFKit offer a comprehensive PDF solution for Android and other platforms, along with first-class support included with every plan. PSPDFKit comes with a fully featured document viewer with a modern customizable user interface and a range of additional features such as:

Interactive forms with JavaScript support

Document editing (both programmatically and through the UI)

If you’re interested in our solution, visit the Android product page to learn more and download a free trial.

Conclusion

In this post, we outlined some of the available free PDF viewer libraries for Android that can help you render PDFs. However, if you want to add more advanced features to your PDF viewer — such as PDF annotation support, interactive PDF forms, and digital signatures — you should consider looking into commercial alternatives.

At PSPDFKit, we offer a commercial, feature-rich, and completely customizable Android PDF library that’s easy to integrate and comes with well-documented APIs to handle complex use cases. Try our PDF library using our free trial and check out our demos to see what’s possible.

Источник

Open pdf file android studio

Looking for new maintainer!

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 3.2.0-beta.1?

  • Merge PR #714 with optimized page load
  • Merge PR #776 with fix for max & min zoom level
  • Merge PR #722 with fix for showing right position when view size changed
  • Merge PR #703 with fix for too many threads
  • Merge PR #702 with fix for memory leak
  • Merge PR #689 with possibility to disable long click
  • Merge PR #628 with fix for hiding scroll handle
  • Merge PR #627 with fitEachPage option
  • Merge PR #638 and #406 with fixed NPE
  • Merge PR #780 with README fix
  • Update compile SDK and support library to 28
  • Update Gradle and Gradle Plugin
Читайте также:  Mirror android phone screen

Changes in 3.0 API

  • Replaced Contants.PRELOAD_COUNT with PRELOAD_OFFSET
  • Removed PDFView#fitToWidth() (variant without arguments)
  • Removed Configurator#invalidPageColor(int) method as invalid pages are not rendered
  • Removed page size parameters from OnRenderListener#onInitiallyRendered(int) method, as document may have different page sizes
  • Removed PDFView#setSwipeVertical() method

Add to build.gradle:

or if you want to use more stable version:

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

If you are using ProGuard, add following rule to proguard config file:

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.

Version 3.0.0 introduced support for links in PDF documents. By default, DefaultLinkHandler is used and clicking on link that references page in same document causes jump to destination page and clicking on link that targets some URI causes opening it in default application.

You can also create custom link handlers, just implement LinkHandler interface and set it using Configurator#linkHandler(LinkHandler) method. Take a look at DefaultLinkHandler source to implement custom behavior.

Pages fit policy

Since version 3.0.0, library supports fitting pages into the screen in 3 modes:

  • WIDTH — width of widest page is equal to screen width
  • HEIGHT — height of highest page is equal to screen height
  • BOTH — based on widest and highest pages, every page is scaled to be fully visible on screen

Apart from selected policy, every page is scaled to have size relative to other pages.

Fit policy can be set using Configurator#pageFitPolicy(FitPolicy) . Default policy is WIDTH.

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 FitPolicy.WIDTH policy or add following snippet when you want to fit desired page in document with different page sizes:

How can I scroll through single pages like a ViewPager?

You can use a combination of the following settings to get scroll and fling behaviour similar to a ViewPager:

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

Читайте также:  Flash any android device

Источник

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.

report this ad

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 .

Источник

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