在上传到服务器之前,我正在尝试给用户预览PDF。我正在使用PdfRenderer。我只是想预览一下第一页。在Start上,我调用了文件选择器函数,该函数允许您从Internal memory中选择pdf文件,在ActivityResult上调用了render函数,但是,我面临一个错误
I/System.out: Cursor= android.content.ContentResolver$CursorWrapperInner@a8d29d4
Uri String= content://com.adobe.scan.android.documents/document/root%3A23
File pathcontent://com.adobe.scan.android.documents/document/root%3A23
W/System.err: java.lang.IllegalArgumentException: Invalid page index
at android.graphics.pdf.PdfRenderer.throwIfPageNotInDocument(PdfRenderer.java:282)
at android.graphics.pdf.PdfRenderer.openPage(PdfRenderer.java:229)
at com.ay404.androidfileloaderreader.CustomFunc.Main2Activity.openPdfFromStorage(Main2Activity.java:56)
这是我的代码:
@RequiresApi(api=Build.VERSION_CODES.LOLLIPOP)
private void openPdfFromStorage(Uri uri,String filename) throws IOException {
File fileCopy = new File(getCacheDir(), filename);//anything as the name
copyToCache(fileCopy, uri);
ParcelFileDescriptor fileDescriptor =
ParcelFileDescriptor.open(fileCopy,
ParcelFileDescriptor.MODE_READ_ONLY);
mPdfRenderer = new PdfRenderer(fileDescriptor);
mPdfPage = mPdfRenderer.openPage(1);
Bitmap bitmap = Bitmap.createBitmap(mPdfPage.getWidth(),
mPdfPage.getHeight(),
Bitmap.Config.ARGB_8888);//Not RGB, but ARGB
mPdfPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
imageView.setImageBitmap(bitmap);
}
void copyToCache(File file,Uri uri) throws IOException {
if (!file.exists()) {
InputStream input = getContentResolver().openInputStream(uri);
FileOutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int size;
while ((size = input.read(buffer)) != -1) {
output.write(buffer, 0, size);
}
input.close();
output.close();
}
}
RequiresApi(api=Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
Uri uri = data.getData();
String uriString=uri.toString();
File myFile=new File(uriString);
String displayName=null;
Cursor cursor=null;
Log.e("URI: ", uri.toString());
try {
if (uriString.startsWith("content://")) {
try {
cursor=getApplicationContext().getContentResolver().query(uri, null, null, null, null);
System.out.println("Cursor= " + cursor);
System.out.println("Uri String= " + uriString);
System.out.println("File path" + data.getData());
if (cursor != null && cursor.moveToFirst()) {
displayName=cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
openPdfFromStorage(uri,displayName);
File imgFile=new File(String.valueOf(data.getData()));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
System.out.println("Uri String= " + uriString);
System.out.println("File path" + myFile.getAbsolutePath());
displayName=myFile.getName();
try {
openPdfFromStorage(uri,displayName);
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void fileChoser(){
Intent intent=new Intent();
intent.setType("application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PICK_PDF_REQUEST);
}
@Override
protected void onStart() {
super.onStart();
fileChoser();
}
}
找到修复程序,路径需要是静态的,因此,我将文件复制到缓存,然后从缓存位置打开它们
private void showPdf(String base64, String filename) {
String fileName = "test_pdf ";
try {
final File dwldsPath = new File(this.getExternalFilesDir(String.valueOf(this.getCacheDir()))+"/"+filename);
Log.d("File path", String.valueOf(dwldsPath));
byte[] pdfAsBytes = Base64.decode(base64, 0);
FileOutputStream os;
os = new FileOutputStream(dwldsPath, false);
os.write(pdfAsBytes);
os.flush();
os.close();
Uri uri = FileProvider.getUriForFile(this,
BuildConfig.APPLICATION_ID + ".provider",
dwldsPath);
fileName="";
String mime = this.getContentResolver().getType(uri);
openPDF(String.valueOf(dwldsPath),fileName);
} catch(Exception e){
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}