简体   繁体   English

如何从资产或原始文件夹查看pdf?

[英]How to view pdf from assets or raw folder?

I am using the MuPDF library to display pdf in my app.. It is possible to view PDFs saved in internal or external memories but the App doesn't show the pdf if they are stored in assets folder of the app... How to view in app PDFs? 我正在使用MuPDF库在应用程序中显示pdf。可以查看保存在内部或外部存储器中的PDF,但如果将PDF存储在应用程序的资产文件夹中,则该应用程序不显示pdf。在应用PDF中查看?

I've seen solutions which say thatbwe can copy our in app PDFs in app associated folder and then use them later on... but I can't get that.. 我见过一些解决方案,其中说我们可以将我们的应用程序PDF复制到应用程序关联的文件夹中,然后在以后使用它们...但是我听不到。

here's the code - 这是代码-

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button showPDFBtn = (Button)findViewById(R.id.btn_show_pdf);
        showPDFBtn.setOnClickListener(new View.OnClickListener() {
                 @Override
                 public void onClick(View view) {

        Uri uri = Uri.parse("file:///android_asset/test.pdf");
        Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(uri);
        startActivity(intent);



}}
  );
  }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
}

Try below code 试试下面的代码

 private void readAssetAndMakeCopy()
    {
        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);
        }
    }

Make sure to include 确保包括

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

in manifest 在清单中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM