[SalesForce] Embedding Dynamic Images in VF Page that renders as PDF

I would like to know how can we embed an image that's got as a response from an external service. It works fine in a VF page but when renderAs="PDF" is given, the image is broken since the page renders before the response is got from the external server.

Edit :

This is what I've tried and its working. I send a http request to the external server and i get a response which I store as an attachment using response.getBodyAsBlob() and set the ContentType to 'png' and save it.

Now that it's working I've another doubt. Since the call to external server might get delayed response, if I send the call out in constructor or 'action parameter in <apex:page>', the page will take time to load and render as PDF.

Since the delay is unavoidable, is there a way to set a kind of timer in apex to limit the time the request can wait for response?

Best Answer

Regarding your edit to the question: yes, you can specify callout timeouts.

http://wiki.developerforce.com/page/Apex_Web_Services_and_Callouts#Additional_Considerations

// SOAP callouts - code generated from WSDL will have timeout_x variable.
// Modify it in said class (for all callouts) or only in controller of your specific page.
docSample.DocSamplePort stub = new docSample.DocSamplePort();
stub.timeout_x = 2000; // timeout in milliseconds

// REST callouts
HttpRequest req = new HttpRequest();
req.setTimeout(2000); // timeout in milliseconds

To be honest I've never had broken images from callouts (maybe they were completing before the timeout). I'd expect the PDF rendering engine to wait (straightforward img tag like in https://salesforce.stackexchange.com/a/10713/799).

If you're hitting timeouts then either leave your updated code as is or maybe split it into 2 actions "fetch image, store as attachment" and "compile PDF with latest image"?