2013-02-12 59 views
0

我有一个PDF文件存储在我的资产中。我想从我的资产中加载PDF并在应用程序本身中阅读它,而无需使用任何第三方应用程序进行查看。从资产中加载PDF文件到应用程序

我在这里得到了解决方案link。从sdcard中选择文件时它工作正常。

+0

你认为从资产文件夹中的文件复制到SD卡中加载? – Pallavi 2013-02-12 11:07:32

+0

是的,我已经试过 – Goofy 2013-02-12 11:11:15

+0

检查[this](https://stackoverflow.com/questions/47647784/trying-to-open-pdf-file-from-assets-folder-using-fileprovider-but-it-gives- filen?answertab = active#tab-top“这会帮助你”)! one – 2017-12-05 13:22:37

回答

2

下面的代码片段可以帮助你从asset文件夹访问文件,然后打开它:

private void ReadFromAssets() 
{ 
    AssetManager assetManager = getAssets(); 

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

    startActivity(intent); 
} 

copyFile方法如下:

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

编辑

为此目的你将不得不使用一个永恒的图书馆。它在下面的链接中解释得很好: Render a PDF file using Java on Android

希望这会对你有所帮助。

+0

是的,这将工作,但只安装了外部应用程序 – Goofy 2013-02-12 11:09:01

+0

请参阅现在编辑。 – 2013-02-12 11:18:38

+0

是的,我看到我正在使用PDFViewer库,但是你没有解释如何实现,你能帮我解决这个问题,在GitHib的 – Goofy 2013-02-12 11:21:12

1

它的更好,如果你能使用的WebView

WebView web = (WebView) findViewById(R.id.webView1); 

web.loadUrl("file:///android_asset/yourpdf.pdf"); 

希望工程打开它。

哎呀,我刚才检查时,PDF无法在Web视图 对不起

+1

没有伙伴它昂贵的做法,也需要一些时间来加载哪些用户不能等待 – Goofy 2013-02-12 11:23:36

相关问题