Prevent printing with Ctrl+P

Q: How can I prevent the printing dialog from appearing when the Ctrl+P keyboard shortcut is used?

A: You can listen to the keydown event in the capture phase and, if the Ctrl+P shortcut combination (or ⌘+P in Mac) is detected, call both event.preventDefault() and event.stopImmediatePropagation() to prevent both PSPDFKit printing and the default printing dialog from appearing.

Warning

Internet Explorer 11 is no longer supported in our Web SDK as of version 2022.5. Edge 18 is no longer supported in our Web SDK as of version 2023.2.

Making this work in IE11 involves some extra work, like blocking the main thread so as to prevent the default printing dialog from showing up:

PSPDFKit.load(configuration).then(instance => {
  const isIE11 = navigator.userAgent.indexOf("Trident/") > -1;
  instance.contentDocument.addEventListener(
    "keydown",
    keyDownHandler,
    isIE11
      ? {
          capture: true
        }
      : true
  );
  document.addEventListener(
    "keydown",
    keyDownHandler,
    isIE11
      ? {
          capture: true
        }
      : true
  );

  function keyDownHandler(event) {
    // Watch for `metaKey` too (⌘ in Mac)
    if ((event.ctrlKey || event.metaKey) && event.keyCode === 80) {
      // Is the browser IE11?
      if (isIE11) {
        const end = Date.now() + 4000; // block the main thread for 4s.
        while (Date.now() < end) {
          // Deliberately no-op
        }
      }

      event.preventDefault();
      event.stopImmediatePropagation();
      console.log("Ctrl+P shortcut detected");
    }
  }
});

This has been tested with PSPDFKit for Web 2020.1.2.