简体   繁体   English

如何从Android应用程序打开本地PDF文件

[英]How to open a local PDF file from an Android application

I'm trying to open a PDF file out of my Android application using Adobe Reader. 我正在尝试使用Adobe Reader从我的Android应用程序中打开PDF文件。 When my code gets excecuted, the Adobe Reader opens but throws the following error: 'Error: The document path is not valid' The file blabla.pdf is in my Application rootfolder 当我的代码被激活时,Adobe Reader会打开,但会抛出以下错误: '错误:文档路径无效'文件blabla.pdf在我的应用程序根文件夹中

String filename = "blabla.pdf";
File file = new File(filename);
Uri internal = Uri.fromFile(file);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(internal, "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

intent = Intent.createChooser(target, "Open File");
try {
    startActivity(intent);
} catch (ActivityNotFoundException e) {
    Toast.makeText(this, "U hebt geen PDF viewer geïnstalleerd op dit toestel. " +
        "Ga naar de app store en download een PDF viewer om dit bestand te openen.", Toast.LENGTH_LONG).show();
}
startActivity(intent);

I want to use internal storage, not external storage. 我想使用内部存储,而不是外部存储。 I've used this example: Link and didn't really understand these 2 examples: Link1 and Link2 我使用过这个例子: Link并没有真正理解这两个例子: Link1Link2

1)First copy the file to internal storage. 1)首先将文件复制到内部存储器。 -> Keep your pdf file in assets folder.Use follwing function to copy file to internal storage - >将您的pdf文件保存在assets文件夹中。使用follwing函数将文件复制到内部存储

private void copy( InputStream in, File dst ) throws IOException {
    FileOutputStream out = new FileOutputStream( dst );
    byte[] buf = new byte[1024];
    int len;

    while ( ( len = in.read( buf ) ) > 0 ) {
        out.write( buf, 0, len );
    }

    in.close( );
    out.close( );
}

function call for the same : 函数调用相同:

File f = new File( getContext( ).getFilesDir( ), "abc.pdf" );
AssetManager assets = getContext( ).getResources( ).getAssets( );
copy( assets.open( "abc.pdf" ), f );

2)Now you have your file in internal storage so use following code to get file object 2)现在您将文件放在内部存储中,因此请使用以下代码来获取文件对象

File f = new File( getContext( ).getFilesDir( )+"/"+abc.pdf);

Use below code to check whether the file path is correct or not 使用下面的代码检查文件路径是否正确

if(file.exists()){
  //file path is correct 
}else{
  //file path is not correct 
}

You must set full path to file. 您必须设置文件的完整路径。 Like in example you shown 就像你展示的例子一样

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);

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

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