How to Implement PDF Picker in Android?


By adding a PDF picker to an Android application, users can easily choose and work with PDF files right within the app. This feature enhances user experience as it allows seamless access to important documents. To integrate this functionality, developers need to add a specific file picker component for PDF files which enables users to browse device storage and select a file. They can then view, edit or share the document. By following simple steps, developers can implement this feature into their Android app making interacting with PDF files more convenient for users.

PDF

Portable Document Format, more commonly known as PDF, is a widely recognized file format developed by Adobe Systems. Its purpose was to offer a universal way of representing documents free of any software, hardware, or operating system limitations. What sets PDF files apart is their ability to preserve the layout, fonts, formatting, and images of a document uniformly across different platforms. This makes them an ideal medium for sharing and viewing documents worldwide.

PDFs offer high versatility and enable the inclusion of an array of elements such as text, images, hyperlinks, tables, forms, and multimedia. They are widely utilized for reports, contracts, brochures, manuals and e-books. One of their most significant benefits is platform independent; users can access and interact with them on different devices running various operating systems by leveraging PDF reader applications.

Approaches

To implement a PDF picker in an Android application using Java, you can follow several methods. Here are three common approaches:

  • Using Intent

  • Using a File Picker Library

  • Using Storage Access Framework (SAF)

Using Intent

This method involves launching an intent with the action ACTION_GET_CONTENT and the MIME type set to application/pdf. This opens the system file picker, allowing users to select a PDF file. Upon receiving the result in the onActivityResult method, you can retrieve the selected PDF file based on the returned data.

Algorithm

  • Use the ACTION_GET_CONTENT intent with the MIME type set to application/pdf.

  • Launch the intent and handle the result in the onActivityResult method to retrieve the selected PDF file.

Example

//MainActivity.java
package com.example.volley;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

   private Button pickPdfButton;
   private TextView selectedPdfTextView;

   private ActivityResultLauncher<Intent> pdfPickerLauncher;

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

      pickPdfButton = findViewById(R.id.pick_pdf_button);
      selectedPdfTextView = findViewById(R.id.selected_pdf_text_view);

      pickPdfButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            openPdfPicker();
         }
      });

      pdfPickerLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            result -> {
               if (result.getResultCode() == Activity.RESULT_OK) {
                  Intent data = result.getData();
                  if (data != null) {
                     Uri pdfUri = data.getData();
                     String pdfName = getFileName(pdfUri);
                     selectedPdfTextView.setText(pdfName);
                     // Do something with the selected PDF file
                  }
               } else {
                  Toast.makeText(MainActivity.this, "No PDF selected", Toast.LENGTH_SHORT).show();
               }
            });
   }

   private void openPdfPicker() {
      Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
      intent.setType("application/pdf");
      pdfPickerLauncher.launch(intent);
   }

   private String getFileName(Uri uri) {
      String result = null;
      if (uri.getScheme().equals("content")) {
         try (Cursor cursor = getContentResolver().query(uri, null, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
               int columnIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
               if (columnIndex != -1) {
                  result = cursor.getString(columnIndex);
               }
            }
         }
      }
      if (result == null) {
         result = uri.getLastPathSegment();
      }
      return result;
   }
}

//activity_main.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"
   tools:context=".MainActivity">

   <Button
      android:id="@+id/pick_pdf_button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Pick PDF"
      android:layout_centerInParent="true"/>

   <TextView
      android:id="@+id/selected_pdf_text_view"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textSize="16sp"
      android:layout_below="@id/pick_pdf_button"
      android:layout_marginTop="16dp"
      android:layout_centerHorizontal="true"/>

</RelativeLayout>

Output

Using a File Picker Library

This approach requires integrating a file picker library into your Android project, such as android-filepicker, TedPicker, or MaterialFilePicker. These libraries provide pre-built components that allow you to display and filter files, including PDFs. By configuring the library and implementing the necessary callbacks, you can retrieve the selected PDF file from the user's file selection.

Algorithm

  • Integrate a file picker library, such as android-filepicker, TedPicker, or MaterialFilePicker, into your project.

  • Configure the library to filter and display only PDF files.

  • Implement the necessary callbacks or listeners to retrieve the selected PDF file.

Example

// Step 1: Add the file picker library to your project's dependencies
implementation 'com.github.jaiselrahman:FilePicker:2.4.1'

// Step 2: Request the necessary permissions in your AndroidManifest.xml file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

// Step 3: Create a button in your layout file to trigger the PDF picker
<Button
   android:id="@+id/btnPickPDF"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Pick PDF" />

// Step 4: In your activity or fragment, initialize the file picker library
FilePicker filePicker = new FilePicker(this);

// Step 5: Set the file types to be picked (in this case, PDF files)
filePicker.setFileTypes(new String[]{".pdf"});

// Step 6: Set the file picker listener to handle the selected PDF file
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.nbsp.materialfilepicker.MaterialFilePicker;
import com.nbsp.materialfilepicker.ui.FilePickerActivity;

import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

   private static final int PERMISSION_REQUEST_CODE = 1;

   private Button btnPickPDF;

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

      btnPickPDF = findViewById(R.id.btnPickPDF);
      btnPickPDF.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            checkPermissionsAndPickFile();
         }
      });
   }

   private void checkPermissionsAndPickFile() {
      if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
         ActivityCompat.requestPermissions(this,
               new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
               PERMISSION_REQUEST_CODE);
      } else {
         startFilePicker();
      }
   }

   private void startFilePicker() {
      new MaterialFilePicker()
            .withActivity(this)
            .withRequestCode(PERMISSION_REQUEST_CODE)
            .withFilter(Pattern.compile(".*\.pdf$"))
            .withHiddenFiles(true)
            .start();
   }

   @Override
   public void onRequestPermissionsResult(int requestCode, @NonNull String[] 
permissions, @NonNull int[] grantResults) {
      if (requestCode == PERMISSION_REQUEST_CODE) {
         if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startFilePicker();
         } else {
            Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
         }
      }
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);

      if (requestCode == PERMISSION_REQUEST_CODE && resultCode == RESULT_OK) {
         String filePath = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
         if (filePath != null) {
            // Handle the selected PDF file here
            // You can perform operations like displaying the file name or opening the file
            File file = new File(filePath);
            // Do something with the file
         }
      }
   }
}

Output

Using Storage Access Framework (SAF)

To start selecting PDF files in your app, the first step is to request READ_EXTERNAL_STORAGE permission through the app manifest. After that, launch the file picker system using Intent.ACTION_OPEN_DOCUMENT intent specifically for PDFs. Once you receive the result from onActivityResult method, access the selected PDF's URI to perform additional operations on it.

Algorithm

  • Start by requesting the READ_EXTERNAL_STORAGE permission in your app's manifest.

  • Use the Intent.ACTION_OPEN_DOCUMENT intent to allow users to select PDF files using the system's file picker.

  • Handle the result in the onActivityResult method to obtain the selected PDF file's URI.

Example

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

   private static final int REQUEST_CODE_PICK_PDF = 1;

   private Button pickPdfButton;

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

      pickPdfButton = findViewById(R.id.pick_pdf_button);
      pickPdfButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.setType("application/pdf");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, REQUEST_CODE_PICK_PDF);
         }
      });
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);

      if (requestCode == REQUEST_CODE_PICK_PDF && resultCode == RESULT_OK) {
         if (data != null) {
            Uri uri = data.getData();
            if (uri != null) {
               String pdfPath = getPathFromUri(uri);
               // Do something with the selected PDF file path
            }
         }
      }
   }

   private String getPathFromUri(Uri uri) {
      String path = null;
      if (DocumentsContract.isDocumentUri(this, uri)) {
         String documentId = DocumentsContract.getDocumentId(uri);
         if (documentId.startsWith("raw:")) {
            path = documentId.substring(4);
         } else {
            String[] split = documentId.split(":");
            if (split.length >= 2) {
               String type = split[0];
               String id = split[1];
               Uri contentUri = null;
               if ("primary".equalsIgnoreCase(type)) {
                  contentUri = Uri.parse("content://media/external/file/" + id);
               } else {
                  contentUri = Uri.parse("content://com.android.externalstorage.documents/document/" + id);
               }
               String[] projection = {DocumentsContract.MediaColumns.DATA};
               Cursor cursor = getContentResolver().query(contentUri, projection, null, null, null);
               if (cursor != null && cursor.moveToFirst()) {
                  int columnIndex = cursor.getColumnIndexOrThrow(DocumentsContract.MediaColumns.DATA);
                  path = cursor.getString(columnIndex);
                  cursor.close();
               }
            }
         }
      }
      return path;
   }
}

Output

Conclusion

In this tutorial, implementing a PDF picker in an Android application allows users to conveniently select and interact with PDF files within the app. By integrating methods such as using intents, file picker libraries, or the Storage Access Framework, developers can provide a seamless and user-friendly experience for accessing and working with PDF documents. Whether it's through the system file picker, custom file picker dialogs, or URI retrieval, the chosen method can be tailored to suit the specific requirements of the app and enhance the overall functionality for handling PDF files.

Updated on: 26-Jul-2023

957 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements