Android view pdf from url

How to Load PDF from URL in Android?

Most of the apps require to include support to display PDF files in their app. So if we have to use multiple PDF files in our app it is practically not possible to add each PDF file inside our app because this approach may lead to an increase in the size of the app and no user would like to download the app with such a huge size. So to tackle this issue related to the size we will load PDF files from the server directly inside our app without actually saving that files inside our app. Loading PDF files from the server will help us to manage the increase in the size of our app. So in this article, we will take a look at How to Load PDF files from URLs inside our Android App.

Implementation of PDFView

For adding this PDF View we are using a library that will help us to load PDF from URL. Note that we are going to implement this project using the Java language.

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Add dependency to build.gradle(Module:app)

Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.

Now sync option will appear at the top right corner click on the sync now option.

Источник

Android view pdf from url

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

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
Читайте также:  Hollywood story взлом андроид

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

Источник

Android view pdf from url

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?

Читайте также:  Idoing как обновить андроид

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

Источник

How to open a PDF file in Android programmatically?

Opening and viewing documents in Android applications are very interesting and a must to have in every application. You can open any application present on your mobile and you will find that every application contains documents in some or the other way. And among these documents, the most popular and widely used document format is the PDF format.

PDF or Portable Document Format is a file format that has captured all the elements of a printed document. This is the most used document format. For example, in the Paytm application, you get your monthly expenses in the form of PDF document. So, if you also want to display some kind of document in your application, then you can open this PDF format document.

So, welcome to MindOrks and in this tutorial, we will learn how to open a PDF file in Android programmatically. We will cover the below topics in this tutorial:

  1. Project setup
  2. Ways of opening PDF in Android
  3. Making UI and adding Activities for the project
  4. Opening a PDF file using WebView
  5. Opening a PDF file using AndoirdPdfviewer library
  6. Project source code and What next?

Project setup

In this tutorial, we will make a project and try various ways of opening PDF file, Here we are going to set up our project:

  • Start a new Android Studio Project
  • Select Empty Activity and Next
  • Name: Open-PDF-File-Android-Example
  • Package name: com.mindorks.example.openpdffile
  • Language: Kotlin
  • Finish
  • Your starting project is ready now
  • Under your root directory, create a package named utils .(right-click on root directory > new > package)
  • In the utils package, create one object classes: FileUtils .(right-click on utils > new > Kotlin file/class > Object class)

If you are preparing for your next Android Interview, Join our Android Professional Course to learn the latest in Android and land job at top tech companies.

Ways of opening PDF in Android

If you want to display PDF in your Android application, there are various ways of doing it. Some of the ways of opening the PDF can be:

  1. From Assets: Let’s take an example, if you want to display some icons in your application then you will put all your icons in the drawable folder and then you will use those icons in your application. Same is with the case of PDF files also. If you have some PDF file that is constant and you want to display it in your application then you can put that PDF file in the assets folder and use that PDF in your app. One example can be the Terms and Conditions file. The terms and conditions files are rarely changed. So, you can put that document in the assets folder and use it.
  2. From Device: The other way of opening a PDF is to open it from the device itself. Here, you can open the PDF files present in your mobile device. This is the most used approach for opening the PDF in an Android device.
  3. From the Internet: Here, you can open PDF files from the internet. All you need to do is just use the URL of the PDF file and after downloading the PDF file, you can open the PDF file in your mobile application.

So, we will look upon all these ways of viewing the PDF in your Android Application. Let’s make the UI of the project.

Making UI for the project

In our example, we are going to cover four different cases:

  1. Opening a PDF file using WebView
  2. Opening a PDF file from assets using AndroidPdfViewer library
  3. Opening a PDF file form storage using AndroidPdfViewer library
  4. Opening a PDF file from the internet using AndroidPdfViewer library

So, for the first point, we will use WebViewActivity and for 2nd, 3rd, and 4th point, we will be using PdfViewActivtiy .

Create two activities named WebViewActivtiy and PdfViewActivity .(right-click on root directory > new > Activity> Empty Activity)

Now, for the above four actions, create four buttons and assign the task to open activity by those four buttons.

The code for the activity_main.xml file is:

In the MainActivity.kt file, we call the desired activity with the corresponding buttons:

We are done with the UI part. Let’s learn how to view PDF from WebView.

Opening a PDF file in Android using WebView

The very first and the easiest way of displaying the PDF file is to display it in the WebView. All you need to do is just put WebView in your layout and load the desired URL by using the webView.loadUrl() function.

Читайте также:  График выхода андроид 12 для самсунг

So, add a WebView in the activity_web_view.xml file:

Now, open the FileUtils class of the utils package that we created at the starting of this blog and add a function named getPdfUrl that will return the URL of the PDF which we are going to view in the WebView. Here, I am using the syllabus of MindOrks Professional Course. Add below method in FileUtils class:

Now, all we need to do is open the above URL in the WebView by calling the webView.loadUrl method. Following is the code of WebViewActivity.kt file:

The last thing that you need to do is adding INTERNET permission to your application. So, add the below line in your AndroidManifest.xml file:

Now, run the application on your mobile phone and the PDF will be displayed on the screen.

Note: The opening of PDF in WebView depends on your internet speed, so wait for sometimes if your internet is slow.

Opening a PDF file in Android using AndroidPdfViewer library

There are various libraries that can be used to display PDF files in our application. In our tutorial, we will learn how to open a PDF file from Assets, Phone Storage, and from the Internet by using the AndroidPdfViewer library.

Also, we will be using PRDownloader library by MindOrks to download files from the Internet and open it by AndoridPdfViewer .

Adding dependencies and permissions

Open the app level build.gradle and add the below dependencies of AndroidPdfViewer and PRDownloader:

Since we will be reading pdf from INTERNET. Open the AndoidManifest.xml file and add the below:

The AndroiPdfViewer provides a PDFView to display PDF files in it. So, write the below code in actvity_pdf_view.xml :

We can use the AndroidPdfViewer to open the PDF from:

  • Assets folder
  • Phone storage
  • Internet

So, we need to write the code to connect the button click of MainActivity with the above events. Create a function named checkPdfAction() and write the below code:

Call the above method from the onCreate() :

Let’s learn how to display PDF from assets, storage, and internet.

Assets Folder

Firstly, we will look upon how to view PDF, stored in the Assets Folder.

Creating an assets folder

Create an assets folder by right-clicking on main > New Folder > Assets Folder and paste the PDF document into it.

PDF file name: MindOrks_Android_Online_Professional_Course-Syllabus.pdf

Create getPdfNameFromAssets() method

Create a method named getPdfNameFromAssets in the FileUtils class. This method will return the name of the PDF file present in the assets folder:

Now, in the PdfViewActivity.kt file, create a method showPdfFromAssets which will take the file name in string format and will use the fromAssets() method of AndroidPdfViewer library to display PDF:

Call the above method from the checkPdfAction and pass the file name by calling the getPdfnameFromAssets method of FileUtils class:

Finally, run the application on your mobile device and see the output.

From Phone Storage

Now, we will look upon how to open PDF files from the Phone’s storage. So, we have to launch an intent to find the file having PDF format and the selected file will be displayed in the PDFView by calling the fromUri method.

Create a function selectPdfFromStorage() in the PdfViewActivity.kt file and add the below code:

Once, the user selects a PDF, the onActivityResult will be called:

Now, create a method named showPdfFromUri that will take a Uri and display the PDF:

Now, you can check the output by running your application on your mobile device and select the desired PDF.

PDF from Internet

Lastly, our aim is to view the PDF files from the Internet. We will first download the PDF by using the PRDownloader and then use this file to display the PDF on your PdfViewActiviy by using the same process as used for Assets and Storage but here you have to use fromFile() to add display the PDF.

So, we need to download the file first by using the PRDownloader library. Initialise it in the onCreate() method of PdfViewActivity :

Now, you need to download the file from the INTERNET by using the download() method of PRDownloader. So, create a function named downloadPdfFromInternet() in the PdfViewActivity. This function will take the URL, directory path, and file name of the file to be downloaded.

The onDownloadComplete method will be called when the file is downloaded. So, call the showPdfFromFile method and pass the downloaded file to the method:

Finally, call the downloadPdfFromInternet method from the checkPdfAction method but we need the URL, directory name and file name of the file to be downloaded. We can get the URL by calling the getPdfUrl method of FileUtils class. Now, make a function getRootDirPath method in the FileUtils class that will return the root directory:

Now, call the downloadPdfFromInternet method from checkPdfAction method of PdfViewActivity :

Finally, run the application and try to verify all the three options i.e. assets, storage and internet options to view PDF in Android Application. Try to replace the PDF link used in the above example with your own PDF URL.

There are many other methods present in the AndroidPdfViewer library. You can explore all the methods from here.

Project source code and What next?

Do share this tutorial with your fellow developers to spread the knowledge. You can read more blogs on Android on our blogging website .

Источник

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