All I need to do is take a (locally saved) PDF-document and convert one or all of it\'s pages to image format like JPG or PNG.
I\'ve tr
from below code, you can extract all pages as image (PNG) format from PDF using PDFRender:
// This method is used to extract all pages in image (PNG) format.
private void getImagesFromPDF(File pdfFilePath, File DestinationFolder) throws IOException {
// Check if destination already exists then delete destination folder.
if(DestinationFolder.exists()){
DestinationFolder.delete();
}
// Create empty directory where images will be saved.
DestinationFolder.mkdirs();
// Reading pdf in READ Only mode.
ParcelFileDescriptor fileDescriptor = ParcelFileDescriptor.open(pdfFilePath, ParcelFileDescriptor.MODE_READ_ONLY);
// Initializing PDFRenderer object.
PdfRenderer renderer = new PdfRenderer(fileDescriptor);
// Getting total pages count.
final int pageCount = renderer.getPageCount();
// Iterating pages
for (int i = 0; i < pageCount; i++) {
// Getting Page object by opening page.
PdfRenderer.Page page = renderer.openPage(i);
// Creating empty bitmap. Bitmap.Config can be changed.
Bitmap bitmap = Bitmap.createBitmap(page.getWidth(), page.getHeight(),Bitmap.Config.ARGB_8888);
// Creating Canvas from bitmap.
Canvas canvas = new Canvas(bitmap);
// Set White background color.
canvas.drawColor(Color.WHITE);
// Draw bitmap.
canvas.drawBitmap(bitmap, 0, 0, null);
// Rednder bitmap and can change mode too.
page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
// closing page
page.close();
// saving image into sdcard.
File file = new File(DestinationFolder.getAbsolutePath(), "image"+i + ".png");
// check if file already exists, then delete it.
if (file.exists()) file.delete();
// Saving image in PNG format with 100% quality.
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
Log.v("Saved Image - ", file.getAbsolutePath());
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can call this method in below way:
// Getting images from Test.pdf file.
File source = new File(Environment.getExternalStorageDirectory() + "/" + "Test" + ".pdf");
// Images will be saved in Test folder.
File destination = new File(Environment.getExternalStorageDirectory() + "/Test");
// Getting images from pdf in png format.
try {
getImagesFromPDF(source, destination);
} catch (IOException e) {
e.printStackTrace();
}
Cheers!