javascripthtmlcssprintingmedia-queries

"@media print" - QR code shows up with CTRL-P but not with window.print()


I would like to add a QR code when someone prints a page from our website. I have added the following embedded CSS:

@media print {
    body:after {
        content: "Convenient QR code to return to this page ..." url(https://image-charts.com/chart?chs=100x100&cht=qr&chl=https://<?=$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];?>&choe=UTF-8);
    }
}

This is working perfectly when someone uses CTRL-P and the text and QR code appear at the bottom of the page. However, when someone uses the button I provide for "Printer Friendly" — which simply executes window.print() — all that appears at the bottom of the page is the text ... no QR code. I tried printing the page thinking it may be a print preview issue but the QR code did not appear on the page (Note: When printing using CTRL-P the QR code does show up).

In essence, I am asking why there is a difference between CTRL-P and window.print() and what I can do to correct the situation. I have searched for solutions and only found a couple of references in Stack Overflow (53758720 and 7928963) but they were not addressing the same issue. Any help will be appreciated.


Solution

  • You need to ensure that the image has loaded before the print function is run (i.e. before that content styling takes place).

    One way of doing that is to make it the src of an img element which is then displayed none.

    Here's a simple example:

    <style>
      @media print {
        body::after {
          content: "Convenient QR code to return to this page ..." url(https://image-charts.com/chart?chs=100x100&cht=qr&chl=https://stackoverflow.com&choe=UTF-8);
        }
      }
    </style>
    
    <body>
      <img src="https://image-charts.com/chart?chs=100x100&cht=qr&chl=https://stackoverflow.com&choe=UTF-8">
      <button onclick="window.print();">Print</button>
      <script>
        document.querySelector('img').style.display = 'none';
      </script>
    
    </body>

    Note: the service providing the QR code may take some time to create the image and serve it to you so I wouldn't rely on a timeout to make sure it's loaded. You should probably tidy up the above code by waiting on a load event for a production bit of code.