DImuthuUpe/AndroidPdfViewer

Issue with Tap Location and Page Number Mapping in PDFView

Ahsan2408 opened this issue · 0 comments

Hi,

I'm using the android-pdf-viewer library to display a PDF and capture tap events. However, I'm facing an issue with accurately determining the page number and coordinates within the page based on a tap.

Problem Description
When I tap on the PDF, I want to get the page number and the coordinates of the tap relative to the PDF page. I've noticed that the calculated page number sometimes does not correspond correctly to the actual page being tapped.

Code Snippet
Here is the code I'm using to handle tap events:

private void displayPdf(Uri uri, int page) {
try {
pdfView.recycle();
InputStream inputStream = getContentResolver().openInputStream(uri);
pdfView.fromStream(inputStream)
.defaultPage(page) // Set the page here
.scrollHandle(new DefaultScrollHandle(getApplicationContext()))
.enableAntialiasing(true)
.autoSpacing(false)
.enableDoubletap(false)
.spacing(1)
.pageFitPolicy(FitPolicy.WIDTH)
.onTap(new OnTapListener() {
@OverRide
public boolean onTap(MotionEvent e) {
handleTap(e);
return true; // Returning true means the tap event is consumed
}
})
.enableAnnotationRendering(true)
.load();
} catch (Exception e) {
e.printStackTrace();
}
}

private void handleTap(MotionEvent event) {
float tapX = event.getX();
float tapY = event.getY();

// Calculate the vertical offset in the PDFView
float offsetY = pdfView.getCurrentYOffset() + tapY;

// Get the page number based on the offset
int pageNumber = pdfView.getPageAtOffset(-offsetY);

// Calculate the scale
float zoom = pdfView.getZoom();

// Convert tap coordinates to PDF coordinates
float pdfX = tapX / zoom;
float pdfY = tapY / zoom;

// Get the page dimensions in PDF points
float pageWidth = pdfView.getMeasuredWidth();
float pageHeight = pdfView.getMeasuredHeight();

// Adjust coordinates to the actual PDF page coordinates
float pageX = (pdfX / pdfView.getWidth()) * pageWidth;
float pageY = (pdfY / pdfView.getHeight()) * pageHeight;

// Debug output
Toast.makeText(this, "Page: " + pageNumber + ", X: " + pageX + ", Y: " + pageY, Toast.LENGTH_SHORT).show();

// Add annotation
//here the function call for add annotation on pdf

}

Observations
The pageNumber sometimes does not match the actual page being tapped.
The PDFViewerWidth and PDFViewerHeight differ from pageWidth and pageHeight, causing inconsistencies.
Steps to Reproduce
Load a multi-page PDF document.
Tap on different pages and observe the debug output for page number and coordinates.
Expected Behavior
The pageNumber should correspond accurately to the tapped page.
The coordinates should match the position on the actual PDF page.
Actual Behavior
The pageNumber is sometimes incorrect.
The coordinates do not accurately reflect the position on the PDF page.
Any guidance or suggestions to resolve this issue would be greatly appreciated.

Thank you!