简体   繁体   中英

How to display a PDF in iframe with ajax after calling a servlet

I have a problem when I want to display a PDF in an iframe (using the attribute src).The PDF is never downloaded from the browser. I need to use an ajax call to display a message in a popup in some cases. The code of the servlet that generate the PDF works because currently we use this directly in the src attribute of the iframe.

 <iframe src="myServlet" />

But when I use the servlet with a ajax call, and I want to add the content of the PDF in the iframe, it doesn't work. I don't know why. This is an example of the js :

$.ajax(
{
   url: "myServlet",
   ...
   complete: function(data) {
        var blob = new Blob([data], { type: 'application/pdf' });
        var downloadUrl = URL.createObjectURL(blob);
        $('#myframe').attr("src", downloadUrl);
   }
 }
);

I try with chrome and I have the error: jquery-2.1.3.js?ts=13012017:3 GET data:application/pdf;base64,blob: http://localhost:8180/d21d82b6-8254-4a38-907e-129b3ac037fa net::ERR_INVALID_URL

I can see that I have the data as a binary file: %PDF-1.4 % 3 0 obj <>stream x {PU ^A e ( ...................... ................... startxref 38448 %%EOF

Sorry but I don't have the code here (at home), but I think that the explanations are fairly clear. I don't know why the PDF cannot be downloaded if I use ajax with iframe and attribut src. Do you have an idea?

Thanks. Fred

This do the trick for me.

$.ajax(
{
   url: "myServlet",
   ...
   complete: function(data) {
        $('#myframe').attr('src','data:application/pdf;base64,'+data);
   }
 }
);

Also, you should encode the ajax ans this way base64_encode($data) .

I hope you find this helpful.

In Javascript, to encode the ajax answer you should do it this way:

var enc = btoa(data)

If you have problems, you should try this:

var enc = btoa(unescape(encodeURIComponent(data)))

Then

 $('#myframe').attr('src','data:application/pdf;base64,'+ enc);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM