Open In App

How to Implement PDF Picker in Android?

Last Updated : 04 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to see how we can implement a PDF picker in android studio and get the file information of the pdf like file name, size and path. In this application, we will create a launcher to launch the file picker and display the file information after a pdf is picked successfully.

Note that we are going to implement this application using Java & Kotlin language.

Step by Step Implementation

Step 1: Create a New Project

 To create a new project in the Android Studio, please refer to How to Create/Start a New Project in Android Studio?

Step 2: Working with activity_main.xml

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. In this file we will be adding a button to launch pdf picker and a textview to display the document informations.

activity_main.xml:

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <!--Button to pick pdf-->
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pick pdf"/>

    <!--TextView to display file information-->
    <TextView
        android:id="@+id/fileNameTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="32dp"
        android:text="file name"/>

</LinearLayout>


Step 3: Working with MainActivity file

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

MainActivity.java
package org.geeksforgeeks.demo;

import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.database.Cursor;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    // UI elements
    private Button button;
    private TextView fileNameTextView;
    // URI for the selected PDF
    private Uri selectedPdfUri;

    // Activity launcher for picking PDF
    private final ActivityResultLauncher<String[]> pickPdfLauncher =
        registerForActivityResult(new ActivityResultContracts.OpenDocument(), uri -> {
            if (uri != null) {
                selectedPdfUri = uri;
                // Get the file information
                Pair<String, Long> fileInfo = getFileInfo(uri);
                String fileName = fileInfo.first;
                float fileSize = fileInfo.second;

                // Convert file size to MB
                String fileSizeInMB = String.format(Locale.getDefault(), "%.3f", fileSize / 1000000.0);

                // Update the UI with the file information
                fileNameTextView.setText("Filename - " + fileName + "\nFile size - " + fileSizeInMB + " MB\nFile path - " + uri.getPath());
            } else {
                // Handle the case where no file was selected
                Toast.makeText(MainActivity.this, "No file selected", Toast.LENGTH_SHORT).show();
            }
        });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize UI elements
        button = findViewById(R.id.button);
        fileNameTextView = findViewById(R.id.fileNameTextView);

        // Set click listener for the button
        button.setOnClickListener(v -> {
            // Launch the PDF picker
            pickPdfLauncher.launch(new String[]{"application/pdf"});
        });
    }

    // Function to get the file name from URI - optional
    private Pair<String, Long> getFileInfo(Uri uri) {
        // Initialize default values
        String fileName = "Unknown";
        long fileSize = 0L;

        // Query the content resolver to get the file name and size
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        if (cursor != null) {
            try {
                // Move to the first row
                if (cursor.moveToFirst()) {
                    // Get the display name and size columns
                    int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
                    // Check if the columns exist
                    if (nameIndex != -1) {
                        // Get the file name and size
                        fileName = cursor.getString(nameIndex);
                        fileSize = cursor.getLong(sizeIndex);
                    }
                }
            } finally {
                cursor.close();
            }
        }

        // Return the file name and size as a pair
        return new Pair<>(fileName, fileSize);
    }

    // Simple Pair class
    private static class Pair<F, S> {
        public final F first;
        public final S second;
        public Pair(F first, S second) {
            this.first = first;
            this.second = second;
        }
    }
}
MainActivity.kt
package org.geeksforgeeks.demo

import android.net.Uri
import android.os.Bundle
import android.provider.OpenableColumns
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import java.lang.String.format

class MainActivity : AppCompatActivity() {

    // UI elements
    private lateinit var button: Button
    private lateinit var fileNameTextView: TextView
    // URI for the selected PDF
    private var selectedPdfUri: Uri? = null

    // Activity launcher for picking PDF
    private val pickPdfLauncher =
        registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
            uri?.let {
                selectedPdfUri = it
                // Get the file information
                val fileInfo = getFileInfo(it)
                val fileName = fileInfo.first
                val fileSize = fileInfo.second.toFloat()

                // Convert file size to MB
                val fileSizeInMB = format("%.3f", fileSize / 1000000.0)

                // Update the UI with the file information
                fileNameTextView.text = "Filename - $fileName\nFile size - $fileSizeInMB MB\nFile path - ${it.path}"
            } ?: run {
                // Handle the case where no file was selected
                Toast.makeText(this@MainActivity, "No file selected", Toast.LENGTH_SHORT).show()
            }
        }

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

        // Initialize UI elements
        button = findViewById(R.id.button)
        fileNameTextView = findViewById(R.id.fileNameTextView)

        // Set click listener for the button
        button.setOnClickListener {
            // Launch the PDF picker
            pickPdfLauncher.launch(arrayOf("application/pdf"))
        }
    }

    // Function to get the file name from URI - optional
    private fun getFileInfo(uri: Uri): Pair<String, Long> {
        // Initialize default values
        var fileName = "Unknown"
        var fileSize = 0L
        // Query the content resolver to get the file name and size
        contentResolver.query(uri, null, null, null, null)?.use { cursor ->
            // Move to the first row
            if (cursor.moveToFirst()) {
                // Get the display name and size columns
                val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                val sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE)
                // Check if the columns exist
                if (nameIndex != -1) {
                    // Get the file name and size
                    fileName = cursor.getString(nameIndex)
                    fileSize = cursor.getLong(sizeIndex)
                }
            }
        }
        // Return the file name and size as a pair
        return Pair(fileName, fileSize)
    }
}

Output: 




Next Article

Similar Reads