7

i have a link in my main page that uses ajax to retrieve a PDF which is displayed in an Iframe, i am trying to detect scroll event of the PDF document and display a message or do something. i have tried different solutions from other solutions on stackoverflow and google search in general and couldn't find a good solution.

Main.php

 <html>
 <!--ajax request-->
 <script type="text/javascript">
  $(document).on('click','#nextpdf',function(event) {

  event.preventDefault();

  var reg = $(this).attr("href");
  var str = reg.split('?')[1];

  $.ajax({

    type: "GET",
    url: '../functions/pdfreader.php',
    data: 'pdfxs='+str+'',
    cache:false,
      async: false,
     success: function(data) {
   // data is ur summary
  $('.refresh').html(data);
  return false;
        }

   });//end of ajax

      });


</script>
  <?php

     while($obj = $c_content->fetch())
 {
   $title = $obj['lecture_title'];

    echo '<article class="comment2">

    //pdf link
   <div class="comment2-body">
<div class="text" style="color:#999;padding-right:130px;">
  <p><a href="../functions/pdfreader.php?'.$title.'"" 
  style="color:#999" id="nextpdf">'.$title.'</a></p>
   </div>
</div>
 </article>
   ';

    }

    ?>
    </html>

pdfreader.php

//detect iframe pdf scroll
               <script type="text/javascript">
     $("myiframe").load(function () {
     var iframe = $("myiframe").contents();

     $(iframe).scroll(function () { 
      alert('scrolling...');
        });
           });
        </script>

  <?php



         ........
        while($obj = $gettrend->fetch())
    {
       $coursefile = $obj['lecture_content'];
          //this is my iframe
       echo '<div class="mov_pdf_frame"><iframe id="myiframe"
      src="https://localhost/einstower/e-learn/courses/pdf/'.$coursefile.'" 
      id="pdf_content"
     width="700px" height="800px" type="application/pdf">
       </iframe></div>';
             }
                 ?>

The major problem here is that nothing happens when i scroll the pdf document, how can i detect scrolling?

i found this fiddle that works but i cant view the javascript solution. http://fiddle.jshell.net/czw8pbvj/1/

  • Maybe related: https://stackoverflow.com/q/43264078/1531971 (If not maybe [edit] the question to explain why not.) –  Feb 20 '18 at 15:20
  • No accepted answer for that question, i also tried the solution with the most votes and it didn't work. – Alexander Omoruyi Feb 20 '18 at 15:24
  • "it didn't work" Maybe share what this means? Assume no one knows in the slightest what you are trying to do. –  Feb 20 '18 at 15:25
  • Nothing just happens, i've checked the web console but no errors – Alexander Omoruyi Feb 20 '18 at 15:27
  • Also: https://stackoverflow.com/q/33154598/1531971 or https://stackoverflow.com/q/36193354/1531971 Basically, you are going to have to help out here by showing your research; it's just how it works. Someone is going to have to feel interested in answering, and this partly relies on knowing what groundwork has been done. What we need is to grok what it is about your case that makes those solutions not work for you. –  Feb 20 '18 at 15:29
  • In desperation you might need to resort to a third-party that handles the ugly details for you. Maybe something like https://pdfobject.com/ –  Feb 20 '18 at 15:33
  • i have done alot of research on this as i mentioned in the question, i've seen different methods all of which where never accepted as an answer and also didnt work for me. – Alexander Omoruyi Feb 20 '18 at 15:36
  • Well, you've _said_ you did a lot of research, but you didn't _show_ it. Given how little interest those others answers generated, I'm suggesting how you can make this question better. I mean, if there is a solution it will require going from the known to the unknown by testing your assumptions. Of interest is how those other solutions failed. Inspect the DOM. Use a debugger. Issue print statements to see if and when code is entered. All we see here is that something is not working. (Or figure it out and submit your own answer and be a SO hero.) –  Feb 20 '18 at 15:41
  • i found this fiddle that works but i cant view the javascript solution. http://fiddle.jshell.net/czw8pbvj/1/ – Alexander Omoruyi Feb 20 '18 at 15:47
  • Essentially the user is not scrolling the iframe but the pdf reader within it. Attaching an eventhandler to the reader is not possible. PDF.js would be a work around. Would you accept, if I post an example? – Thomas Feb 24 '18 at 19:29
  • Yes please. I’ve tried tracking progress with pdf.js but I couldn’t get it to work properly. Also in your example can you show how to store the progress in a variable. I would like to retrieve that value and store it in a database. Thanks – Alexander Omoruyi Feb 24 '18 at 20:45

5 Answers5

2

First off, $("myiframe") isn't finding anything, so it attaches a load event to nothing. 1) change it to $("#myiframe") or $("iframe").

Here's a working fiddle (for iframe scroll detection)


UPDATE: to detect the scroll within PDF document, you can't use iframe. For that, you need embed or object tags AND a JS-enabled PDF document (hopefully its your PDFs..), who can send messages to your page's JS (see this answer).

Unfortunately, I couldn't find a scroll event in Adobe's Acrobat API Reference. It lists only these events:

Event type: Event names

App: Init

Batch: Exec

Bookmark: Mouse Up

Console: Exec

Doc: DidPrint, DidSave, Open, WillClose, WillPrint, WillSave

External: Exec

Field: Blur, Calculate, Focus, Format, Keystroke, Mouse Down, Mouse Enter, Mouse Exit, Mouse Up, Validate

Link: Mouse Up

Menu: Exec

Page: Open, Close

Screen: InView, OutView, Open, Close, Focus, Blur, Mouse Up, Mouse Down, Mouse Enter, Mouse Exit


So, basically, I think what you want just isn't possible as for now, at least with default rendering. With custom rendering (https://github.com/mozilla/pdf.js) it could be possible, though I'm not sure.

Apparently, it could be done with page scroll (see this issue). So back to iframes solution. :^D

Bernardo Dal Corno
  • 1,858
  • 1
  • 22
  • 27
  • True, I only focus on correction of your code. I will update my answer, but check [this](https://stackoverflow.com/a/19123741) and [this one](https://stackoverflow.com/a/5942729) – Bernardo Dal Corno Mar 01 '18 at 14:09
1

Please try this

iframe.on( "scroll", handler ) 
Priya
  • 1,410
  • 14
  • 22
1

Because this question is asked a long time ago, i think i need to help with my experience before.

The answer is: You can not

Why? because PDF is rendered by external apps, such as adobe pdf reader, foxit or else. And you can not attach event on them.

if you are using adobe reader, The only you can do is goto page, change zoom etc. Full example you can read here: https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf#page=8 (see. i bring you to page 8 directly instead to first page).

But, hei.. how if our client using another apps? we will confused more


The way to do this is only build your own pdf viewer.

we can using js library, like: http://www.bestjquery.com/2012/09/best-jquery-pdf-viewer-plugin-examples/

but here i only will show you to use pdf.js which created by mozilla.

main.php

<style>
.preview{
    display:none;
    width: 400px;
    height: 400px;
    border: 1px solid black;
}

</style>
<a href="pdfreader.php?pdfxs=test.pdf" style="color:#999;" id="nextpdf">file/test.pdf</a><br>
<a href="pdfreader.php?pdfxs=test1.pdf" style="color:#999;" id="nextpdf">file/test1.pdf</a><br>
<div class="preview">
    <iframe id="myiframe" frameborder="0" width="400px" height="400px" >not support iframe</iframe>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    $(document).on('click', '#nextpdf', function(e){
        e.preventDefault();
        $('#myiframe').attr('src', $(this).attr('href'));
        $('.preview').show();
    });

    //handle iframe on scroll
    $('#myiframe').on('load', function () {
        $(this).contents().scroll(function () { 
            console.log('scrolled');
        }).click(function(){
            console.log('clicked');
        });
    });

});


</script>

pdfreader.php

<?php 
$path = 'file/';
$pdf = isset($_GET['pdfxs']) ? $path . $_GET['pdfxs'] : '';
if(!file_exists($pdf) ||  !mime_content_type($pdf) =='application/pdf') die('file not found');
?>
<div id="pdf-container">
    <div id="pdf-box"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>

<script>
$(function(){

    //original script : https://gist.github.com/fcingolani/3300351
    function renderPDF(url, canvasContainer, options) {
        var options = options || { scale: 1 };

        function renderPage(page) {
            var viewport = page.getViewport(options.scale);
            var canvas = $(document.createElement('canvas'));
            var renderContext = {
              canvasContext: canvas[0].getContext('2d'),
              viewport: viewport
            };
            canvas.attr('width', viewport.width).attr('height', viewport.height);

            canvasContainer.append(canvas);
            page.render(renderContext);
        }

        function renderPages(pdfDoc) {
            for(var num = 1; num <= pdfDoc.numPages; num++)
                pdfDoc.getPage(num).then(renderPage);
        }
        PDFJS.disableWorker = true;
        PDFJS.getDocument(url).then(renderPages);
    }

    renderPDF('<?=$pdf;?>', $('#pdf-box'));
});
</script>

Note: i put pdf on folder file/

in main.php you will notice that you can attach event scroll (and click too) to the pdf. because our pdf is not rendered by external apps now.

and the last part is, if you read pdfreader.php carefully, you will notice that you no need iframe anymore. You just need div, and then you can fully handle all event that do you want to your pdf : like scroll, click, change page, zoom, etc. why?? because your pdf is redered as canvas now (pdf.js render your pdf as HTML5 canvas). see full example of pdf.js

plonknimbuzz
  • 2,594
  • 2
  • 19
  • 31
  • Thanks for taking the time to answer, i've just implemented your answer but i cant find anything on the web console to indicate that the event is detected, can you update the code to use `alert('scrolling...');` i've tried using alert but it didnt pop up while scrolling. – Alexander Omoruyi Mar 02 '18 at 16:47
0
$("#frame").scroll(function () {
    if ($(window).scrollTop() == $(document).height() - $(window).height())
        alert('Bottom reached');
});

I found this in the JSFiddle that was referenced in the Fiddle you linked. The HTML field is empty. This CSS was in there, too.

body {
    height: 1500px;
}

In the fiddle that you linked, the <iframe> has an ID of frame. I figured you can use the jQuery selector like $("#frame").

Tanner Babcock
  • 3,232
  • 6
  • 21
  • 23
0

I think this will help you.

$("#myiframe").load(function () {
    $(this).contents().scroll(function () {
        //your code here
    });
});
Mukesh
  • 150
  • 1
  • 10