ACTION_CREATE_DOCUMENT is used to create a new document. If one already existed, it will be overwritten. If you want to view an existing document, use ACTION_VIEW.

Of course none of the code you posted actually downloads a PDF. If you need help with that, post your DownloadManager code.

Answer from Gabe Sechan on Stack Overflow
🌐
Mindorks
blog.mindorks.com › how-to-open-a-pdf-file-in-android-programmatically
How to open a PDF file in Android programmatically? - MindOrks
June 17, 2019 - In our tutorial, we will learn how to open a PDF file from Assets, Phone Storage, and from the Internet by using the AndroidPdfViewer library. Also, we will be using PRDownloader library by MindOrks to download files from the Internet and open ...
Discussions

android - how to: download and open a pdf file programmatically via http connection - Stack Overflow
how to: download (via an http connection) and open or save a pdf file programmatically. Say I have a button on my screen and the url to the pdf, when the button is clicked I want to download the... More on stackoverflow.com
🌐 stackoverflow.com
storage - Saving PDF in external Download directory on Android 11 - Stack Overflow
In android 11 scoped storage is introduced. According to documentation to save non media file (like PDF) Storage Access framework should be use. So using Storage access framework user needs to choose More on stackoverflow.com
🌐 stackoverflow.com
How to download a pdf file in Android? - Stack Overflow
There is no need to put lengthy code to open and download pdf in android you can just use below code to open and download pdf More on stackoverflow.com
🌐 stackoverflow.com
My App with Android 11 doesn't load PDF file
You can have a try to add permission in AndroidManifest.xml and RequestPermissions. In addition, you can check if there is any isue with the pdf file. More on learn.microsoft.com
🌐 learn.microsoft.com
1
0
July 5, 2021
Top answer
1 of 4
88

Hi the problem is in FileDownloader class

 urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);

You need to remove the above two lines and everything will work fine. Please mark the question as answered if it is working as expected.

Latest solution for the same problem is updated Android PDF Write / Read using Android 9 (API level 28)

Attaching the working code with screenshots.

MainActivity.java

package com.example.downloadread;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public void download(View v)
    {
        new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf"); 
    }

    public void view(View v)
    {
        File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "maven.pdf");  // -> filename = maven.pdf
        Uri path = Uri.fromFile(pdfFile);
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try{
            startActivity(pdfIntent);
        }catch(ActivityNotFoundException e){
            Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
        }
    }

    private class DownloadFile extends AsyncTask<String, Void, Void>{

        @Override
        protected Void doInBackground(String... strings) {
            String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
            String fileName = strings[1];  // -> maven.pdf
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, "testthreepdf");
            folder.mkdir();

            File pdfFile = new File(folder, fileName);

            try{
                pdfFile.createNewFile();
            }catch (IOException e){
                e.printStackTrace();
            }
            FileDownloader.downloadFile(fileUrl, pdfFile);
            return null;
        }
    }


}

FileDownloader.java

package com.example.downloadread;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FileDownloader {
    private static final int  MEGABYTE = 1024 * 1024;

    public static void downloadFile(String fileUrl, File directory){
        try {

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            //urlConnection.setRequestMethod("GET");
            //urlConnection.setDoOutput(true);
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while((bufferLength = inputStream.read(buffer))>0 ){
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.downloadread"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.downloadread.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="15dp"
        android:text="download"
        android:onClick="download" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="38dp"
        android:text="view"
        android:onClick="view" />

</RelativeLayout>
2 of 4
10

This is the best method to download and view PDF file.You can just call it from anywhere as like

PDFTools.showPDFUrl(context, url);

here below put the code. It will works fine

 public class PDFTools {
    private static final String TAG = "PDFTools";
    private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
    private static final String PDF_MIME_TYPE = "application/pdf";
    private static final String HTML_MIME_TYPE = "text/html";

   
    public static void showPDFUrl(final Context context, final String pdfUrl ) {
        if ( isPDFSupported( context ) ) {
            downloadAndOpenPDF(context, pdfUrl);
        } else {
            askToOpenPDFThroughGoogleDrive( context, pdfUrl );
        }
    }

   
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
        // Get filename
        //final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
        String filename = "";
        try {
            filename = new GetFileInfo().execute(pdfUrl).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        // The place where the downloaded PDF file will be put
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
        Log.e(TAG,"File Path:"+tempFile);
        if ( tempFile.exists() ) {
            // If we have downloaded the file before, just go ahead and show it.
            openPDF( context, Uri.fromFile( tempFile ) );
            return;
        }

        // Show progress dialog while downloading
        final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true );

        // Create the download request
        DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
        r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
        final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
        BroadcastReceiver onComplete = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ( !progress.isShowing() ) {
                    return;
                }
                context.unregisterReceiver( this );

                progress.dismiss();
                long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
                Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

                if ( c.moveToFirst() ) {
                    int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                    if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                        openPDF( context, Uri.fromFile( tempFile ) );
                    }
                }
                c.close();
            }
        };
        context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

        // Enqueue the request
        dm.enqueue( r );
    }

    
    public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
        new AlertDialog.Builder( context )
                .setTitle( R.string.pdf_show_online_dialog_title )
                .setMessage( R.string.pdf_show_online_dialog_question )
                .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
                .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        openPDFThroughGoogleDrive(context, pdfUrl);
                    }
                })
                .show();
    }

    public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
        context.startActivity( i );
    }
    
    public static final void openPDF(Context context, Uri localUri ) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        i.setDataAndType( localUri, PDF_MIME_TYPE );
        context.startActivity( i );
    }
    
    public static boolean isPDFSupported( Context context ) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
        i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
        return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
    }

    // get File name from url
    static class GetFileInfo extends AsyncTask<String, Integer, String>
    {
        protected String doInBackground(String... urls)
        {
            URL url;
            String filename = null;
            try {
                url = new URL(urls[0]);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                conn.setInstanceFollowRedirects(false);
                if(conn.getHeaderField("Content-Disposition")!=null){
                    String depo = conn.getHeaderField("Content-Disposition");

                    String depoSplit[] = depo.split("filename=");
                    filename = depoSplit[1].replace("filename=", "").replace("\"", "").trim();
                }else{
                    filename = "download.pdf";
                }
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
            }
            return filename;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // use result as file name
        }
    }

}

try it. it will work, enjoy

🌐
The Code City
thecodecity.com › home › android › download pdf from any url in android studio – solution
Download PDF From Any URL in Android Studio – Solution
May 13, 2023 - In conclusion, downloading PDF files from any URL in Android Studio is a simple process that can be done using either the view intent or the download manager. Both methods are effective, and the choice depends on your app’s requirements. With the knowledge and tools provided in this guide, you’ll be able to download PDF files programmatically and save them to internal storage in no time.
🌐
GitHub
github.com › MindorksOpenSource › Open-PDF-File-Android-Example
GitHub - MindorksOpenSource/Open-PDF-File-Android-Example: An example project to demonstrate how to open a PDF file in Android programmatically · GitHub
This project contains a sample ... following in this project: ... Download file from the internet using the PRDownloader library and then open that file using the AndroidPdfViewer library...
Starred by 70 users
Forked by 18 users
Languages   Kotlin
🌐
YouTube
youtube.com › programmer world
How to create and read a PDF file in your Android 11 App? - YouTube
This video shows the steps to create and read a PDF file in an Android 11 App. It uses iTextpdf library for reading the PDF file and PdfDocument API from and...
Published   October 30, 2021
Views   6K
Find elsewhere
🌐
Android Developers
developer.android.com › api reference › pdfdocument
PdfDocument | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-download-file-from-url-in-android-programmatically-using-download-manager
How to Download File from URL in Android Programmatically using Download Manager? - GeeksforGeeks
May 23, 2021 - import android.app.DownloadManager; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { Button button; DownloadManager manager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.download); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { manager
🌐
Android Knowledge
androidknowledgeblog.wordpress.com › 2016 › 04 › 02 › download-pdf-from-server-android › comment-page-1
Download pdf from server android – Android Knowledge
April 9, 2016 - Note : You can Download any file from this link i tested (PDF,ZIP,IMAGES). Step 2 : Create project with empty activity project name->PDFDownloadDemo and copy this code into your MainActivity.java · import java.io.File; import java.io.IOException; import android.app.Activity; import android.app.ProgressDialog; import android.content.ActivityNotFoundException; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.View; import android.widget.Toast; public class Main
🌐
Coderzheaven
coderzheaven.com › 2013 › 03 › 06 › download-pdf-file-open-android-installed-pdf-reader
How to Download a PDF File and open it in Android using an installed PDF Reader? – CoderzHeaven
March 6, 2013 - Here is the complete program that shows how to download a PDF File and open it in Android using an installed PDF Reader.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-load-pdf-from-url-in-android
How to Load PDF from URL in Android? - GeeksforGeeks
April 1, 2025 - */ private class LoadPdfTask extends AsyncTask<String, Void, InputStream> { @Override protected InputStream doInBackground(String... strings) { return fetchPdfStream(strings[0]); } @Override protected void onPostExecute(InputStream inputStream) { if (inputStream != null) { pdfView.fromStream(inputStream).load(); } else { Toast.makeText(MainActivity.this, "Failed to load PDF. Check your internet connection.", Toast.LENGTH_SHORT).show(); } } } /** * Fetches the PDF InputStream from the given URL. * Uses HTTPS connection to securely download the PDF file.
🌐
Stack Overflow
stackoverflow.com › questions › 67006892 › saving-pdf-in-external-download-directory-on-android-11
storage - Saving PDF in external Download directory on Android 11 - Stack Overflow
According to documentation to save non media file (like PDF) Storage Access framework should be use. So using Storage access framework user needs to choose location with system file picker to save non media file (PDF).
🌐
Android Developers
developer.android.com › core areas › app data and files › access documents and other files from shared storage
Access documents and other files from shared storage | App data and files | Android Developers
Furthermore, on Android 11 (API level 30) and higher, you cannot use the ACTION_OPEN_DOCUMENT_TREE intent action to request that the user select individual files from the following directories: The Android/data/ directory and all subdirectories. The Android/obb/ directory and all subdirectories. After the user has selected a file or directory using the system's file picker, you can retrieve the selected item's URI using the following code in onActivityResult():
🌐
Blogger
zacktutorials.blogspot.com › 2014 › 07 › android-downloading-and-viewing-pdf.html
Zack Tutorials: Android Downloading and Viewing a PDF File Example
July 15, 2014 - This tutorial is about downloading a pdf file and viewing it using an Android APP. In this example we will be downloading the pdf file i...
🌐
Nutrient
nutrient.io › android › miscellaneous › from a remote url
Open PDF from URL on Android | Nutrient SDK
Open PDF documents from any URL on Android using Nutrient Android SDK. Learn to implement different methods for downloading and managing remote files efficiently.
🌐
UPDF
updf.com › home › best ways to save pdfs on android in 2026
Top Ways To Save PDFs on Android in 2026 | UPDF
January 3, 2026 - Look for the option to export or save the PDF file. It may be located in the app's menu or within the PDF viewer itself. When prompted to choose a location, select the desired folder or directory.