【发布时间】:2020-11-27 06:44:23
【问题描述】:
public class PDF extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_pdf, container, false);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(intent, 1212);
return rootView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1212:
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
String uriString = uri.toString();
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
String displayName = null;
String p = uri.toString(); // "file:///mnt/sdcard/FileName.mp3"
File f = new File(uriString);
String pathhh = f.getAbsolutePath();
Log.d("rwdsvcx", pathhh);
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
Log.d("rwdscxwa", "FilePath : " + path);
cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
openPDF(path);
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
public void openPDF(String filePath){
try {
String parsedText="";
PdfReader reader = new PdfReader("/storage/emulated/0/Download/sample.pdf");
int n = reader.getNumberOfPages();
for (int i = 0; i <n ; i++) {
parsedText = parsedText+ PdfTextExtractor.getTextFromPage(reader, i+1).trim()+"\n"; //Extracting the content from the different pages
}
Log.d("rwdscxwa", parsedText);
reader.close();
} catch (Exception e) {
Log.d("rwdscxwa", ": "+e.getMessage());
}
}
}
我得到的文件路径是 /content:/com.mi.android.globalFileexplorer.myprovider/external_files/Download/sample.pdf
我什至尝试了路径 /storage/emulated/0/Download/sample.pdf
两条路径我得到相同的错误:
/storage/emulated/0/Download/sample.pdf not found as file or resource.
清单
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
我正在使用 iText 库并尝试从 PDF 中获取文本。我哪里出错了? 有没有其他好的库可以从 PDF 中获取文本?任何帮助表示赞赏
【问题讨论】: