I had various problems with the answers, so I pulled together something that works.
LAYOUT
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:id="@+id/image_pdf"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/btn_okay"
android:layout_margin="5dp"/>
<Button
android:id="@+id/btn_okay"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="10dp"
android:text="@string/ok"/>
</RelativeLayout>
CODE
/**
* Render a page of a PDF into ImageView
* @param targetView
* @throws IOException
*/
private void openPDF(ImageView targetView) throws IOException {
//open file in assets
ParcelFileDescriptor fileDescriptor;
String FILENAME = "your.pdf";
// Create file object to read and write on
File file = new File(getActivity().getCacheDir(), FILENAME);
if (!file.exists()) {
AssetManager assetManager = getActivity().getAssets();
FileUtils.copyAsset(assetManager, FILENAME, file.getAbsolutePath());
}
fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
//Display page 0
PdfRenderer.Page rendererPage = pdfRenderer.openPage(0);
int rendererPageWidth = rendererPage.getWidth();
int rendererPageHeight = rendererPage.getHeight();
Bitmap bitmap = Bitmap.createBitmap(
rendererPageWidth,
rendererPageHeight,
Bitmap.Config.ARGB_8888);
rendererPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
targetView.setImageBitmap(bitmap);
rendererPage.close();
pdfRenderer.close();
}
public static boolean copyAsset(AssetManager assetManager, String fromAssetPath, String toPath) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(fromAssetPath);
new File(toPath).createNewFile();
out = new FileOutputStream(toPath);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
return true;
} catch(Exception e) {
e.printStackTrace();
return false;
}
}
public static void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}