Android App DevelopmentEducationProgramming

How To Load PDF From URL in Android

How To Load PDF 
From URL in Android
How To Load PDF
From URL in Android

Hey Guys, We are back with Another Android Tutorial. Today Let’s See about how to load a PDF on Android in Android Studio. How to implement PDF Viewer in Android Studio.

There are many methods to load and show pdf in Android Studio. Some of them are:

  1. Using Webview
  2. Using Barteksc Android PdfViewer Library
  3. Using Google Docs PDF Viewer inside a Webview

If you are Developing a basic PDF Viewer you can use a Webview or Google Docs PDF Viewer inside a Webview. But If you are Developing a Professional PDF Viewer App like E-Book Apps you have to use a PDF Viewer Library. There are many Open-Source and also Paid Libraries to Use for developing PDF Viewer App.

But Barteksc Android PdfViewer Library is One of the Libraries to develop a PDF Viewer App. For the last three years, I’m using this library without any problem. 

Why I Preferred this Barteksc PDF Viewer?

I preferred it because it has five Options to load a PDF in Android Studio. You can load PDF from URL, FILE, BYTES, STREAM, ASSETS. It has a lot of Customisation Options like setting Width and Height, Enabling and Disabling Zoom, Horizontal Page Swiping, Page Change Event Listener, Scroll Event Listener, Night Mode Option, Error Handling, Dynamic Spacing between pages, Displaying Page Numbers, Double Tap actions, Link Handler, and more features. 

Now I’ll show you how to develop a PDF Viewer using Barteksc Android PdfViewer Using a PDF URL.

Implementation of PDF Viewer

Here We Use Barteksc Android PdfViewer Library

Add this dependency in your app-level build.gradle

dependencies {

    
    implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'

}

Add Network Permissions as they are required to load PDF from URL(Internet).

    <!–Internet Permission Required to load PDF from URL->


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

Now Let’s go to activity_main.xml and design this PDF Viewer.

activity_main.xml
<?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"
    tools:context=".MainActivity">


    <!-- pdf viewer to load and display PDF -->
    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="8dp"/>

    <com.google.android.material.progressindicator.CircularProgressIndicator
        android:id="@+id/progress_circular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:indeterminate="true"/>

</RelativeLayout>

Now Let’s See MainActivity.java Code.

MainActivity.java

package com.example.pdfviewer;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnErrorListener;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.google.android.material.progressindicator.CircularProgressIndicator;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    String pdfurl="https://bigbosstelugu.org/wp-content/uploads/2021/05/dummy-text.pdf";
    PDFView pdfView;
    CircularProgressIndicator progress_circular;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pdfView = findViewById(R.id.pdfView);
        progress_circular = findViewById(R.id.progress_circular);
        progress_circular.setVisibility(View.VISIBLE);

        new loadpdffromUrl().execute(pdfurl);

    }


    //create an async task to load pdf from URL.
    class loadpdffromUrl extends AsyncTask<String, Void, InputStream> implements OnLoadCompleteListener, OnErrorListener {
        @Override
        protected InputStream doInBackground(String... strings) {
            //We use InputStream to get PDF.
            InputStream inputStream = null;
            try {
                URL url = new URL(strings[0]);
                HttpURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
                if (urlConnection.getResponseCode() == 200) {
                    // if response is success. we are getting input stream from url and storing it in our variable.
                    inputStream = new BufferedInputStream(urlConnection.getInputStream());
                }

            } catch (IOException e) {
                //method to handle errors.
                e.printStackTrace();
                return null;
            }
            return inputStream;
        }

        @Override
        protected void onPostExecute(InputStream inputStream) {
            //after the executing async task we load pdf in to pdfview.
            pdfView.fromStream(inputStream).onLoad(this).onError(this).load();
        }

        @Override
        public void loadComplete(int nbPages) {
            progress_circular.setVisibility(View.GONE);
        }

        @Override
        public void onError(Throwable t) {
            progress_circular.setVisibility(View.GONE);
            Toast.makeText(MainActivity.this,"Error:" +t.getMessage(),Toast.LENGTH_SHORT).show();
        }
    }
    
}

Note:The link I Used is a dummy PDF

Finally, We Achieved PDF Loading from URL in Android. That’s it, Guys. If you have any Doubts or If you encounter any errors while implementing PDF Viewer just comment below. I’ll respond to your comment and try to solve your issues.

Check our Other Android App Tutorials

Leave a Reply

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

Back to top button