我已经使用了下面的代码,请检查一下。
PdfRenderer.Page page = null;
Bitmap mBitmap;
try {
descriptor = getSeekableFileDescriptor(documentPath);
renderer = new PdfRenderer(descriptor);
page = renderer.openPage(0);
Bitmap bitmap = Bitmap.createBitmap(page.getWidth(), page.getHeight(),Bitmap.Config.ARGB_8888);
page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
page.close();
renderer.close();
response.invoke(params);
} catch (SecurityException e) {
Log.e(TAG, "SecurityException exception found: " + e);
if (page != null)
page.close();
if (renderer != null)
renderer.close();
} catch (Exception e) {
Log.e(TAG, "getPDFThumbnail exception found: " + e);
if (page != null)
page.close();
if (renderer != null)
renderer.close();
}
protected ParcelFileDescriptor getSeekableFileDescriptor(String path) throws IOException {
ParcelFileDescriptor parcelFileDescriptor = null;
File pdfCopy = new File(path);
if (pdfCopy.exists()) {
parcelFileDescriptor = ParcelFileDescriptor.open(pdfCopy, ParcelFileDescriptor.MODE_READ_ONLY);
return parcelFileDescriptor;
}
parcelFileDescriptor = this.reactContext.getApplicationContext().getContentResolver().openFileDescriptor(Uri.parse(path), "r");
return parcelFileDescriptor;
}
AndroidManifest.xml
android:minSdkVersion="21"
android:targetSdkVersion="22" />
android:name=".MainApplication"
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:hardwareAccelerated="true"
android:vmSafeMode="true"
android:largeHeap="true"
android:theme="@style/AppTheme">
步骤:首先选择受密码保护的pdf文件,然后它将直接引发有效的SecurityException,但是如果我再次选择不受密码保护的普通Pdf,则还将引发SecurityException。