从项目的原始文件夹中读取 .pdf
Posted
技术标签:
【中文标题】从项目的原始文件夹中读取 .pdf【英文标题】:Reading .pdf from raw folder in project 【发布时间】:2014-08-28 05:04:17 【问题描述】:我正在尝试从我的资产文件夹中读取 .pdf 文件,错误显示“无法打开此文档”。我尝试将 .pdf 文件复制到 sd 卡,然后从那里读取,但没有成功。这是代码。请帮帮我。
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File fileBrochure = new File("/sdcard/fleetman.pdf");
if (!fileBrochure.exists())
CopyAssetsbrochure();
/** PDF reader code */
File file = new File("/sdcard/fleetman.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(MainActivity.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("fleetman.pdf"))
InputStream in = null;
OutputStream out = null;
try
in = assetManager.open(files[i]);
out = new FileOutputStream("/sdcard/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
break;
catch(Exception e)
Log.e("tag", e.getMessage());
【问题讨论】:
【参考方案1】: try this, hope it ll help you
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CopyReadPDFFromAssets();
private void CopyReadPDFFromAssets()
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "pdfdemofile.pdf");
try
in = assetManager.open("pdfdemofile.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyPdfFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
catch (Exception e)
Log.e("exception", e.getMessage());
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/pdfdemofile.pdf"),
"application/pdf");
startActivity(intent);
private void copyPdfFile(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" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
【讨论】:
@gautamjoshi 那么请给我UpVote:P 我会给你 10 个 UpVotes。但收视率问题。给我你的电子邮件ID。如果我在某些问题上遇到困难会咨询你..:P ;) 或者你可以通过 joshi.gautam.2203@gmail.com 给我发邮件 只要你能做到就可以了以上是关于从项目的原始文件夹中读取 .pdf的主要内容,如果未能解决你的问题,请参考以下文章
从 PDF 文件中提取 CropBox 作为 MediaBox 并保留原始字体