【问题标题】:how to open pdf file from assets folder如何从资产文件夹中打开pdf文件
【发布时间】:2018-12-17 11:00:36
【问题描述】:

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

public class CodSecreen extends AppCompatActivity {
    PDFView pdfView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cod_secreen);
        pdfView=(PDFView)findViewById(R.id.pdf);
        Intent intent = getIntent();
        String str = intent.getStringExtra("message");
        if (str.equals(getResources().getString(R.string.introduction))){
            pdfView.fromAsset("phpvariable.pdf").load();
        }
    }
}

通过传递按钮的字符串值

bttn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String str = bttn1.getText().toString();
            Intent i=new Intent(DetailSecreen.this,CodSecreen.class);
            startActivity(i);
        }
    });

【问题讨论】:

标签: android


【解决方案1】:

Android Q 更新

这是一个较老的问题,但由于新的文件访问权限/系统,Android Q 有一些变化。现在不再可能只将 PDF 文件存储在公共文件夹中。我通过在我的应用程序的 data/data 的 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 时覆盖它。

【讨论】:

    【解决方案2】:

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

    第 1 步:在您的项目中创建 assets 文件夹并将 PDF 放入其中

    :: 例如:assets/MyPdf.pdf

    第 2 步:将以下代码放入您的类 [onCreate]:

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

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

    <?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>
    

    第 4 步权限

        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    就是这样:)

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-06
      • 2017-12-12
      • 2014-08-25
      • 2015-07-22
      • 2010-12-28
      • 1970-01-01
      • 2018-01-19
      • 1970-01-01
      相关资源
      最近更新 更多