How to display a PDF via Android web browser without "downloading" first
Asked Answered
L

12

130

Is there a way to get the stock Android browser to auto-open a PDF, Word or other typical file without having to go through the process of downloading the file and then getting the user to open the file from the Downloads app or the Notification bar?

We have a web application that has a lot of documents that we'd like to include and not have to convert to HTML, but making the user download the file and manually open it is not easy to train users on.

On iOS, these files all display inline in the browser. I'd like a way to get the browser to auto-launch the files into Acrobat Reader or QuickOffice or whatever program the user has to display them.

Does anyone know a way to do that? I know that Google Docs has some PDF viewing support, but people using our web app may not have public Internet access in all cases, and may be hitting on a local web server.

Lyre answered 15/9, 2011 at 21:23 Comment(3)
I've never seen it work that way. That being said, I would imagine you could create your own browser that is capable of decoding and properly displaying pdf files. I just don't believe any of the popular browsers support this.Gossoon
Are your PDF files optimized for "Fast Web View"? If not they can not be displayed while download is still in progress - hence they can only be downloaded and then displayed.Towrey
If the browser is not handling Content-Disposition:inline and similar headers properly, try serving it through viewerjs or similar javascript PDF renderer. (instead of serving the pdf, serve an iframe that loads a viewer that fetches the pdf).Irs
H
84

You can open a file PDF in Google Docs Viewer by appending the URL to:

https://docs.google.com/gview?embedded=true&url=<URL of a supported doc>

This would open a PDF file in the default browser or a WebView.

A list of supported formats is given here.

Haematin answered 3/4, 2012 at 15:3 Comment(15)
This was very helpful, thank you. I'm not sure it's 100% necessary, but it is probably worth mentioning that the <url of a supported doc> should be urlencoded.Apospory
This doesn't work for me... It just display a page "Oops! There was a problem previewing this document" with a download button. There is nothing happens when you click on the download button.Bouley
The above link failed to work for Chrome on Android, I switched to https://drive.google.com/viewerng/viewer?embedded=true&url=#### and that did the job!Grube
Hi, it seems the url in the answer no longer works . I get an infinite loop with it now in webView listener. The url posted in comment from QFDev is working.Destrier
This still saves the document to your temp android directory if I recall correctly.Cremator
This is also providing download option at the right corner of the screen If You click more than 10 times It is redirectionOverturn
Is this url changes from locale to locale ?Lolanthe
there is a size limit in viewing pdf in google doc. is there any workaround for that?Depressed
sorry, but this tip never worked for me, it always returns the same error "No preview available" :-(Innocent
while I am in China, i could not reach any google services, is there a alternative way ?Mallon
This is a WORKAROUND that requires google obtaining a copy of the document (and making the document publicly accessible over the Internet). Not really an answer to the question, and absolutely devastating from a security/privacy point of view.Irs
The version in the comment by QFDev works for me. Does anyone have an idea to make this more convenient and quick to open a pdf using this url? (It would be great if we could somehow set chrome visiting this url with the link appended as the default action for clicking the link but that is probably asking too much.)Downwards
@Irs If the doc you are trying to preview is publicly accessible to the internet then I don't think this is a security concern.Skilled
@FunyinoluwaKashimawo, even if it is not a security issue, it's building in a dependency to a third-party service that may not be available. See KingAmo's comment.Irs
@Irs true. That was definitely a concern for me. You don't want to depend on another system you can't guarantee will always be up.Skilled
D
31

You can use this format as of 2017-04-06.

https://docs.google.com/viewerng/viewer?url=http://yourfile.pdf

Just replace http://yourfile.pdf with the link you use.

Dissimilar answered 6/4, 2017 at 22:4 Comment(3)
The perfect way to get the preview without full download.Risner
perfect answer .Tendency
This is a WORKAROUND that requires google obtaining a copy of the document (and making the document publicly accessible over the Internet). Not really an answer to the question, and absolutely devastating from a security/privacy point of view.Irs
S
6
String format = "https://drive.google.com/viewerng/viewer?embedded=true&url=%s";
String fullPath = String.format(Locale.ENGLISH, format, "PDF_URL_HERE");
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(fullPath));
startActivity(browserIntent);
Swordsman answered 9/8, 2017 at 8:11 Comment(2)
This is a WORKAROUND that requires google obtaining a copy of the document (and making the document publicly accessible over the Internet). Not really an answer to the question, and absolutely devastating from a security/privacy point of view.Irs
Could you expand on what you are doing here? Are you automating opening the pdf with the google drive link? Where is this script meant to go?Downwards
J
5

Specifically, to install the pdf.js plugin for Firefox, you do not use the app store. Instead, go to addons.mozilla.org from inside Mozilla and install it from there.

Also, to see if it's installed properly, go to the menu ToolsAdd-ons (not the "about:plugins" URL as you might think from the desktop version).

Joyless answered 17/1, 2015 at 16:17 Comment(1)
Are you saying this is possible on android?As far as I know there are only a few Firefox plugins that can be installed on android and this one is not one of them.Downwards
S
4

Try this code This worked for me.

package ak.wp.meto.activity;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Toast;
import com.github.barteksc.pdfviewer.PDFView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import ak.wp.meto.R;

public class PdfViewer extends Activity {
    private TextView txt; // You can remove if you don't want this
    private PDFView pdf;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_pdf);
   
        pdf = (PDFView) findViewById(R.id.pdfView); //github.barteksc
        txt = findViewById(R.id.txtPdf);
        String pdfUrl = "https://www.rkiinstruments.com/pdf/71-0136RK.pdf";
        try{
            new RetrievePdfStream().execute(pdfUrl);
        }
        catch (Exception e){
            Toast.makeText(this, "Failed to load Url :" + e.toString(), Toast.LENGTH_SHORT).show();
        }
    }

    class RetrievePdfStream extends AsyncTask<String, Void, InputStream> {
        @Override
        protected InputStream doInBackground(String... strings) {
            InputStream inputStream = null;
            try {
                URL url = new URL(strings[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                if (urlConnection.getResponseCode() == 200) {
                    inputStream = new BufferedInputStream(urlConnection.getInputStream());
                }
            } catch (IOException e) {
                return null;
            }
            return inputStream;
        }
        @Override
        protected void onPostExecute(InputStream inputStream) {
            pdf.fromStream(inputStream).load();
        }
    }

}

add library in build.gradle

 implementation 'com.github.barteksc:android-pdf-viewer:3.1.0-beta.1'
 implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'

create activity_custom_pdf.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        tools:context=".activity.PdfViewer">
    
        <com.github.barteksc.pdfviewer.PDFView
            android:id="@+id/pdfView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    
        <TextView
            android:id="@+id/txtPdf"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="invisible"/>
    </RelativeLayout>
Skinhead answered 26/2, 2022 at 0:58 Comment(2)
It uses android-pdf-viewer library and AsyncTask. :)Chapin
It would work (much better than the other answers with Google Drive??), but it also increase APK size by 16 MBWhosoever
R
3

Unfortunately the native browser present on Android devices not support this type of file. Let's see if in the 4.0 we will be able to do that.

Retha answered 24/10, 2011 at 17:58 Comment(0)
N
3

I needed this too, and the links above stopped working so this is what I found to work with the New Google Drive:

Google has a service that creates the link for PDF's Not in GDrive: https://docs.google.com/viewer Just add your URL and it creates a link, and IFrame code (Look closely and you will see the pattern and create links without this web service)

Also, there is a way to do it for PDF's stored in Google Drive: https://docs.google.com/viewer?srcid=YOUR_GDRIVE_PDF_DOC_ID_HERE&pid=explorer&efh=false&a=v&chrome=false&embedded=true (this can be a link or the src URL of an iframe)

I've tested on Android and it brings up the PDF viewer nicely.

Natividadnativism answered 11/8, 2014 at 15:56 Comment(5)
For me, if I am not currently signed in with a google account, then it takes me to a log in page. Is there a way to bypass this and just view the pdf?Meatiness
Try using viewerjs.org viewer.js file looks promising because it is browser independent and relies on your server to do the heavy lifting.Cinematograph
This is a WORKAROUND that requires google obtaining a copy of the document (and making the document publicly accessible over the Internet). Not really an answer to the question, and absolutely devastating from a security/privacy point of view.Irs
What links stopped working? In a particular answer?Clayborne
OK, the poster left the building in 2017. Can someone else chime in?Clayborne
F
2

You can use this

webView.loadUrl("https://docs.google.com/viewer?url=" + "url of pdf file"); 
Frug answered 19/10, 2016 at 10:57 Comment(4)
can anyone please mention the reason of downvoting.Frug
May be, your answer holds good for some programming technique, and the answer could be just the URL, even I can add it into an anchor tag, which is already mentioned abovePlumose
@akash maybe u need adding more explanation. it's the rules hereStrudel
This is a WORKAROUND that requires google obtaining a copy of the document (and making the document publicly accessible over the Internet). Not really an answer to the question, and absolutely devastating from a security/privacy point of view.Irs
I
1
public class MainActivity extends AppCompatActivity {

    Button button;

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

        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openURL("http://docs.google.com/viewer?url=" + " your pdf link ");
            }
        });
    }

    private void openURL(String s) {
        Uri uri = Uri.parse(s);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri,"text/html");
        startActivity(intent);
    }
}
Impenetrable answered 12/5, 2020 at 9:5 Comment(1)
This is a WORKAROUND that requires google obtaining a copy of the document (and making the document publicly accessible over the Internet). Not really an answer to the question, and absolutely devastating from a security/privacy point of view.Irs
T
1

I'm using PDF.js here:

They have two demo links to first verify that it's actually working mobile ( for it does )

I found that when using <object data="${pdf}" width="100%" height="100%" type="application/pdf"> Firefox actually using PDF.js in the background but version 3.4 - which didn't work for me on mobile.

When using the latest PDF.js from the GitHub link, it's using version 3.5

But the reason I'm writing this answer, is actually because I found a very simple way of using PDF.js w/o all this Javascript, implemented the following <iframe> tag according to this document

<iframe
      src="/web/viewer.html?file=/path/to/server/document.pdf"
      width="1000px"
      height="1000px"
      style="border: none"></iframe>

Ofc I had to edit the links inside viewer.html to match my personal server structure, but it's working great for me on both desktop ( Chrome / Firefox ) and mobile Android (Brave)

Togliatti answered 5/5, 2023 at 14:51 Comment(0)
H
0

Try the following. It worked for me.

WebView view = (WebView) findViewById(R.id.yourWebView);

view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setPluginState(WebSettings.PluginState.ON);
view.loadUrl("http://docs.google.com/gview?embedded=true&url="
              +"your document link(pdf,doc,docx...etc)");
Hamper answered 1/3, 2017 at 7:34 Comment(9)
setPluginState ON is important, thanks mentioning itCowan
@BeeingJk, setPluginState is deprecated from API 18 (#19362549).Chapin
@Chapin what you showed in link is setPluginsEnabled rather than setPluginStateCowan
@BeeingJk, please, open the page again, press Ctrl + F, write "setPluginState" and press Enter.Chapin
@Chapin ok thanks I also saw it here, developer.android.com/reference/android/webkit/…, but I couldn't remove setPluginState else my webview won't workCowan
@BeeingJk, thanks, you are right, these situatuins exist in Android (and devices). By the way, what is your API version?Chapin
check this link #55829946Bartolomeo
This is a WORKAROUND that requires google obtaining a copy of the document (and making the document publicly accessible over the Internet). Not really an answer to the question, and absolutely devastating from a security/privacy point of view.Irs
Could you explain what you are doing here. Where would this script go?Downwards
R
-7
  • Download the Acrobat Reader .apk file for Android to display PDF files

  • Put your PDF files on an SD card

  • Use the snippet of code below

     File file = new File("/sdcard/test.pdf");
     Uri path = Uri.fromFile(file);
     Intent i = new Intent(Intent.ACTION_VIEW);
     i.setDataAndType(path,"application/pdf");
     i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
     startActivity(i);
    
Romanism answered 21/3, 2012 at 13:0 Comment(1)
This is for a web browser, not a native android application. -1Creek

© 2022 - 2024 — McMap. All rights reserved.