Load external images in print media

css, printing

Solution

After hours of experimenting I came to conclusion that as of today web browsers just don't wait for any external resources specified in print-specific stylesheets to be fully downloaded before rendering the print-ready document.

So, seems like the only way to display external resources in print version of the page is to at least download them (either via html tags, screen stylesheets or javascript, doesn't really matter how) before user decides to print that page.

And, no, seems like this is not a bug, but rather a standard accepted by current major vendors.

Problem

A heading should have an image to the right of it only when a page is printed. I declared following stylesheet: ``` @media print { h1::after { content: url( IMAGE_URL_HERE ); position: absolute; top: 0; right: 0; } } ``` The problem is that image won't appear in print preview (of any browser). If I, however, print preview dialog is closed and re-opened, image will then appear just fine. You can try to reproduce it youself: http://jsbin.com/gevefivi Is there anything I'm doing wrong or is it an expected behaviour? UPDATE: I think it is related to race condition inside engine's print layout rendering because when I refer to a local image it is always displayed in Print Preview and is printed just fine. UPDATE: Looks like print engine really doesn't wait before external resource in `content: url()` is loaded but generates PDF file for preview and that's why there is no image there if image fetch takes some time to finish. But it does send HTTP request and saves it locally for the next time. So that explains why it usually works fine when Print Preview is opened for the second time. I tested it with following PHP file as an external resource: ``` <?php sleep(5); // Create a blank image and add some text $im = imagecreatetruecolor(120, 20); $text_color = imagecolorallocate($im, 233, 14, 91); imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color); // Set the content type header - in this case image/jpeg header('Content-Type: image/jpeg'); header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); // Output the image imagejpeg($im); // Free up memory imagedestroy($im); ``` It only returns an image in 5 seconds. To reproduce this issue make sure PHP file above is located on your local server or at worst in your local network. Refer to it in `content: url()` and open the Print Preview dialog. You'll not see the image. Close the dialog. Open the dialog and you'll still not see the image. Wait 2-3 seconds. Open it and you'll see the image as it is fetched and cached. If you remove the `sleep(5);` line you should see the image from the first time you open Print Preview dialog. Still eager to know whether this is a bug or whether this is an expected behavior and if there is a working solution at the moment.

Original source