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
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
5 min read
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
Chrome Custom Tabs in Android with Kotlin
As developers, we have the option of displaying web content to a user in their browser or via WebViews, but both have their own limitations: starting the browser is a large, non-customizable context transition for users, whereas WebViews don't support all aspects of the web platform. To address this
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
How to Play Video from URL in Android?
In this article, you will see how to play a video from a URL on Android. For showing the video in our Android application we will use the VideoView widget. The VideoView widget is capable of playing media files, and the formats supported by the VideoView are 3gp and MP4. By using VideoView you can p
3 min read
SearchView in Android with Kotlin
SearchView is a widget in android which provides a search interface with the help of which users can be able to make searches within the given list of data. In this search view, the user has to specify the search query. According to the search, query results will be populated within the listview. In
4 min read
Steps to Integrate of Local Host with Android Kotlin
In this article, we will build an Android app using Kotlin that connects to a local host server. You will learn how to configure your development environment, set up a local host server on your machine, and make network requests from the Android app. By the end of this article, youâll have a fully f
4 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