Receiving the pdf file with AJAX

4,168 views
Skip to first unread message

mills

unread,
Aug 17, 2011, 3:46:31 PM8/17/11
to dompdf
Hi,

How can I receive a newly created pdf file using XMLHttpRequest?

In javascript do I use:
xmlHttpRequest.setRequestHeader('Content-Type', 'application/pdf');

instead of:
xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-
form-urlencoded');

What else do I need to change?

I'm trying to display the pdf in a new tab. AJAX is used to send data
and have a progress bar. I'm just unsure how this is done with files.

Thanks :)

BrianS

unread,
Aug 17, 2011, 10:02:51 PM8/17/11
to dompdf
The request header indicates what you're sending to your server. That
should stay as application/x-www-form-urlencoded.

I won't say it's not possible to retrieve the PDF via AJAX, but you're
asking for more work trying to find a way to present it via
JavaScript. You could maybe even do what you want without even using
AJAX. However, sticking to what you asked one method would be to have
the server create the PDF and save it in a web-accessible location.
What the server would then return would be the location of the PDF,
which your client-side script would use to, for example, generate an
iframe that uses the returned PDF location for the src attribute.

That's one way to handle this.

mills

unread,
Aug 18, 2011, 8:19:38 AM8/18/11
to dompdf
Yes I can do that with a temporary file. Thank you!

Another way I noticed that might be possible is to send back a string
with all the pdf data.

Using this:

$output = $dompdf->output();
echo $output;

When I receive that string client side is there a way I can use it to
display the pdf?

BrianS

unread,
Aug 18, 2011, 1:58:49 PM8/18/11
to dom...@googlegroups.com
On Thursday, August 18, 2011 8:19:38 AM UTC-4, mills wrote:
Another way I noticed that might be possible is to send back a string
with all the pdf data.

Using this:

$output = $dompdf->output();
echo $output;

When I receive that string client side is there a way I can use it to
display the pdf?

That's where things get tricky. It's difficult to deal with displaying binary data via JavaScript, especially if the data has to be rendered by a plug-in. One method that may work would be to base64 encode your PDF when you send it to the browser. Then when you embed it in the document you can use a data URI for the src reference.

But I'm not sure if that would actually work.

mills

unread,
Aug 18, 2011, 3:32:48 PM8/18/11
to dompdf
Wow thank you so much! That worked perfectly and exactly how I wanted!

Cheers :D
Reply all
Reply to author
Forward
Message has been deleted
0 new messages