9

Does any one has an idea on how to open a PDF file in Android? My code looks this this:

public class SampleActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); CopyReadAssets(); } private void CopyReadAssets() { AssetManager assetManager = getAssets(); InputStream in = null; OutputStream out = null; File file = new File(getFilesDir(), "git.pdf"); try { in = assetManager.open("git.pdf"); out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE); copyFile(in, out); in.close(); in = null; out.flush(); out.close(); out = null; } catch (Exception e) { Log.e("tag", e.getMessage()); } Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType( Uri.parse("file://" + getFilesDir() + "/git.pdf"), "application/pdf"); startActivity(intent); } private void copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } } 
5
  • You can look at this link: stackoverflow.com/questions/6491210/… Commented Oct 15, 2012 at 5:20
  • check out this stackoverflow.com/questions/6491210/… Commented Oct 15, 2012 at 5:32
  • @sai please specify what problem ur facing, i.e. any exception/error, or app displays list of available pdf Viewer list? Commented Oct 15, 2012 at 6:08
  • 1
    You might wish to log the Uri you are trying to use, as I suspect it is not the value that you think it is. Commented Oct 15, 2012 at 10:44
  • Duplicate: stackoverflow.com/questions/17085574/… Commented Apr 15, 2014 at 8:46

1 Answer 1

2

Here is the code for opening pdf file from asset folder, but you must have pdf reader installed on your device :

 private void CopyAssets() { AssetManager assetManager = getAssets(); InputStream in = null; OutputStream out = null; File file = new File(getFilesDir(), "fileName.pdf"); try { in = assetManager.open("fileName.pdf"); out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE); copyFile(in, out); in.close(); in = null; out.flush(); out.close(); out = null; } catch (Exception e) { Log.e("tag", e.getMessage()); } Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType( Uri.parse("file://" + getFilesDir() + "/fileName.pdf"), "application/pdf"); startActivity(intent); } private void copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

This answer is essentially copied verbatim from this one: stackoverflow.com/questions/17085574/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.