'How can I programmatically check if a file is a valid PDF document in Android Studio?

In my app, I have a button that allows the user to pick a PDF file from the external downloads folder. My code for that is shown below:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(intent, IMPORT_PDF);

I also have a screenshot of the file picker intent:

enter image description here

Once the user picks a file, I run the code below in OnActivityResult:

if (requestCode == IMPORT_PDF) {
    Uri uri;
    if (data != null) {
        // get uri of selected file
        uri = data.getData();

And I proceed to use the file's URI to open it in a PDF viewer that I integrated into my app (PDFTron), and I have already tested that the PDF viewer works.

Here's the problem: When the PDF is of "invalid format" and I try to open it in my app, I get the following error and the PDF viewer crashes:

W/System.err: Exception: 
     Message: PDF header not found. The file is not a valid PDF document.

Is there any way to check if a PDF file is of invalid format programmatically before I try to open it in my PDF viewer?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source