javascript

how to disable right click in PDF file in browser

How to disable right click in PDF file in browser

1. Using PDF CDN

Copy-paste the script <script> into your <head><script src=”https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.3.200/pdf.js”></script>

2. Using jQuery CDN

Copy-paste the script <script> into your <head>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js”></script>
3. Convert PDF file to Canvas, Disable F12 and right Click on the window
<script>
window.onload = function() {
    document.addEventListener(“contextmenu”, function(e){
        e.preventDefault();
        if(event.keyCode == 123) {
        disableEvent(e);
    }
    }, false);
 function disableEvent(e) {
        if(e.stopPropagation) {
            e.stopPropagation();
        } else if(window.event) {
            window.event.cancelBubble = true;
        }
    }
}
$(document).contextmenu(function() { return false;});
url = “fileUrl”;
var thePdf = null;
var scale = 1;
pdfjsLib.getDocument(url).promise.then(function(pdf) {
          thePdf = pdf;
          viewer = document.getElementById(‘pdf-viewer’);
          for(page = 1; page <= pdf.numPages; page++) {
            canvas = document.createElement(“canvas”);
            canvas.className = ‘pdf-page-canvas’;
            viewer.appendChild(canvas);
            renderPage(page, canvas);
          }
      });
      function renderPage(pageNumber, canvas) {
          thePdf.getPage(pageNumber).then(function(page) {
            viewport = page.getViewport(scale);
            canvas.height = viewport.height;
            canvas.width = viewport.width;
            page.render({canvasContext: canvas.getContext(‘2d’), viewport: viewport});
      });
      }
</script>
4. HTML Code
 <body>
     <div id=”pdf-viewer”>
     </div>
 </body>
Note:- this file should be in the Server root folder. i.e (htdocs, www…)

5 thoughts on “how to disable right click in PDF file in browser

Leave a Reply

Your email address will not be published. Required fields are marked *