如何从资产文件夹打开pdf文件

时间:2018-07-09 17:25:28

标签: android

点击按钮尝试从资产文件夹打开pdf文件

12345345,56891235,1245  
8963,12568745

通过传递按钮的字符串值

12345345,56891235,  
12458963,12568745

2 个答案:

答案 0 :(得分:0)

您可以通过四个步骤完成此操作

第1步:在项目中创建资产文件夹,然后将PDF放入其中

::例如:assets / MyPdf.pdf

第2步:将以下代码放在您的课​​程[onCreate]中:

<Project>/bin/*
<Project>/obj/*

第3步:将以下代码放入布局中:

Button read = (Button) findViewById(R.id.read);


// Press the button and Call Method => [ ReadPDF ]
read.setOnClickListener(new OnClickListener() {
       public void onClick(View view) {
            ReadPDF();
    }
    });
    }
    private void ReadPDF()
    {
        AssetManager assetManager = getAssets();
        InputStream in = null;
        OutputStream out = null;
        File file = new File(getFilesDir(), "MyPdf.pdf"); //<= PDF file Name
        try
        {
            in = assetManager.open("MyPdf.pdf"); //<= PDF file Name
            out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
            copypdf(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
        PackageManager packageManager = getPackageManager();
        Intent testIntent = new Intent(Intent.ACTION_VIEW);
        testIntent.setType("application/pdf");
        List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
        if (list.size() > 0 && file.isFile()) {
            //Toast.makeText(MainActivity.this,"Pdf Reader Exist !",Toast.LENGTH_SHORT).show();
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(
                Uri.parse("file://" + getFilesDir() + "/MyPdf.pdf"),
                "application/pdf");
            startActivity(intent);
            }
            else {
            // show toast when => The PDF Reader is not installed !
            Toast.makeText(MainActivity.this,"Pdf Reader NOT Exist !",Toast.LENGTH_SHORT).show();
            }
        }
        private void copypdf(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1)
        {
            out.write(buffer, 0, read);
        }
    }
}

第4步权限

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <Button
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Read PDF !"
        android:id="@+id/read"/>

</LinearLayout>

仅此而已:)

祝你好运!

答案 1 :(得分:0)

Android Q更新

这是一个较旧的问题,但是由于新的文件访问权限/系统,Android Q进行了一些更改。现在,不再可能仅将PDF文件存储在公共文件夹中。我通过在应用程序数据/数据的cache文件夹中创建PDF文件的副本来解决此问题。这种方法不再需要权限WRITE_EXTERNAL_STORAGE

打开PDF文件:

fun openPdf(){
    // Open the PDF file from raw folder
    val inputStream = resources.openRawResource(R.raw.mypdf)

    // Copy the file to the cache folder
    inputStream.use { inputStream ->
        val file = File(cacheDir, "mypdf.pdf")
        FileOutputStream(file).use { output ->
            val buffer = ByteArray(4 * 1024) // or other buffer size
            var read: Int
            while (inputStream.read(buffer).also { read = it } != -1) {
                output.write(buffer, 0, read)
            }
            output.flush()
        }
    }

    val cacheFile = File(cacheDir, "mypdf.pdf")

    // Get the URI of the cache file from the FileProvider
    val uri = FileProvider.getUriForFile(this, "$packageName.provider", cacheFile)
    if (uri != null) {
        // Create an intent to open the PDF in a third party app
        val pdfViewIntent = Intent(Intent.ACTION_VIEW)
        pdfViewIntent.data = uri
        pdfViewIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        startActivity(Intent.createChooser(pdfViewIntent, "Choos PDF viewer"))
    }
}

provider_paths.xml中的提供程序配置,用于访问您自己的应用程序外部的文件。这样可以访问cache文件夹中的所有文件:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <cache-path
        name="cache-files"
        path="/" />
</paths>

在您的AndroidManifest.xml

中添加文件提供者配置
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths" />
</provider>

可以通过仅复制一次文件并检查文件是否已经存在并替换它来增强此功能。由于打开PDF并不是我应用程序的主要部分,因此我只将其保存在缓存文件夹中,并在用户每次打开PDF时覆盖它。