Search code examples
c#winformspdfpdfium

Get mouse position on PDF document displayed in PDFium viewer on click


I have a Windows Forms application where a user is supposed to open a PDF, then click on any place on said PDF and a stamp should appear where the user has clicked.

I am using PdfRenderer from PDFiumViewer for rendering the PDF and iText7 to create the stamp.

One things I struggle with, is getting the mouse position relative to the displayed PDF. PDF is zoomable, and you can scroll up and down. For now, I have tried this:

 private void pdfRenderer_MouseClick(object sender, MouseEventArgs e)
 {
     var args = (MouseEventArgs)e;
     clickX = args.X;
     clickY = args.Y;
     zoomFactor = pdfRenderer.Zoom;            

     float pdfX = (float)(clickX / zoomFactor);
     float pdfY = (float)(clickY / zoomFactor);

where pdfX and pdfY are coordinates inside PDF. But this does not work. Another solution I thought of, is maybe always resizing the renderer, so that renderer width is always equal to PDF page width, but not sure if this is the right way. Is it possible to implement this idea, or is it better to do it somehow else?


Solution

  • I was able to finally get it working.

    private void pdfRenderer_MouseClick(object sender, MouseEventArgs e)
    {
        var args = (MouseEventArgs)e;
        _clickX = e.Location.X;
        _clickY = e.Location.Y;
    
        Point DevicePoint = new Point((int)_clickX, (int)_clickY);
        PdfPoint PDFpoint = pdfRenderer.PointToPdf(DevicePoint);
    
        float pdfX = PDFpoint.Location.X;
        float pdfY = PDFpoint.Location.Y;
    

    This gives you X and Y coordinates on PDF file. Works with different zoom factors and multiple pages loaded.