Android: Open a Pdf from My App Using the Built in Pdf Viewer

android: open a pdf from my app using the built in pdf viewer

AFAIK, Adobe has not documented any public Intents it wants developers to use.

You can try an ACTION_VIEW Intent with a Uri pointing to the file (either on the SD card or MODE_WORLD_READABLE in your app-local file store) and a MIME type of "application/pdf".

How to open a PDF from an Android app (in a separate PDF viewer app)

Here's the solution that worked for me. It's a class called PdfHandler and here's how you use it - just put the pdf file in the assets folder. It will open it in a PDF viewer app if one is available, and if not show a warning message and direct the user to the Adobe Reader Play Store entry.

PdfHandler pdf = new PdfHandler(this);
pdf.openPdf("document.pdf");

The PdfHandler class. You should move text resources into Android string resources.

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.net.Uri;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
* Handles the opening of PDF files, using whatever app the user has installed to view PDFs
* If no PDF app installed, shows a warning and directs them to appropriate Store listing
*/
public class PdfHandler {

public PdfHandler(Context context) {
this.context = context;
}

public void openPdf(String filename) {
if (isPdfAppAvailable()) {
copyPdfAndOpenIt(filename);
} else {
showPdfWarning();
}
}

private void copyPdfAndOpenIt(String filename) {
try {
File file = copyPdfFromAssetsToStorage(filename);
startPdfIntent(file);
} catch (Exception e) {
Log.e("PdfHandler", "Error handling the PDF file", e);
}
}

private File copyPdfFromAssetsToStorage(String filename) throws Exception {
String tempFilename = "temp.pdf";
AssetManager is = context.getAssets();
InputStream inputStream = is.open(filename);
String outFilename = context.getFilesDir() + "/" + tempFilename;
FileOutputStream outputStream = context.openFileOutput(tempFilename, Context.MODE_WORLD_READABLE);
copy(inputStream, outputStream);
outputStream.flush();
outputStream.close();
inputStream.close();
return new File(outFilename);
}

private void copy(InputStream fis, FileOutputStream fos) throws IOException {
byte[] b = new byte[8];
int i;
while ((i = fis.read(b)) != -1) {
fos.write(b, 0, i);
}
}

private boolean isPdfAppAvailable() {
PackageManager packageManager = context.getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}

private void startPdfIntent(File file) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
context.startActivity(intent);
}

private void showPdfWarning() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Please install an app to view PDF file");
builder.setCancelable(false);
builder.setPositiveButton("Install", getButtonListener());
builder.setNegativeButton("Cancel", null);
builder.setTitle("PDF Viewer");
AlertDialog alert = builder.create();
alert.show();
}

private DialogInterface.OnClickListener getButtonListener() {
return new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
goToGooglePlayStoreEntry();
}
};
}

private void goToGooglePlayStoreEntry() {
context.startActivity(getAppListingIntent());
}

private Intent getAppListingIntent() {
Intent intent = new Intent(Intent.ACTION_VIEW);
String pdfAppPackageName = "com.adobe.reader";
intent.setData(Uri.parse("market://details?id=" + pdfAppPackageName));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}

private Context context;

}

Show PDF file in App

Android provides PDF API now with which it is easy to present pdf content inside application.

you can find details here

Below is the sample snippet to render from a pdf file in assets folder.

    private void openRenderer(Context context) throws IOException {
// In this sample, we read a PDF from the assets directory.
File file = new File(context.getCacheDir(), FILENAME);
if (!file.exists()) {
// Since PdfRenderer cannot handle the compressed asset file directly, we copy it into
// the cache directory.
InputStream asset = context.getAssets().open(FILENAME);
FileOutputStream output = new FileOutputStream(file);
final byte[] buffer = new byte[1024];
int size;
while ((size = asset.read(buffer)) != -1) {
output.write(buffer, 0, size);
}
asset.close();
output.close();
}
mFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
// This is the PdfRenderer we use to render the PDF.
if (mFileDescriptor != null) {
mPdfRenderer = new PdfRenderer(mFileDescriptor);
}
}

update: This snippet is from google developers provided samples.

Open online pdf file through android intent?

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

Cannot open PDF file in external app

Ok guys, problem solved!

This is the code that i use to open a PDF file, stored on external memory:

File pdfFile = new File(Environment.getExternalStorageDirectory(),"namePdfFile.pdf");//File path
if (pdfFile.exists()) //Checking if the file exists or not
{
Uri path = Uri.fromFile(pdfFile);
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setDataAndType(path, "application/pdf");
objIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP);
startActivity(objIntent);//Starting the pdf viewer
} else {

Toast.makeText(getActivity(), "The file not exists! ", Toast.LENGTH_SHORT).show();

}

Open a selected file (image, pdf, ...) programmatically from my Android Application?

Try the below code. I am using this code for opening a PDF file. You can use it for other files also.

File file = new File(Environment.getExternalStorageDirectory(),
"Report.pdf");
Uri path = Uri.fromFile(file);
Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenintent.setDataAndType(path, "application/pdf");
try {
startActivity(pdfOpenintent);
}
catch (ActivityNotFoundException e) {

}

If you want to open files, you can change the setDataAndType(path, "application/pdf"). If you want to open different files with the same intent, you can use Intent.createChooser(intent, "Open in...");. For more information, look at How to make an intent with multiple actions.

Android download PDF from URL then open it with a PDF reader

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.

Sample Image

Sample Image

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>


Related Topics



Leave a reply



Submit