43

Currently I have a pdf url, and I would like to simply using the intent to open it, however, it does not work if I put the url in intent

My code is like this, it always throw ActivityNotFoundException error

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(law.url), "application/pdf");

try {
    startActivity(intent);
} catch (ActivityNotFoundException e){
    Utility.showErrorDialog(
        ctx,ctx.getResources().getString(R.string.sys_in, 
        ctx.getResources().getString(R.string.err_no_pdf_reader), 
        ctx.getResources().getString(R.string.close));
}

Also I tried the goolge doc approach but my client reject this, so I am not using this method

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setDataAndType(Uri.parse("http://docs.google.com/viewer?url=" 
+ publish.get(Integer.parseInt((String) view.getTag())).pdfURL), "text/html");  
ctx.startActivity(intent);

Thanks for help

Log cat error Update

04-23 18:18:50.487: E/AndroidRuntime(17161): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=http://oshc.zizsoft.com/oshc_testing.pdf typ=application/pdf }
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1568)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1439)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.app.Activity.startActivityForResult(Activity.java:3356)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.app.Activity.startActivityForResult(Activity.java:3317)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:848)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.support.v4.app.Fragment.startActivity(Fragment.java:878)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at com.example.oshpedia.Fragment.Shelf$4.onItemClick(Shelf.java:142)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at it.sephiroth.android.library.widget.AdapterView.performItemClick(AdapterView.java:299)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at it.sephiroth.android.library.widget.AbsHListView.performItemClick(AbsHListView.java:972)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at it.sephiroth.android.library.widget.AbsHListView$PerformClick.run(AbsHListView.java:2511)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at it.sephiroth.android.library.widget.AbsHListView$1.run(AbsHListView.java:3200)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.os.Handler.handleCallback(Handler.java:615)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.os.Looper.loop(Looper.java:137)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at android.app.ActivityThread.main(ActivityThread.java:4882)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at java.lang.reflect.Method.invokeNative(Native Method)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at java.lang.reflect.Method.invoke(Method.java:511)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
04-23 18:18:50.487: E/AndroidRuntime(17161):    at dalvik.system.NativeStart.main(Native Method)
user3538235
  • 1,991
  • 6
  • 27
  • 55

13 Answers13

88

You can view or download the pdf by either of the two ways i.e by opening it in device in-built browser or in the webview by embedding it in your app.

To open the pdf in browser,

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(pdf_url));
startActivity(browserIntent);

Instead to open in webview,

 WebView webView = (WebView) findViewById(R.id.webView1);
 webView.getSettings().setJavaScriptEnabled(true);
 webView.loadUrl(pdf_url);
Akanksha Hegde
  • 1,738
  • 11
  • 14
40

Best practice is wrapping your Intent to Chooser before starting. It provides users with built-in application selection dialog and lets avoid ActivityNotFoundException

Here a little example:

Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.setDataAndType(Uri.parse(msg.getData()), Constants.MIME_PDF);

Intent chooser = Intent.createChooser(browserIntent, getString(R.string.chooser_title));
chooser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // optional

startActivity(chooser);

Where Constants.MIME_PDF is defined as String value "application/pdf".


It is possible to ask PackageManager is this Intent has appropriate handling Activity or not.

public static boolean isActivityForIntentAvailable(Context context, Intent intent) {
    final PackageManager packageManager = context.getPackageManager();
    List list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}
Zhar
  • 3,330
  • 2
  • 24
  • 25
Alexander Skvortsov
  • 2,696
  • 2
  • 17
  • 31
  • 1
    This is a great solution because it makes use of the existing apps to open the pdf document and also gives the user the option to choose which one he prefers. Not adding the chooser will break the app though if there isn't any 'pdf reader' app installed. – mgm Feb 05 '19 at 13:45
  • Simple and amazing. Thank you! – Alex Belets Dec 07 '19 at 21:05
  • This helped me. I was having a link without pdf name, pdf was generated when we hit that url. In webview it stopped showing recently. Using chooser method I was able to show pdf. Thanks – ashishdhiman2007 Jan 22 '21 at 10:23
  • this is a good solution but when I use google drive's link, it does not work. can you please take a look at [this question](https://stackoverflow.com/q/70737697/8192914)? – ganjaam Jan 17 '22 at 07:23
11

you can view PDF in web view like this

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setDataAndType(Uri.parse( "http://docs.google.com/viewer?url=" + pdfLink), "text/html");

startActivity(intent);
Yaron Schwimmer
  • 5,327
  • 5
  • 36
  • 59
Asad Butt
  • 135
  • 1
  • 2
10

I see that you are trying this method defining the data type:

Intent intent = new Intent();
intent.setDataAndType(Uri.parse(url), "application/pdf");
startActivity(intent);

but it will cause:

ActivityNotFoundException: No Activity found to handle Intent

Use method without the type definition and it will work perfectly:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
6

you can view pdf in webview like this

WebView webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginsEnabled(true);
webView.loadUrl("https://docs.google.com/viewer?"+pdf_url);
Mahendra
  • 323
  • 2
  • 16
  • 4
    Hi, thanks for your answer - helped me a lot. But note that your code is missing the url parameter name, i.e. it should be; webView.loadUrl("https://docs.google.com/viewer?url="+pdf_url); – gts101 Jan 29 '16 at 04:06
  • 3
    i am getting no preview available – Juturu Yugandhar Oct 12 '18 at 10:28
  • hi,here along with URL i need to pass input parameters then i will get Pdf link – Kumar Sep 13 '19 at 06:37
  • @JuturuYugandhar, this solution has a limitation. it can not display large pdf. this thread contains answers regarding this issue: https://stackoverflow.com/q/39866468/8192914 – ganjaam Feb 19 '21 at 14:32
5

Download source code from here (Open Pdf from url in Android Programmatically )

MainActivity.java

package com.deepshikha.openpdf;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {
    WebView webview;
    ProgressBar progressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webview = (WebView)findViewById(R.id.webview);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        webview.getSettings().setJavaScriptEnabled(true);
        String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
        webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);

        webview.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url){
                // do your stuff here
                progressbar.setVisibility(View.GONE);
            }
        });

    }
}
Deepshikha Puri
  • 2,104
  • 22
  • 23
2

The actual error

android.content.ActivityNotFoundException: No Activity found to 
handle Intent 
{
 act=android.intent.action.VIEW 
 dat=http://oshc.zizsoft.com/oshc_testing.pdf typ=application/pdf 
}

This says that:

  1. You "broadcast" and Intent to let the system try to open a PDF file
  2. The system does not find any application registered to be able to handle this type of file (PDF)

You just need a PDF viewer of some kind.

Solution

Get a PDF reader app or use @Mahendra's solution.

Prags
  • 2,457
  • 2
  • 21
  • 38
shkschneider
  • 17,833
  • 13
  • 59
  • 112
2

If you use Intent you will be directed to browser all the Time So ,
Use PDFView Android Widget to View Pdf With in an Android application Assuming that you already have PDF Url or You can Pass the URL to this activity using Intent

Step 1 : Add Dependencies

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

Sync the Gradle

Step 2 : Create a Layout [Text View is Optional]

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ViewPdf">




    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/ViewPdf"
        android:layout_height="match_parent"
        android:layout_width="match_parent"

        />

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="invisible"
        />
</RelativeLayout>

Step 3 : Here is the Activity.java files code , Add URL to pdfUrl variable in middle of the code

package com.example.firebase;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.media.Image;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.webkit.WebView;
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;

public class ViewPdf extends AppCompatActivity {

    private TextView txt; // You can remove if you don't want this
    private PDFView pdf;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pdf);
        pdf = findViewById(R.id.ViewPdf);
        txt = findViewById(R.id.txt);

        //Intent inten = getIntent();
        String pdfUrl = "Add PDF url"
        //Toast.makeText(this, pdfUrl, Toast.LENGTH_SHORT).show();


        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();
        }
    }
}

STEP 4 : Don't Forget to change / Give the pdf url in above code to make it work

Be Champzz
  • 391
  • 3
  • 6
  • Thank You @Be Champzz you solved my biggest issue Code really working smooth just i will add progress bar to know how much % percent pdf loaded – abhilash kaveriappa Feb 26 '22 at 00:19
1

you can try this. it works for both .pdf and .docx

 String pdfUrl = "abc.pdf"; //
 String url = "http://docs.google.com/gview?embedded=true&url=" + pdfUrl;

 WebView webView = findViewById(R.id.webview_cv_viewer);
 webView.getSettings().setSupportZoom(true);
 webView.getSettings().setJavaScriptEnabled(true);
 webView.loadUrl(url);
Dinesh Sarma
  • 461
  • 3
  • 14
1

With kotlin using anko, simply call

 context.browse(PDF_URL)

to open any doc file, your browser will redirect you to the doc viewer app.

If you want to use Google Docs, then append your pdf url as,

"http://docs.google.com/viewer?url=$PDF_URL"
Aziz
  • 1,976
  • 20
  • 23
1

View document using below method by default application in device. Here url is the docuement url.

val browserIntent = Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse(url)
            )
            (view.context as AppActivity).startActivity(browserIntent)
1

You can follow this

 Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(URL_HERE));
            startActivity(intent);
Harry Potter
  • 184
  • 1
  • 6
-1

you can use the SkewPdfView library for loading pdf from remote urls.

First of all, Add following in your root build.gradle:

allprojects {
repositories {
    ...
    maven { url 'https://jitpack.io' }
}

}

and add the SkewPdfView Library as:

dependencies {
    implementation 'com.github.naya-aastra:SkewPdfView:1.1'
}

Now Include SkewPdfView in your layout:

<com.nayaastra.skewpdfview.SkewPdfView
    android:id="@+id/skewPdfView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Load a PDF file programmatically as:

SkewPdfView skewPdfView;
skewPdfView = findViewById(R.id.skewPdfView);
skewPdfView.loadPdf(pdfLink);

P.S. link of SkewPdfView library

SkewPdfView Github Page