我想在android中读取PDF文件。我将PDF文件放在assets文件夹中。
我怎么从那里读取PDF文件?
我检查了上面的链接,但它对我不起作用。它给我一个错误,说没有找到活动。
我还想在WebView中打开一个PDF文件。那么可以在WebView中阅读PDF吗?
您需要一个可以支持该mimetype并打开它的应用程序。在你的设备/模拟器中没有安装应用程序,因此它会抛出错误
你可以下载PDFbox API来阅读android中的PDF试试这个链接:http://pdfbox.apache.org/
使用外部安装的应用程序(如Adobe Reader
)阅读pdf的另一个很好的解决方案。
private void openPDF(final String pathToPDF) {
File file = new File(pathToPDF);
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "application/pdf");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show();
}
}
谷歌缓存显示格式,如pdf,ppt,docx等。您根本不需要安装任何应用程序。搜索谷歌中的链接,然后转到缓存。
private void openPDF(final String path) {
File file = new File(path);
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
uri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
} else {
uri = Uri.fromFile(file);
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show();
}
}