Marvil
Marvil

Reputation: 93

How do I open a PDF file with an Android app?

If I have a PDF file in main\res\PDFs\test.pdf, how do I open it?

I was thinking of doing

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("URI of the file"));
                startActivity(browserIntent);

I don't know what to put in the URI, nor if the browser can open PDFs natively though. I'm targeting Android 4.1.3, but if it can't open PDF files out of the box, then I can switch to a newer API level, preferably as old as possible.

I would rather not do a WebView, but if it's necessary, then i can do one. Thanks!

Upvotes: 1

Views: 1002

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006564

If I have a PDF file in main\res\PDFs\test.pdf, how do I open it?

Copy the PDF to a file on internal storage (e.g., in getCacheDir()), then use FileProvider to make it available to other apps. This sample Java app and its Kotlin counterpart do exactly that.

I don't know what to put in the URI

A resource is not a file on the filesystem of the device. There is no easy way to get a Uri directly to the resource.

I'm targeting Android 4.1.3, but if it can't open PDF files out of the box, then I can switch to a newer API level, preferably as old as possible.

No Android device is guaranteed to have an app that will render PDFs in response to an ACTION_VIEW Intent. Whether that will be available to your app depends on:

  • Whether the manufacturer shipped such an app, or whether the user installed such an app; and
  • Whether the current user has rights to run that app (not always guaranteed, particularly for family-shared devices)

I would rather not do a WebView

WebView has no built-in ability to render PDFs.

There are other options for rendering PDFs in your own app, with varying limitations.

The best solution, if possible, is to switch from PDF to HTML/CSS/images, and render that in a WebView.

Upvotes: 1

Related Questions