7heViking
7heViking

Reputation: 7587

How to get the number of pages of a pdf file in Android?

Can you help me find out the number of pages of a pdf document on Android, that will support down to at least api version 16. I am extracting document information but can't see a solution to get the total amount of pages. This Is what I doo so far:

private void extractDocumentDataFromUri(Uri uri)
    {
        String[] dataFileds = new String[]{
                MediaStore.MediaColumns.DATA,
                OpenableColumns.DISPLAY_NAME,
                OpenableColumns.SIZE};

        Cursor cursor = context.getContentResolver().query(uri, dataFileds, null, null, null);
        cursor.moveToFirst();

        contentUrl = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA));
        title = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
        size = cursor.getInt(cursor.getColumnIndex(OpenableColumns.SIZE));

        cursor.close();

        contentType = context.getContentResolver().getType(uri);
    }

Upvotes: 4

Views: 5403

Answers (2)

pm dubey
pm dubey

Reputation: 1016

Try this:

private void countPages(File pdfFile) throws IOException {
    try {
       
        ParcelFileDescriptor parcelFileDescriptor = ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY);
        PdfRenderer pdfRenderer = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            pdfRenderer = new PdfRenderer(parcelFileDescriptor);
            totalpages = pdfRenderer.getPageCount();
            pdfRenderer.close()
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

Upvotes: 7

Krupa Patel
Krupa Patel

Reputation: 3359

This solution works if you add the iTextG library to your libs folder. The library contains a class called PdfReader.

Try something like this:

PdfReader reader = new PdfReader("Your file path");
int aa = reader.getNumberOfPages();

Upvotes: 3

Related Questions