0

I was trying to create a chooser to grant users freedom to open a pdf file with the application they prefer.

Here's my approach:

    private void openPdf(String pdfUrl, String mime) {
//        Intent pdfViewIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        Intent pdfViewIntent = new Intent(Intent.ACTION_VIEW);
        pdfViewIntent.setDataAndType(Uri.parse(pdfUrl), mime);
        Log.d(TAG, "openPdf: uri: " + Uri.parse((pdfUrl)));

        Intent chooser = Intent.createChooser(pdfViewIntent, "Choose an app");
//        chooser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // optional

        startActivity(chooser);
        finish();
    }

The pdf url is something like this: https://drive.google.com/file/d/.../view?usp=sharing

And for the mime type, I tried using both "application/vnd.google-apps.document" and "application/pdf".

Now, when the user clicks on document, I get an output like the following:

my output

But I want an output like the following screenshot: (it appears when I try to open the same link with WhatsApp)

desired output

NOTE 1: using WebView is not a good option for me.

NOTE 2: the above approach works if the URL is in the format https://example.com/.../filename.pdf. But it fails for Google Drive's link.

ganjaam
  • 1,030
  • 3
  • 17
  • 29
  • Did you download the PDF in the first place? as I think you can not open PDF directly in a local PDF viewer and if you have downloaded the PDF then your code is missing a flag which is `Intent.FLAG_GRANT_READ_URI_PERMISSION` – Rakshit Nawani Jan 17 '22 at 07:31
  • 1
    `was trying to create a chooser to grant users freedom to open a pdf file... ` That has nothing to do with a chooser but with using an ACTION_VIEW intent. – blackapps Jan 17 '22 at 07:32
  • 1
    Set type to "text/html". – blackapps Jan 17 '22 at 07:34
  • @RakshitNawani I did not download the pdf in my code. However, when the pdf url is in the format `https://our.domain.name/relativeurl/filename.pdf` the above solution works perfectly. This solution fails only when google drive's url is provided. – ganjaam Jan 17 '22 at 07:53
  • 1
    @ganjaam The last time worked on this we were unable to open Google drive's PDF directly because of a known bug from google drive, we need to download the PDF in the first place and then open the downloaded PDF. I would suggest doing the same if you are unable to move forward.\ – Rakshit Nawani Jan 17 '22 at 08:16
  • 1
    Google Drive does not create direct links to the files, so when the system opens the URL it gets a webpage, not a PDF. Try using `/preview` instead of `/view` at the end of your URL or generate a direct download link for the google drive file of the format `https://drive.google.com/uc?export=download&id=DRIVE_FILE_ID` where DRIVE_FILE_ID are the letters between `/d/` and `/view`. – GenError Jan 17 '22 at 08:36

0 Answers0