Load PDF From URL in Android with Kotlin
Last Updated :
17 Aug, 2022
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: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"
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.
var pdfUrl = "https://unec.edu.az/application/uploads/2014/12/pdf-sample.pdf"
@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:
Similar Reads
Play Audio From URL in Android using Kotlin Many applications want to add different types of audio files to their android applications. These audio files are played using a media player within the android application. We can play audio files within the android application from different sources by playing audio from a web URL or by simply add
4 min read
Android Auto Image Slider with Kotlin Most e-commerce application uses auto image sliders to display ads and offers within their application. Auto Image Slider is used to display data in the form of slides. In this article, we will take a look at the Implementation of Auto Image Slider in our Android application using Kotlin. A sample v
5 min read
Retrofit with Kotlin Coroutine in Android Retrofit is a type-safe http client which is used to retrieve, update and delete the data from web services. Nowadays retrofit library is popular among the developers to use the API key. The Kotlin team defines coroutines as âlightweight threadsâ. They are sort of tasks that the actual threads can e
3 min read
Convert WebView to PDF in Android with Kotlin Sometimes the user has to save some article that is being displayed on the web browser. So for saving that article or a blog users can simply save that specific web page in the form of a PDF on their device. We can implement this feature to save the pdf format of the web page which is being displaye
5 min read
Kotlin Flow in Android with Example Kotlin Flow is a tool that helps developers work with data that changes over time like search results, live updates, or user input. Itâs part of Kotlinâs coroutines, which are used for writing code that doesnât block the app while waiting for something to finish, like a network call or a file to loa
8 min read
Android - Update Data in API using Volley with Kotlin Android applications use APIs to get the data from servers in android applications. With the help of APIs, we can add, read, update and delete the data from our database using APIs. We can use Volley and Retrofit for consuming data from APIs within the android application. In this article, we will t
5 min read