Reputation: 393
I have a problem generating a pdf with the TCPDF library, and tried to follow some examples that are here, but I have not managed to solve my problem, which is this: when I click on a button I am making an AJAX request Which sends a parameter and the url points to a controller in php with CODEIGNITER, the parameter is used to execute my query and generate the report based on it. I have already debugged the report with static parameters to see if it worked and without using AJAX, and everything went well. The problem is that I need to send the data this way and I do not know how to load the pdf file created in the response of my request, any ideas?
$("#BtnDownload").click(function (){
var jsonString = 2; //Example parameters;
$.ajax({
type: 'POST',
url: baseurl+"reports/selectReport",
data: {'data': jsonString},
success: function(response){
//What my driver should return
}
});
});
This is the function in my controller that I point my ajax request, I do not put all the code of the layout of my report because it is working, and the code is very long, the important thing is to know how to return my generated report And can view it from the browser.
public function selectReport(){
$this->load->library('Pdf');
$pdf = new Pdf('L', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetTitle('report');
$pdf->SetSubject('Report PDF');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->setPrintHeader(false);
$pdf->setFooterData($tc = array(0, 64, 0), $lc = array(0, 64, 128));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->SetFont('dejavusans', '', 12, '', true);
$base_url = base_url();
$data = $this->input->post("data");
// report body
$name_pdf = utf8_decode("report.pdf");
$pdf->Output($name_pdf, 'I');
}
Upvotes: 1
Views: 1791
Reputation: 4582
In TCPDF ( according to TCPDF Save file to folder? ) the PDF can be saved:
$dir = 'pdfs/';
$filename = 'report' . microtime(TRUE) . '.pdf';
if( ! is_dir( FCPATH . $dir ) )
mkdir( FCPATH . $dir, 0777, TRUE );
$pdf->Output( FCPATH . $dir . $filename, 'F'); // F saves to filesystem
Since you know the PDFs are in the pdf directory:
$this->load->helper('url');
echo json_encode(array(
'path' => FCPATH . $dir . $filename,
'url' => base_url( $dir . $filename )
));
Then in your ajax success function data.url is the URL to the file:
success: function(response){
if( response.url ){
window.location = response.url;
}
}
Make sure your $.ajax has the configuration for dataType: 'json'.
$.ajax({
// ...
dataType: 'json'
// ...
});
Upvotes: 1