Prevent Printing with Control-P

It’s possible to prevent the print dialog from appearing when the Control-P keyboard shortcut is used.

You can listen to the keydown event in the capture phase, and if the Control-P shortcut combination (Command-P on Mac) is detected, call both event.preventDefault() and event.stopImmediatePropagation() to prevent both PSPDFKit from printing and the default print 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.

This involves some extra work in IE11, like blocking the main thread so as to prevent the default print 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 (⌘ on 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.