Show PDF in Android

后端 未结 2 1408
灰色年华
灰色年华 2021-02-09 04:00

In my onCreate() I do this check:

//
// check if we have a PDF viewer, else bad things happen
//
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType(\         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-09 05:00

    -Copy the following code in your activity. Call the function CopyReadAssets("File_name.pdf") from onCreate() function. Place the File_name.pdf file in assets folder.

    private void CopyReadAssets(String pdfname)
    {
        AssetManager assetManager = getAssets();
        InputStream in = null;
        OutputStream out = null;
        File file = new File(getFilesDir(), pdfname);
        try
        {
            in = assetManager.open(pdfname);
            out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
            copyFile(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } catch (Exception e)
        {
            Toast.makeText(getApplicationContext(), "Pdf Viewer not installed", Toast.LENGTH_SHORT).show();
        }
        try
        {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(
                Uri.parse("file://" + getFilesDir() + "/"+pdfname),
                "application/pdf");
    
        startActivity(intent);
        }catch (Exception e) {
            // TODO: handle exception
            Toast.makeText(getApplicationContext(), "Pdf Viewer not installed" ,Toast.LENGTH_SHORT).show();
        }
    }
    
    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);
        }
    }
    

提交回复
热议问题