Can you detect when a PDF is printed or downloaded from the browser PDF viewer?

后端 未结 3 1495
我寻月下人不归
我寻月下人不归 2021-02-20 00:10

We have an AngularJS web app that loads PDF documents from the server and displays them within the page like this:

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-20 00:57

    Unfortunately, you can not append any script to the PDF window because it is from MIME type "application/pdf".

    If you load some PDF in your Chrome browser and then look into developer console you will see some code like follows:

    
    

    I have tried to add some script into PDF window like follows:

    
    
    
    
    

    But it does nothing because the MIME type is "application/pdf".

    You can detect the print events only for HTML-documents like follows:

    function beforePrint(){alert('before print')}
    
    function afterPrint(){alert('after print')}
    
    if(window.onafterprint !== void 0)
    {
        window.onbeforeprint = beforePrint;
        window.onafterprint = afterPrint;
    }
    else if(window.matchMedia)
    {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener(function(mql)
        {
            if(mql.matches)
                beforePrint();
            else afterPrint()
        });
    }
    

    For more details into and what it can be used for you can read this article.

    May be you can use this code but I think not for this case.

    Because of all this you can write a solution only if you write your own PDF viewer. You can use PDF.js for example for this goal. PDF.js is Portable Document Format (PDF) viewer that is written in JavaScript. It is open source and you can download the full source code on GitHub here.

    And for download is the same (only with your own PDF viewer), but I would like to recomend to read following links:

    • Detect when browser receives file download.
    • The onCreated() event of the downloads API

    And may be with my answer you could save your time!

提交回复
热议问题