Abra la respuesta JSON de Fpdf, en una ventana nueva, para guardar el PDF. - PHP

I'm trying to send a Json array over using an AJAX call to a controller function which processes the data using a FPDF library which is already implemented into Codeigniter. I can see the PDF data being returned, but how would I go about opening this PDF data in a new window so the PDF can be saved. It doesn't matter if the PDF cant be viewed i just need to save the generated file.

Aquí está el código que tengo hasta ahora:

Código Jquery

<script defer="defer" type="text/javascript">
$(document).ready(function() {
    $('a#export').click(function(exportRecord) {    
        var postData = {
            'record_type'   : 1,
            'title' : 'Some Title Here',
            'content' : 'Some content here',
        };
        $.ajax({
                url: "<?php echo base_url().'admin/pdf/createPDF';?>",
                type:'POST',
                data: postData,
                dataType: 'json',
                success: function(data){
                        window.open(
                            'data:application/pdf,'+encodeURIComponent(data),
                            'Batch Print',
                            'width=600,height=600,location=_newtab'
                        );
                    } // End of success function of ajax form
        }); // End of ajax call
        return false;
    });
});
</script>

La función del controlador

<?php
    function createPDF(){       
            $content = $this->input->post('content');
            $font_directory = './assets/fpdf_fonts/';
            set_realpath($font_directory);
            define('FPDF_FONTPATH',$font_directory);
            $data = $this->fpdf->Open();
            $data = $this->fpdf->AddPage();
            $data = $this->fpdf->SetFont('Arial','',8);
            $data = $this->fpdf->Cell(80);
            $data = $this->fpdf->Cell(0,0,$content,0,1,'R');
            $data = $this->fpdf->Output();
    }

The JSON Response

%PDF-1.3
3 0 obj
<</Type /Page
/Parent 1 0 R
/Resources 2 0 R
/Contents 4 0 R>>
endobj
4 0 obj
<</Filter /FlateDecode /Length 72>>
stream
x�3R��2�35W(�r
Q�w3T��30PISp
��陛)X��(��(hx����+���i*�d�����F
endstream
endobj
1 0 obj
<</Type /Pages
/Kids [3 0 R ]
/Count 1
/MediaBox [0 0 595.28 841.89]
>>
endobj
5 0 obj
<</Type /Font
/BaseFont /Helvetica
/Subtype /Type1
/Encoding /WinAnsiEncoding
>>
endobj
2 0 obj
<<
/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]
/Font <<
/F1 5 0 R
>>
/XObject <<
>>
>>
endobj
6 0 obj
<<
/Producer (FPDF 1.7)
/CreationDate (D:20120309201958)
>>
endobj
7 0 obj
<<
/Type /Catalog
/Pages 1 0 R
>>
endobj
xref
0 8
0000000000 65535 f 
0000000228 00000 n 
0000000411 00000 n 
0000000009 00000 n 
0000000087 00000 n 
0000000315 00000 n 
0000000515 00000 n 
0000000590 00000 n 
trailer
<<
/Size 8
/Root 7 0 R
/Info 6 0 R
>>
startxref
639
%%EOF
""

preguntado el 10 de marzo de 12 a las 01:03

3 Respuestas

Maybe a bit late, there is my answer I got the system working.

For a reason that I don't understand it doesn't work with ajax call.

This post helped has done the magic : Solicitud de publicación de JavaScript como envío de formulario

HTML (here the call the PDF generator in PHP with POST parameter ):

   post('GenerateStockLabelsWPDF.php',  { CSVTable: JSON.stringify(encodeURIComponent(CSVtable))});

Then PHP (For the sample it's a fixed text, you can adapt it by getting variable via _post):

<?php

include "php/fpdf/fpdf.php";

$pdf = new FPDF();
$pdf->Open();
$pdf->SetMargins(0, 0);
$pdf->SetAutoPageBreak(false);
$pdf->AddPage();

$content = 'thisis a test';

$pdf->SetXY(20, 20);
$pdf->SetFont('Helvetica', 'B', 10);
$pdf->MultiCell(150, 5, $content, 0, 'L');

$pdf->Output('Labels.pdf', 'D');

exit;

?>

Respondido el 20 de junio de 14 a las 14:06

Save the generated file where? On the users computer? On the server?

Parece $data en el objeto createPFD Método is the PDF.

For the former, check http://codeigniter.com/user_guide/helpers/download_helper.html

force_download('coolPDF.pdf', $data);

For the latter, check http://codeigniter.com/user_guide/helpers/file_helper.html

write_file('/path/to/these/PDFs/fileName.pdf', $data);

respondido 11 mar '12, 15:03

to download the file into the users computer - daniel adarve

OK, so the first one (force_download('coolPDF.pdf', $data);) will do the job. - colector de aguas pluviales

I send parameter via POST without ajax and return PDF in new windows:

var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "admin/pdf/createPDF.aspx");

var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "record_type");
hiddenField.setAttribute("value", "1");
hiddenField.setAttribute("name", "title");
hiddenField.setAttribute("value", "Some Title Here");
hiddenField.setAttribute("name", "content");
hiddenField.setAttribute("value", "Some content here");

form.appendChild(hiddenField);
form.setAttribute("target", "_blank");
document.body.appendChild(form);    // Not entirely sure if this is necessary           
form.submit();
return;

Respondido 25 ago 14, 14:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.