Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure images load before generating PDF?

I have a PHP loop that does the following:

  1. Log in to a web page via CURL
  2. Capture and internal page that requires a login
  3. Save the HTML of the page to a local file
  4. Using WKHTMLTOPDF, render the page as a PDF

The issue I'm having is that every once in a while (maybe ~30% of the time), the images won't render in the PDF. If I open up one of the saved HTML files, I'll find that I need to go in and manually refresh the page for the images to show up.

Any ideas on how to pragmatically ensure the images load? Things I've tried:

  1. sleep(n) between each and every line
  2. Adding --javascript-delay 30000 to my WKHTMLTOPDF call to ensure it has ample time to load any images.

#1 made it considerably worse, and #2 did nothing at all.

Thanks!

like image 467
Chords Avatar asked May 07 '12 15:05

Chords


People also ask

How can you tell if an image is loaded?

Using attributes of <img> to check whether an image is loaded or not. The attributes we will use are: onload: The onload event is triggered when an image is loaded and is executed. onerror: The onerror event is triggered if an error occurs during the execution.

How do I make multiple images into a PDF?

Simply visit the Acrobat Online website and upload the files you want to merge. Reorder the files however you like and then click Merge files. After that, just download the merged PDF. This will combine all the JPGs-turned-PDFs into a single PDF you can easily share or view.

How images are loaded in browser?

Images on a webpage can be loaded in two ways - using the <img> tag, or using the CSS `background` property. Let's first look at the more common of the two, the <img> tag, and then move on to CSS background images.

How do I load an image after loading a page?

The Postify jQuery plugin provides an elegant way to lazy load images that load specific images after the main part of your webpage has been loaded. The plugin provides 7 built-in showup animations for images when they're loaded and rendered in the document.


1 Answers

Between step 3 & 4 of your example you might want to consider parsing the HTML file for all image links and downloading them individually using curl, saving them locally as well and then updating the links in the saved HTML file to point to the new local image resources instead of the remote ones.

This should drastically improve the load time of images when rendering the HTML as a PDF.

like image 81
stevecomrie Avatar answered Oct 26 '22 05:10

stevecomrie