I am looking into the PDF renderer API native to Google Android development. I see the following code example in the documentation:
// create a new renderer
PdfRenderer renderer = new PdfRenderer(getSeekableFileDescriptor());
// let us just render all pages
final int pageCount = renderer.getPageCount();
for (int i = 0; i < pageCount; i++) {
Page page = renderer.openPage(i);
// say we render for showing on the screen
page.render(mBitmap, null, null, Page.RENDER_MODE_FOR_DISPLAY);
// do stuff with the bitmap
// close the page
page.close();
}
// close the renderer
renderer.close();
I think this example uses from File Object. How I can get this API to work with a URL from a webserver, such as a document from a website? How can I load a PDF natively in an Android app that does not require a download of the file onto the local storage? Something like how you can run the Google docs viewer to open the PDF in webview - but I cannot take that approach because the Google docs viewer is blocked in the environment I am in.
What is PdfRenderer? The PdfRenderer allows us to create a Bitmap from a page in a PDF document so that we can display it on the screen. PdfRenderer class is not thread-safe. If we want to render a PDF, we first need to get a ParcelFileDescriptor from the file and then create a renderer instance.
Developers or not, most of us are familiar with PDFs and are used to work with them all the time, so rendering PDFs may seem like an ordinary task that any platform should be able to perform with minimal effort. Surprisingly, that's not exactly the case on Android.
With that in mind, this is how we'd render the first page of our PDF file: First line is easy, whenever we want to open a page we can simply call openPage () and pass the index of the page we want to open. The bitmap creation is a bit more interesting.
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Navigate to the Gradle Scripts > build.gradle (Module:app) and add the below dependency in the dependencies section. implementation ‘com.github.barteksc:android-pdf-viewer:2.8.2’
how I can get this API to work with URL from a webserver?
Download the PDF from the server to a local file. Then, use the local file.
The purpose of what I am trying to learn is how to load pdf natively in android app that does not require a download of the file onto the local storage
AFAIK, you cannot use PdfRenderer
that way. It needs a seekable FileDescriptor
, and the only way that I know of to create one of those involves a local file.
You cannot use Pdf Renderer to load URL. But your can make use of Google Docs in your webview to load URL without downloading the file...
webView.loadUrl("https://docs.google.com/gview?embedded=true&url=" + YOUR_URL);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With