0

in php create pdf as string, something like this:

%PDF-1.4
(..skipping...)
/F1 9 Tf
0 g 
BT
157 830 Td
(Lorem ) Tj
ET
(..skipping...)
8 0 obj 
<</Type /Font /Encoding /WinAnsiEncoding /Subtype /Type1 /BaseFont /Helvetica >>
endobj

My php code:

//string it's pdf as plain text
return new Response($string);

In js I use ajax:

$("a#get_pdf").on('click', function(e){
    e.preventDefault();
    $.ajax('/get_pdf/');
});

How I can download this file, because I have response as plain text, don't like a file.

-----EDIT-----

I can do this, like in this answer: https://stackoverflow.com/a/34065784/4900669

-----EDIT 2----

But after some search I edit my js code(https://stackoverflow.com/a/20830337/4900669):

$("a#get_pdf").on('click', function(e){
    e.preventDefault();
    $.ajax({
        url: '/get_pdf/',
        type: 'POST',
        success: function() {
            window.location = '/get_pdf/';
        }
    });
});

And it's work perfectly.

Community
  • 1
  • 1
Ivan
  • 2,463
  • 1
  • 20
  • 28

2 Answers2

1

First of all I don't think you need to make this as ajax, just let the browser open the link in a blank window.

Then you need to fix your headers to make the download possible, reference: Symfony2 - Force file download

This should be enough to make it work! I hope it helps

Community
  • 1
  • 1
Renato Mefi
  • 2,131
  • 1
  • 18
  • 27
0

Javascript is explicitly prevented from writing files. You cannot combine an Ajax call with a file download.

You can embed a hidden iframe in the current document then point that iframe at the content which will result in the download being triggered in the browser. e.g.

$("a#get_pdf").on('click', function(e){
   e.preventDefault();
   document.getElementById('someHiddenDiv').innerHTML="<iframe src='/get_pdf/'></iframe>";
}

But you do need to set at least the mimetype in the header of the response containing the pdf file.

symcbean
  • 47,736
  • 6
  • 59
  • 94