Open In App

Load PDF From URL in Android with Kotlin

Last Updated : 17 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

PDF View is most of the applications to display the PDF files within the application to display the pdf within our own application rather than redirecting to another application. If we want to display multiple pdf files within our application we have to host these files and then access these files with the help of their URL. In this article, we will be building a simple application in which we will be loading PDF from URL using PDF View in Android using Kotlin. 

Note: If you are looking to load PDF from URL in PDF View in Android using Java. Check out the following article: How to Load PDF from URL in Android using Java

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin 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'

After adding this dependency sync your project to install the dependency. 

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

Add below two lines inside your manifest tag in the AndroidManifest.xml file.

XML




<!--internet permissions and network state permission-->
<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. Comments are added inside the code to understand the code in more detail.

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"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!--on below line we are creating our pdf view-->
    <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.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.github.barteksc.pdfviewer.PDFView
import java.io.BufferedInputStream
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import javax.net.ssl.HttpsURLConnection
 
class MainActivity : AppCompatActivity() {
     
    // on below line we are creating
    // a variable for our pdf view.
    lateinit var pdfView: PDFView
 
    // on below line we are creating a variable for our pdf view url.
 
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // on below line we are initializing
        // our pdf view with its id.
        pdfView = findViewById(R.id.idPDFView)
         
        // on below line we are calling our async
        // task to load our pdf file from url.
        // we are also passing our pdf view to
        // it along with pdf view url.
        RetrievePDFFromURL(pdfView).execute(pdfUrl)
    }
 
    // on below line we are creating a class for
    // our pdf view and passing our pdf view
    // to it as a parameter.
    class RetrievePDFFromURL(pdfView: PDFView) :
        AsyncTask<String, Void, InputStream>() {
         
        // on below line we are creating a variable for our pdf view.
        val mypdfView: PDFView = pdfView
 
        // on below line we are calling our do in background method.
        override fun doInBackground(vararg params: String?): InputStream? {
            // on below line we are creating a variable for our input stream.
            var inputStream: InputStream? = null
            try {
                // on below line we are creating an url
                // for our url which we are passing as a string.
                val url = URL(params.get(0))
                 
                // on below line we are creating our http url connection.
                val urlConnection: HttpURLConnection = url.openConnection() as HttpsURLConnection
                 
                // on below line we are checking if the response
                // is successful with the help of response code
                // 200 response code means response is successful
                if (urlConnection.responseCode == 200) {
                    // on below line we are initializing our input stream
                    // if the response is successful.
                    inputStream = BufferedInputStream(urlConnection.inputStream)
                }
            }
            // on below line we are adding catch block to handle exception
            catch (e: Exception) {
                // on below line we are simply printing
                // our exception and returning null
                e.printStackTrace()
                return null;
            }
            // on below line we are returning input stream.
            return inputStream;
        }
 
        // on below line we are calling on post execute
        // method to load the url in our pdf view.
        override fun onPostExecute(result: InputStream?) {
            // on below line we are loading url within our
            // pdf view on below line using input stream.
            mypdfView.fromStream(result).load()
 
        }
    }
}


Now run your application to see the output of it.

Output: 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads