Reputation: 184
I need a clear solution of how to get the number of pages from a PDF file in android. Assuming the person has selected the file then on the onActivityResult(), I want to know how many pages the PDF file is. I would love a solution that will work for minSdkVersion 19 and would not need me paying for any PDF manipulation software, because I have checked round the net and there is no clear solution. Please it will be well appreciated because I really need the solution. I am using it with Firebase and want to upload the number of pages of the PDF as I also upload the file.
Here is a sample code, I used PDF Box: The error I keep getting is 08-10 21:07:57.533 20514-20514/com.example.android.firebaseupload E/file: Error: End-of-File, expected line I had to put in the file path manually before now and it has been the same error even after typing the file path manually. How do I load a pdf file from a path into the PDDocument.load()??
try {
PDDocument doc = PDDocument.load("file:///storage/emulated/0/Boom%20Player/cache/c2#.pdf".getBytes());
Toast.makeText(MainActivity.this,"Number of pages: "+doc.getNumberOfPages(),Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Log.e("file",e.getMessage().toString());
}
Upvotes: 2
Views: 4179
Reputation: 184
Found the solution, instead of calling getpath() on the Uri and trying to open it with new file(Uri.getPath()), I Call openInputStream() to get an InputStream from the Uri. Wonderful help here ... getContentResolver().openInputStream(uri) Android: Getting a file URI from a content URI?:) Also thanks the link https://commonsware.com/blog/2016/03/15/how-consume-content-uri.html for making me understand more.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==pickimage && resultCode==RESULT_OK && data!=null && data.getData()!=null)
{
filepath=data.getData();...//rest of code...
PDDocument doc = PDDocument.load(getContentResolver().openInputStream(filepath));//main line
Upvotes: 2
Reputation: 31
PDFBox is the Java equivalent to what you are asking. There's a port of it for Android, though I'm not sure how complete it is.
An example would be:
PDDocument myDocument = PDDocument.load(new File("filename.pdf"));
int numPages = myDocument.getNumberOfPages();
Upvotes: 1