如何在Android中从资产文件夹打开PDF文件?

9

有人知道如何在Android中打开PDF文件吗?我的代码看起来像这样:

public class SampleActivity extends Activity {

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

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

您可以查看此链接:https://dev59.com/Hmw15IYBdhLWcg3wntOh - omi0301
请查看此链接:https://dev59.com/Hmw15IYBdhLWcg3wntOh - Aamirkhan
@sai,请具体说明您遇到的问题,例如是否出现任何异常/错误,或应用程序显示可用的PDF查看器列表? - Chanchal Shelar
1
你可能希望记录你尝试使用的“Uri”,因为我怀疑它不是你认为的值。 - CommonsWare
请阅读assets文件夹中的PDF文件。 - csvan
1个回答

2

以下是从资产文件夹打开pdf文件的代码,但您必须在设备上安装pdf阅读器:

    private void CopyAssets() {

        AssetManager assetManager = getAssets();

        InputStream in = null;
        OutputStream out = null;
        File file = new File(getFilesDir(), "fileName.pdf");
        try {
            in = assetManager.open("fileName.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() + "/fileName.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);
        }
    }

5
这个答案基本上是从这个网址复制的:https://dev59.com/O2Qn5IYBdhLWcg3wIUFn - csvan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接