fatima ezzahra fatima ezzahra - 4 months ago 27
Ajax Question

How to display a pdf in a twig division using ajax and symfony?

I try to display a pdf in my twig , I created a method in the controller that generate the pdf :



public function invitationPDFAction(){

$html = $this->renderView('InvitationInvitationBundle:invitation:indextest.html.twig');

$html2pdf = new \Html2Pdf_Html2Pdf('P','A4','fr');
$html2pdf->pdf->SetTitle('real');
// $html2pdf->pdf->SetAuthor('Fz');

$html2pdf->pdf->SetDisplayMode('real');

$html2pdf->writeHTML($html);
$html2pdf->Output('file.pdf');
$response = new Response();
$response->headers->set('Content-Type','application/pdf');
return $response;

}





and an ajax script that return the pdf inside the view :



$.ajax({
type: 'get',
url: "{{ path('invitation_invitationPDF')}}",
beforeSend: function() {

},
success: function(data) {
$(".page-content").append(data);
$(".modal-body").hide();
}
});





but it seems not working , the method generate the pdf , but I can't display it, take a look at the result please : enter image description here

Answer

Your code is getting the file contents of the PDF with your ajax call, and the content is then displayed in your .page-content.

To achieve what you want you should embed the PDF file instead, this can be achieved in a number of ways, the easiest probably being adding the following code inside your .page-content

<embed src="{{ path('invitation_invitationPDF')}}" width="500" height="400" type='application/pdf'>