Tuesday, September 16, 2014

Print preview images and css not loading for first time.

While I'm trying to print one of my web pages in browser, faced a strange issue today. When I click the print button for the first time, the print preview (in chrome browser) looks like weird and no images and styles are appeared in the print preview. Where as if I click again, strangely everything is fine.


The reason is that, there is a slight difference between, loading the images,css files and the print preview. The print preview winning the race and the images and css files loading later. So when I click next time the already loaded images and css files are showing up in the print preview and everything fine.

The solution is that with help of a timer/timeout we need to wait until the css and image load. So that the images and css files load in that interval before showing up the preview. In GWT case the code looks alike

public static void printHTML(String html) {  
           try {  
                Timer timer = new Timer() {  
                     public void run() {  
                          yourPrintGoesHereWithHtml(html);  
                     }  
                };  
                timer.schedule(TIMER_DELAY * 1000);// TIMER_DELAY= 1 or 2 (based on net speed)  
           } catch (Throwable exc) {  
                Window.alert(exc.getMessage());  
           }  
      }  
Javascript solution:

The same solution applies for JavaScript as well. Instead of timer we can use setTimeOut method here.
setTimeout(function(){  
    //Your Print Function goes here  
  }, 3000); //giving 3 sec loading time. May vary.
That way we can wait to load the css and image files by browser and the print preview functionality can proceed without any problems.

Note: After so much goggling only I went for this solution. If anyone know a better idea to overcome this problem, please comment. It would be great if anyone come up with a solution without a timer.

Post a Comment