【问题标题】:How to view pdf from assets or raw folder?如何从资产或原始文件夹中查看 pdf?
【发布时间】:2016-11-28 06:15:11
【问题描述】:

我正在使用 MuPDF 库在我的应用程序中显示 pdf.. 可以查看保存在内部或外部存储器中的 PDF,但如果它们存储在应用程序的资产文件夹中,则应用程序不会显示 pdf... 如何在应用内查看 PDF?

我见过一些解决方案说我们可以将我们的应用内 PDF 复制到应用相关的文件夹中,然后稍后再使用它们...... 但我无法理解..

这是代码 -

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

【问题讨论】:

  • 确实可以将文件复制到内部存储中,然后打开它。你不知道该怎么做吗?
  • @VladMatvienko 不,我是 android 新手,所以我无法理解...你能举个代码示例吗?
  • @sasikumar 我已经看过了。我可以理解他们如何将 pdf 保存在文件夹中,但如何阅读它?
  • 所以你的问题真的是how to copy file from assets to internal storage,对吧?你为什么不问你真正想要什么?由于两个原因,我真的无法在这个问题中给你举个例子:1.我的答案与你的问题不符。 2. StackOverflow 上已经有数百个回答你的问题

标签: android mupdf


【解决方案1】:

试试下面的代码

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

确保包含

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

在清单中

【讨论】:

  • 如果上面的代码对你有帮助,请接受答案并投票
  • 对不起,忘记投票了。我不能接受这个答案,因为问题不是我的。很抱歉
猜你喜欢
  • 1970-01-01
  • 2011-03-03
  • 1970-01-01
  • 1970-01-01
  • 2011-07-19
  • 2018-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多