open a pdf file programmatically

后端 未结 7 2116
广开言路
广开言路 2021-01-06 15:45

I am working on pdf. I am trying to open a pdf file from my application using the code below. But I failed to open.

private void openPdf() {

        File fi         


        
相关标签:
7条回答
  • 2021-01-06 16:10

    I got solution of above problem, so try once;

    Steps:-

    1. create assets folder in src under your app name.

    2. In this assets folder keep your pdf files e.g. schedule1.pdf.

    3. now come your activity i.e MainActivity.java

    4. setListener on any UI component what you want i.e (Button, ImageView, ImageButton);

    5. In this listener call one user defined method i.e. openPDFFiles()

    the openPDFFiles() method have below code:

    private void openPDFFiles() {
        AssetManager assetManager = getAssets();
    
        InputStream in = null;
        OutputStream out = null;
        File file = new File(getFilesDir(), “schedule1.pdf”);//here schedule1.pdf is the pdf file name which is keep in assets folder.
        try {
            in = assetManager.open(“schedule1.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() + “/schedule1.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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题