Creating PDF using TCPDF on ajax call

I am using the TCPDF class to create a PDF. First I send some data in json (jquery) format, then I would like to generate a PDF with this data.

Could you tell me if I am right. I have to create a PDF file, save it on the server, and then if the ajax call returns success, redirect the user to this pdf file. Good way?

I have:

$.ajax({ url: '/pdf/fiele_to_generate_pdf.php', type: 'POST', contentType: "application/json; charset=utf-8", data: $.toJSON(jsonObj), processData: false, dataType: 'html', async: false, success: function(html) { window.location.href = '/pdf/example.pdf'; } }); 

Thanks for any advice.

Edit: So, I sent a request to create a PDF file via Ajax to the server, then the pdf file was generated and saved on the server. Then I used window.location.href to redirect the user to this pdf file. Everything works, but I would like to avoid saving the file to the server. Any ideas?

+7
source share
1 answer

Ok, this script will save the file and also display it in the browser

the trick is to use the output method using "F" or "I":

 $pdf->Output("your path", 'F'); //save pdf $pdf->Output('file.pdf', 'I'); // show pdf 

CODE

 <?php class PDF extends TCPDF { public function Header (){ $this->SetFont('dejavusans', '', 14); $title = utf8_encode('title'); $subtitle = utf8_encode('sub title'); $this->SetHeaderMargin(40); $this->Line(15,23,405,23); } public function Footer() { $this->SetFont('dejavusans', '', 8); $this-> Cell (0, 5, 'Pag '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'R', 0, '', 0, false, 'T', 'M'); } public static function makeHTML ($json){ $html = '<table border="0.5" cellspacing="0" cellpadding="4"> <tr> <th bgcolor="#DAB926" style="width:3%; text-align:left"><strong>you th</strong></th> </tr>'; for ($i=0; $i<count($json); $i++) { $a= $i+1; $html .= '<tr> <td style="width:15%; text-align:left">'.$json[$i]->Name.'</td> </tr>'; } $html .= '</table>'; return $html; } } function printReport ($json ) { set_time_limit(0); $pdf = new PDF("L", PDF_UNIT, "A3",true, 'UTF-8', false); $pdf->SetMargins (15, 27, 15, true); $pdf->SetFont('dejavusans', '', 8); $pdf->SetAutoPageBreak(TRUE,50); $pdf->AddPage(); //create html $html = $pdf->makeHTML($json); $pdf->writeHTML($html, false, false, false, false, ''); if (!file_exists("your path")) mkdir("your path"); $pdf->Output("your path", 'F'); //save pdf $pdf->Output('file.pdf', 'I'); // show pdf return true; } $json = json_decode("your json"); printReport($json); ?> 
+7
source

All Articles