Open In App

How to Load PDF from URL in Android?

Improve
Improve
Like Article
Like
Save
Share
Report

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. 

implementation ‘com.github.barteksc:android-pdf-viewer:2.8.2’

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

Step 3: Add permission to the internet in your AndroidManifest.xml file

Add below two lines inside your AndroidManifest.xml file.

<!–Permission for internet–>

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

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

Step 4: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <!--PDF Viewer to display our PDF-->
    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/idPDFView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
 
</RelativeLayout>


Step 5: Working with the MainActivity.java file

Navigate to the app > java > your apps package name > MainActivity.java file. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. 

Java




import android.os.AsyncTask;
import android.os.Bundle;
 
import androidx.appcompat.app.AppCompatActivity;
 
import com.github.barteksc.pdfviewer.PDFView;
 
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 {
 
    // creating a variable
    // for PDF view.
    PDFView pdfView;
 
    // url of our PDF file.
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // initializing our pdf view.
        pdfView = findViewById(R.id.idPDFView);
        new RetrivePDFfromUrl().execute(pdfurl);
    }
 
    // create an async task class for loading pdf file from URL.
    class RetrievePDFfromUrl extends AsyncTask<String, Void, InputStream> {
        @Override
        protected InputStream doInBackground(String... strings) {
            // we are using inputstream
            // for getting out PDF.
            InputStream inputStream = null;
            try {
                URL url = new URL(strings[0]);
                // below is the step where we are
                // creating our connection.
                HttpURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
                if (urlConnection.getResponseCode() == 200) {
                    // response is success.
                    // we are getting input stream from url
                    // and storing it in our variable.
                    inputStream = new BufferedInputStream(urlConnection.getInputStream());
                }
                 
            } catch (IOException e) {
                // this is the method
                // to handle errors.
                e.printStackTrace();
                return null;
            }
            return inputStream;
        }
 
        @Override
        protected void onPostExecute(InputStream inputStream) {
            // after the execution of our async
            // task we are loading our pdf in our pdf view.
            pdfView.fromStream(inputStream).load();
        }
    }
}


Note: If you have updated to Android Studio to 4.0 or onwards then you may face the following error

Execution failed for task ':app:stripDebugDebugSymbols'.
NDK at ~/Library/Android/sdk/ndk-bundle did not have a source.properties file

Please refer to this to fix the error.

Output: 

Check out the project: https://github.com/ChaitanyaMunje/GFGImageSlider/tree/PDFViewer



Last Updated : 26 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads