View PDF after AJAX call with TCPDF in Laravel 4

2

After I save information to the database using the following code.

$this->anamnese->create($input);

I just call to test a code to generate a test PDF with the following code.

PDF::SetTitle('Hello World');
PDF::AddPage();
PDF::Write(0, 'Hello World');

$name = '/test.pdf';

$headers = array(
      'Content-Type: application/pdf',
    );

$filename = storage_path() . $name;

PDF::Output($filename);
return $filename;

And in the AJAX request callback I display a confirmation alert.

However analyzing the inspect element, in the network tab, I get the following response

%PDF-1.7
%����
7 0 obj
<< /Type /Page /Parent 1 0 R /LastModified (D:20141016181750-03'00') /Resources 2 0 R /MediaBox [0.000000 0.000000 595.276000 841.890000] /CropBox [0.000000 0.000000 595.276000 841.890000] /BleedBox [0.000000 0.000000 595.276000 841.890000] /TrimBox [0.000000 0.000000 595.276000 841.890000] /ArtBox [0.000000 0.000000 595.276000 841.890000] /Contents 8 0 R /Rotate 0 /Group << /Type /Group /S /Transparency /CS /DeviceRGB >> /Annots [ 6 0 R ] /PZ 1 >>
endobj
8 0 obj
<</Filter /FlateDecode /Length 295>> stream
x���Qo�0���+Σ��ۖ���9]|r[�-Q_&H�'�d  ٿ_%AQ�1p�
�m���ˁ�6�s�_X��+�9����'* �Sp[<9Fw��p?�#]vM���[FG�j�a�c��1)؋z�%���E�u�U�2
&4�L��,G�i�x/�<�������:Z��R�-�/�*-���p����QUU�g��lyQf��j��|7�����
�CI�I����z�C nt��u��*�Bm��V�k�ȚV9��л���~��_�*�҈����8�D�p;�� ���|�o
endstream
endobj

I have tried to put the headers and can not display or force the PDF download, but testing without AJAX in a request to a route with only the code to generate the PDF, it generates and displays in the browser normally.

I would like a PDF to be created after the insert in the database and opened in a new tab with the information for printing.

Or another solution to generate PDF or print.

    
asked by anonymous 16.10.2014 / 23:30

1 answer

2

In order for the browser to know that the content is to be downloaded, you must use the Content-Disposition (English) :

Content-Disposition: attachment; filename="meuFicheiro.pdf"

In addition, according to the rules, the header should preferably be sent:

Content-Type: application/octet-stream

To basically tell the browser:

  

I do not know what this is, call the Salvar como dialog and use the name meuFicheiro.pdf if possible.

I say "preferably" because the browser is supposed to read the stream of the PDF should identify it as a PDF, although, via the doubts, as the two headers give the full indication that is a document to store on the user's device.

Document ID Header

You can also specify in the Content-Type header that it is a PDF document:

Content-Type: application/pdf

Laravel

Alternatively, Laravel contains a method to indicate that the response is a download:

return Response::download($caminhoParaFicheiro, $nomeFicheiro, $cabecalhos);

See the documentation at: Laravel: Special Responses (English)

    
17.10.2014 / 14:12