Ikk*_*kky 23 pdf android assets file
我将在我的应用程序中显示pdf,并且pdf必须与应用程序捆绑在一起.
有什么好办法呢?
我已经读过,可以通过将pdf文件添加到res/raw文件夹并从那里读取它来实现这一点,但是当我将pdf文件放在那里时我得到了项目错误.
所以我试着把pdf文件放在项目的资产文件夹中,它没有给出任何错误.
这是我试图显示pdf的方式:
File pdfFile = new File("res/raw/file.pdf");
Uri path = Uri.fromFile(pdfFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Run Code Online (Sandbox Code Playgroud)
任何想法或建议?
提前致谢
Dee*_*rma 30
您无法直接从assets文件夹打开pdf文件.您首先必须将文件从assets文件夹写入SD卡,然后从SD卡读取它.代码如下: -
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
File fileBrochure = new File(Environment.getExternalStorageDirectory() + "/" + "abc.pdf");
if (!fileBrochure.exists())
{
CopyAssetsbrochure();
}
/** PDF reader code */
File file = new File(Environment.getExternalStorageDirectory() + "/" + "abc.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try
{
getApplicationContext().startActivity(intent);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(SecondActivity.this, "NO Pdf Viewer", Toast.LENGTH_SHORT).show();
}
}
//method to write the PDFs file to sd card
private void CopyAssetsbrochure() {
AssetManager assetManager = getAssets();
String[] files = null;
try
{
files = assetManager.list("");
}
catch (IOException e)
{
Log.e("tag", e.getMessage());
}
for(int i=0; i<files.length; i++)
{
String fStr = files[i];
if(fStr.equalsIgnoreCase("abc.pdf"))
{
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open(files[i]);
out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
break;
}
catch(Exception e)
{
Log.e("tag", e.getMessage());
}
}
}
}
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);
}
}
Run Code Online (Sandbox Code Playgroud)
多数民众赞成......享受!请不要忘记给予1.谢谢
Fel*_*lix 23
您可以从中显示它raw/或者assets/您的应用程序是否实际实现了PDF阅读器.由于您希望它显示在单独的应用程序(例如Adobe Reader)中,我建议您执行以下操作:
assets/目录中.openFileOutput或getExternalFilesDir.Intent正如您现在所做的那样启动,除了getAbsolutePath()在新创建的文件上使用intent的数据.请注意,用户可能没有PDF阅读应用程序.在这种情况下,捕获ActivityNotFoundException并显示适当的消息很有用.
| 归档时间: |
|
| 查看次数: |
50762 次 |
| 最近记录: |