How To Open PDF File In Android Programmatically [Easy Hacks]

Loading...

In our day to day office work, homework, study, the use of pdf files is very common. A PDF file is one of the most common file types we encounter every day. We can easily transform a document file into PDF straight from MS word or using any document to pdf application available online. However, what about opening a PDF File programmatically? Well, that’s the topic of our discussion today. In this article, we are going to show you a bunch of ways to open PDF files in your Android as a programmer do. Are you interested? If yes, keep reading this guide on how to open pdf file in Android programmatically.

 

What is PDF File?

 

PDF stands to indicate Portable Document Format. Being one of the most common file types out there, it has all the traits and elements of a printed document. Many educational websites and software give out their materials and output in PDF format. Unlike Document, it is not easily editable directly from any PDF reader. You might edit them on the pro version of Acrobat DC reader or other paid software like that.

 

 

How To Open PDF File In Android Programmatically

 

 

However, PDF files have become part and parcel in all the areas of digital printing and education as well. If you want to get a book online, many think that you are looking for a PDF version of the printed book. So, the PDF format is well known by almost all kinds of technology users.

Loading...

 

One of the reasons this format is so popular is that you can open the PDF files from your smartphone and computer very easily using any PDF reader.

 

Project Setup

 

We will start this guide by making a project to show you various ways to open a PDF file programmatically. Let’s go ahead:

 

  • Initiate a new project on your Android Studio.
  • Choose Empty Activity and then go for Next.
  • Give a name such as Open-PDF-File-On-Android-Demo.
  • Give a package name of your choice such as com.fb.example.openpdffile
  • Use Kotlin as the language.
  • Click on Finish.
  • Now, your starting project is completely ready to work.
  • What you need to do now is to create a package name: utils under the root directory. To create a new package, right-click on the root directory and then proceed to the new package.
  • Now you have to create an object class: FileUtils in the utils package. Here’s how to do it: right-click on utils, choose new, select Kotlin file/class > Object class.

 

Different Ways of Opening PDF in Android

 

 

How To Open PDF File In Android Programmatically

 

 

 

There are a bunch of ways to open PDF files in an Android application. Let’s see some of the ways:

 

Opening PDF files from Assets:

Let’s start by having a look at how to open a pdf file from assets in Android programmatically. Suppose, you want to display some icons in your app. What would you do? You put the icons in the drawable folder and then use those in your app, right?

 

The same applies to PDF files. For the constant PDF files that you want to display in the application, you have to put the files in the assets folder so that you can use those PDFs in the application.

 

You can do it especially for Terms and Conditions file. As this type of file does not change regularly, you can put this document in the Assets folder and use it when you need it.

 

 

Opening PDF files from Device: You can also open a PDF from the device itself. If you have got the PDF in your mobile device, you are all set to open that file. This is the most common approach that most of us use while we open PDF files from our Android device.

 

Opening PDF files from the Internet: It is also possible to open PDF files from the internet. If you want to open a PDF file from your application, you have to browse the URL of the PDF first. Download the PDF file and now the file is ready to be opened with your mobile app.

 

We will be discussing the steps of opening the PDF files ahead. Before going to the discussion, let’s make the UI of the project:

 

Making UI For The Project

 

In our coming discussion, we will be covering the following 4 cases:

 

  1. Using WebView to open a PDF file.
  2. Using the AndroidPdfViewer library to open a PDF file from assets.
  3. Using the AndroidPdfViewer library to open a PDF file from storage.
  4. Using the AndroidPdfViewer library to open a PDF from the internet.

 

 

We are going to use “WebViewActivity” for the first point. And for the rest of the points, i.e., second, third, and fourth, we will take help from  “PdfViewActivtiy”.

First of all, you have to create two activities by right-clicking on the root directory. Go to new>activity>empty Activity. Name the activities as “WebViewActivtiy” and PdfViewActivity”.

Now, to perform the four actions mentioned above, you are supposed to create four buttons. And then you have to assign the task to open activity using those four buttons.

Here’s the code you need for the activity_main.xml file:

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/secondary_color"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_margin="24dp"
        android:gravity="center"
        android:text="@string/opening_pdf"
        android:textColor="@color/color_black"
        android:textSize="32sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/buttonWebView"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_margin="24dp"
        android:background="@color/primary_color"
        android:text="@string/open_in_webview"
        android:textAllCaps="false"
        android:textColor="@color/color_white"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <Button
        android:id="@+id/buttonAssets"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_margin="24dp"
        android:background="@color/primary_color"
        android:text="@string/open_from_assets"
        android:textAllCaps="false"
        android:textColor="@color/color_white"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonWebView" />

    <Button
        android:id="@+id/buttonStorage"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_margin="24dp"
        android:background="@color/primary_color"
        android:text="@string/open_from_storage"
        android:textAllCaps="false"
        android:textColor="@color/color_white"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonAssets" />

    <Button
        android:id="@+id/buttonInternet"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_margin="24dp"
        android:background="@color/primary_color"
        android:text="@string/open_from_internet"
        android:textAllCaps="false"
        android:textColor="@color/color_white"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonStorage" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

Now, in the MainActivity.kt file, we will need corresponding buttons to call the desired activity:

 

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

setUpOnClickListener()
}

private fun setUpOnClickListener() {
buttonWebView.setOnClickListener {
val intent = Intent(this, WebViewActivity::class.java)
startActivity(intent)
}
buttonAssets.setOnClickListener {
val intent = Intent(this, PdfViewActivity::class.java)
intent.putExtra("ViewType", "assets")
startActivity(intent)
}
buttonStorage.setOnClickListener {
val intent = Intent(this, PdfViewActivity::class.java)
intent.putExtra("ViewType", "storage")
startActivity(intent)
}
buttonInternet.setOnClickListener {
val intent = Intent(this, PdfViewActivity::class.java)
intent.putExtra("ViewType", "internet")
startActivity(intent)
}
}

}


That’s all for the UI part. We can now move to the ways of opening a PDF file in Android programmatically. Let’s start with How to open PDF in Webview in Android.

 

 

Using Webview To Open A PDF File

 

 

How To Open PDF File In Android Programmatically

 

 

Using WebView to open PDF files is probably the easiest and simplest way you can ever try. It does not take more than putting the WebView in your layout and load the desired URL. To load the URL, you have to use “webView.loadUrl()” function.

So, in the “activity_web_view.xml” file add a WebView:

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".WebViewActivity">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout

 

 

From the utils package, open the FileUtils” class that is created at the beginning of this guide. To view the PDF in the WebView, you have to put the PDF URL function getPdfUrl. We are here using the link of an Android Professional course offered by MindOrks. Add the following method in the FileUtils class:

Call the Webview.loadUrl method now to open the above URL in the WebView. Here goes the WebViewActivity.kt code file:

 

fun getPdfUrl(): String {
    return "https://mindorks.s3.ap-south-1.amazonaws.com/courses/MindOrks_Android_Online_Professional_Course-Syllabus.pdf"
}

 

One last thing that you should do now is to add INTERNET permission to your app. For that purpose, you have to include the following line in AndroidManifest.xml file:

 

class WebViewActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web_view)
        webView.webViewClient = WebViewClient()
        webView.settings.setSupportZoom(true)
        webView.settings.javaScriptEnabled = true
        val url = FileUtils.getPdfUrl()
        webView.loadUrl("https://docs.google.com/gview?embedded=true&url=$url")
    }
}

 

 

Now that you are all done, you are ready to run the application on your Android device. You can see the PDF being displayed on the screen.

However, keep in mind that it is your internet speed that plays a great role in the opening of PDF in WebView. You might need to wait for a minute or two in case the data connection is too slow.

 

Using AndroidPdfViewer library to open a PDF file

 

 

How To Open PDF File In Android Programmatically

 

 

There are many libraries available to display your PDFs. In this guide, we will be focusing on the way of opening PDFs from Assets, Device storage, and from the web. We will use AndroidPdfViewer to get our work done.

 

Note that, you can also use the PRDownloader library to download your desired PDF out of online and then open that PDF file from AndroidPdfViewer.

 

Add permissions and dependencies

 

 

How To Open PDF File In Android Programmatically

 

 

Start the operation by opening the app level build.gradle. Add the following dependencies of PDDownloader and AndroidPdfViewer:

 

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

 

As you want to read PDFs from the Internet, you are to open the AndoidManifest.xml file. Add the following code:

 

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

 

Add PDFView

 

AndroiPdfViewer comes with a PDFView so that you can see the PDF files displayed. You have to write the following code in activity_pdf_view.xml file:

 

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".PdfViewActivity">

    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/pdfView" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

If you want to open PDFs from the Internet, device storage, or assets folder, you can use AndroidPdfViewer to do so.

 

It is now time to connect the button click of MainActivity with the events mentioned above. To perform that, you have to to make checkPdfAction() function and write the following code:

 

private fun checkPdfAction(intent: Intent) {
    when (intent.getStringExtra("ViewType")) {
        "assets" -> {
            // perform action to show pdf from assets
        }
        "storage" -> {
            // perform action to show pdf from storage
        }
        "internet" -> {
            // perform action to show pdf from the internet
        }
    }
}

 

From the onCreate () call the above method:

 

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_pdf_view)

    checkPdfAction(intent)

 

 

private fun checkPdfAction(intent: Intent) {
    when (intent.getStringExtra("ViewType")) {
        "assets" -> {
            // perform action to show pdf from assets
        }
        "storage" -> {
            // perform action to show pdf from storage
        }
        "internet" -> {
            // perform action to show pdf from the internet
        }
    }
}

 

Let’s now know the way to display PDF files from Assets, Device Storage, and the Internet

 

Assets Folder

 

Let’s first have a look at how to view the PDF files that are stored in the Assets folder.

 

Create an Assets Folder

 

Creating an assets folder is the first thing you need to do to open PDFs from this folder. Right-click on the main and then go to a new folder and create Assets Folder. Paste the PDF into this folder that you want to open.

 

The PDF file you are supposed to paste is:

 

MindOrks_Android_Online_Professional_Course-Syllabus.pdf

 

Creating getPdfNameFromAssets() method

 

You have to now create a new method with the name of getPdfNameFromAssets in the class of FileUtils. Your method will help to return the PDF file name that is present in the Assets folder. 

 

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pdf_view)checkPdfAction(intent)
}

 

Create a showPdfFromAssets method in the PdfViewActivity.kt file. The file name will be taken in the string format. On top of that, this will use fromAssets() method of AndroidPdfViewer to let you see the PDF:

 

fun getPdfNameFromAssets(): String {
return "MindOrks_Android_Online_Professional_Course-Syllabus.pdf"
}

 

You are to call the method given above from checkPdfAction. Then call the getPdfnameFromAssets  to pass the file name using the method of FileUtils class:

 

private fun showPdfFromAssets(pdfName: String) {
pdfView.fromAsset(pdfName)
.password(null) // if password protected, then write password
.defaultPage(0) // set the default page to open
.onPageError { page, _ ->
Toast.makeText(
this@PdfViewActivity,
"Error at page: $page", Toast.LENGTH_LONG
).show()
}
.load()
}

 

And that’s it. You can now run the app on your Android device and see the output.

 

 

From Device Storage

 

 

How To Open PDF File In Android Programmatically

 

 

Let’s now have a look at how to open PDFs from the Device storage of your Android. You have to first find the files that come with PDF format. Launch an intent to get that done. Once you can do it, you will be able to see the PDF in the PDFView with FromUri method.

 

First of all, make sure that you have created the function named selectPdfFromStorage() in the PdfViewActivity.kt file. Now, add the following code: 

 

private fun checkPdfAction(intent: Intent) {
when (intent.getStringExtra("ViewType")) {
"assets" -> {
showPdfFromAssets(FileUtils.getPdfNameFromAssets())
}
"storage" -> {
// open pdf from storage
}
"internet" -> {
// open pdf from internet
}
}
}

 

Now once you select any PDF, the following onActivityResult will be usually called:

 

companion object {
private const val PDF_SELECTION_CODE = 99
}private fun selectPdfFromStorage() {
Toast.makeText(this, "selectPDF", Toast.LENGTH_LONG).show()
val browseStorage = Intent(Intent.ACTION_GET_CONTENT)
browseStorage.type = "application/pdf"
browseStorage.addCategory(Intent.CATEGORY_OPENABLE)
startActivityForResult(
Intent.createChooser(browseStorage, "Select PDF"), PDF_SELECTION_CODE
)
}

 

You have to now create showPdfFromUri method which takes a Uri and thus displays the PDF:

 

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PDF_SELECTION_CODE && resultCode == Activity.RESULT_OK && data != null) {
val selectedPdfFromStorage = data.data
showPdfFromUri(selectedPdfFromStorage)
}
}

 

You are now ready to run the application to check how it works and then choose the desired PDF.

 

 

PDF from Internet

 

In the end, we are going to show you how to view PDF files from the Internet. We will download the PDF file first with PRDownloader and we will make use of the file for displaying that on PdfViewActivity. We will go through the same process as we do for Assets and Storage. However, you are to use FromFile() to display the PDF.

 

The first step begins with downloading the the file with PRDownloader library.

 

Secondly, you have to initialize the file with the onCreate() method of PdfViewActivity:

 

private fun showPdfFromUri(uri: Uri?) {
pdfView.fromUri(uri)
.defaultPage(0)
.spacing(10)
.load()
}

 

From the PRDownloader, use the download() method and proceed to download the required file from the Internet. In PdfViewActivity, create the following function with the name: downloadPdfFromInternet in it. It is this function that will take the file name, directory path, and the URL of the file that is going to be downloaded.

 

PRDownloader.initialize(applicationContext)

 

Once the file has ended the downloading process, the onDownloadComplete method will come into action. You have to call showPdfFromFile method and then pass the file you have just downloaded to this method:

 

private fun downloadPdfFromInternet(url: String, dirPath: String, fileName: String) {
PRDownloader.download(
url,
dirPath,
fileName
).build()
.start(object : OnDownloadListener {
override fun onDownloadComplete() {
Toast.makeText(this@PdfViewActivity, "downloadComplete", Toast.LENGTH_LONG)
.show()
val downloadedFile = File(dirPath, fileName)
progressBar.visibility = View.GONE
showPdfFromFile(downloadedFile)
}override fun onError(error: Error?) {
Toast.makeText(
this@PdfViewActivity,
"Error in downloading file : $error",
Toast.LENGTH_LONG
)
.show()
}
})
}

 

Now, you have to call the downloadPdfFromInternet method out of the checkPdfAction method. But, you are still to get the file name, URL, and the directory name of your desired file that you want to download. To get the URL, you have to call the getPdfUrl method out of FileUtils class. Making the getRootDirPath function in the FileUtils class is going to return you with the root directory:

 

private fun downloadPdfFromInternet(url: String, dirPath: String, fileName: String) {
    PRDownloader.download(
        url,
        dirPath,
        fileName
    ).build()
        .start(object : OnDownloadListener {
            override fun onDownloadComplete() {
                Toast.makeText(this@PdfViewActivity, "downloadComplete", Toast.LENGTH_LONG)
                    .show()
                val downloadedFile = File(dirPath, fileName)
                progressBar.visibility = View.GONE
                showPdfFromFile(downloadedFile)
            }

            override fun onError(error: Error?) {
                Toast.makeText(
                    this@PdfViewActivity,
                    "Error in downloading file : $error",
                    Toast.LENGTH_LONG
                )
                    .show()
            }
        })
}

 

It is time to call the downloadPdfFromInternet method. You can get it from checkPdfAction method of PdfViewActivity:

 

private fun checkPdfAction(intent: Intent) {
    when (intent.getStringExtra("ViewType")) {
        "assets" -> {
            showPdfFromAssets(FileUtils.getPdfNameFromAssets())
        }
        "storage" -> {
            selectPdfFromStorage()
        }
        "internet" -> {
            progressBar.visibility = View.VISIBLE
            val fileName = "myFile.pdf"
            downloadPdfFromInternet(
                FileUtils.getPdfUrl(),
                FileUtils.getRootDirPath(this),
                fileName
            )
        }
    }
}

 

And that’s all. You should now run the application.

 


you may also have interested to know:

What is omacp on android

how to change emoji color on android

how to recover deleted text messages on android without computer

how to change font color on android

how to empty trash android

 

 

Frequently Asked Questions (FAQ)

 

How can I display a PDF file inside my Android application?

 

The easiest way to display your PDF file is to save your file inside the Assets folder under the main folder.

 

How to open pdf file in android programmatically from URL?

 

After putting Webview in your layout, load the URL of the pdf you want to open. You have to use webView. loadUrl() function to do so. Now run the app and you will see the PDF displayed.

 

How to open pdf from SDcard in Webview in android without Intent?

 

Generally it is not possible to open Pdf directly in your Android web browser.

 

How to open local pdf file in Webview in android programmatically?

 

For older versions of Android, Xamarin uses pdf.js from Mozilla to do so.

 

However, for newer versions, you can try Google Docs online viewer to view PDF in Webview.

 

Final Thoughts

 

Make sure that you check and verify all the three options we have talked about i.e. assets, device storage, and internet. To see if you can load your PDF link, you can replace the existing PDF file link we have shared by your PDF URL.

 

So, by now you know how to display pdf file inside your android application and how to open pdf file in Android programmatically.

Leave a Reply

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