export CSV et imprimer en pdf

132 views
Skip to first unread message

sejadah...@gmail.com

unread,
Feb 9, 2016, 6:26:33 AM2/9/16
to ZnetDK
Bonjour,
pour c qui concerne exportation en CSV et l'impression en pdf qu'est ce qu'on doit faire pour l'activer 
et merci d'avance 
Cordialement 

Pascal Martinez

unread,
Feb 9, 2016, 3:31:46 PM2/9/16
to ZnetDK
Bonjour,

Voici un exemple de vue avec un lien hypertexte pour déclencher le téléchargement et un exemple de contrôleur applicatif en charge de retourner un fichier CSV.
  • Vue ./app/view/myview.php
<a href="<?php echo \General::getURIforDownload('mycontroller'); ?>">Download CSV file</a>
  • Contrôleur ./app/controller/mycontroller.php
<?php
namespace app\controller;
class MyController extends \AppController {
   
static protected function action_download() {
        $response
= new \Response();
        $header
= array('Column 1','Column 2','Column 3');
        $data
= array(
            array
('Row 1 col. 1','Row 1 col. 2','Row 1 col. 3'),
            array
('Row 2 col. 1','Row 2 col. 2','Row 2 col. 3'),
            array
('Row 3 col. 1','Row 3 col. 2','Row 3 col. 3'),
       
);
        $response
->setDataForCsv($data, 'myfile.csv', $header);
       
return $response;
   
}
}

Bon développement avec ZnetDK.

Pascal MARTINEZ

Pascal Martinez

unread,
Feb 9, 2016, 4:16:37 PM2/9/16
to ZnetDK
Bonjour,

Pour générer un document PDF avec ZnetDK, vous devez tout d'abord télécharger la librairie FPDF disponible sur le site officiel http://www.fpdf.org/

Copiez ensuite le contenu de l'archive FPDF dans un sous-dossier de l'application nommé par exemple ./applications/default/app/fpdf, de sorte à disposer du script fpdf.php directement dans ce sous-dossier.

Créer ensuite un nouveau contrôleur applicatif, par exemple ./app/controller/mypdfcontroller.php renvoyant le fichier PDF généré à la demande :

<?php
namespace controller;
class MyPdfController extends \AppController {
   
static protected function action_download() {
        $request
= new \Request();
        $myValue
= $request->my_value;
       
// FPDF is installed in the applications/default/app/fpdf directory
       
require('app' . DIRECTORY_SEPARATOR.'fpdf'.DIRECTORY_SEPARATOR.'fpdf.php');
        $pdf
= new \FPDF();
        $pdf
->AddPage();
        $pdf
->SetFont('Arial','B',16);
        $pdf
->Cell(40,10,"PDF document generated from ZnetDK, value: $myValue");
       
// Response returned to the user's web browser
        $response
= new \Response();
        $response
->setPrinting($pdf, 'mygenerateddoc.pdf');
       
return $response;
   
}
}

Le fichier PDF peut ensuite être téléchargé depuis une vue de l'application ./app/view/mypdfview.php à partir par exemple d'un lien hypertexte :

<a href="<?php echo \General::getURIforDownload('mypdfcontroller','my_value=Hello');?>">PDF Printing...</a>

Bonne programmation.

Pascal MARTINEZ

sejadah...@gmail.com

unread,
Feb 10, 2016, 5:58:35 AM2/10/16
to ZnetDK
Bonjour,
Merci pour votre réponse, pour bien comprendre, si je veux par exemple exporter en CSV les données dans le CRUD demo   qu'est ce que je doit écrire dans
"$data = array(
            array('Row 1 col. 1','Row 1 col. 2','Row 1 col. 3'),
            array('Row 2 col. 1','Row 2 col. 2','Row 2 col. 3'),
            array('Row 3 col. 1','Row 3 col. 2','Row 3 col. 3'),
        ); "
Merci d'avance

Pascal Martinez

unread,
Feb 10, 2016, 3:33:10 PM2/10/16
to ZnetDK
Bonsoir,

Il vous faut remplir le tableau $data des lignes du fichier CSV en parcourant les produits à l'aide de l'objet DAO associé.

Ci-dessous un exemple applicable à la démo CRUD de ZnetDK.

static protected function action_download() {
        $response
= new \Response();

        $header
= array('Part number','Name','Description','Price');
        $productsDAO
= new \app\model\ProductsDAO();
       
while($row = $productsDAO->getResult()) {
            $data
[] = array($row['part_number'],$row['name'],$row['description'],
               
\Convert::toMoney($row['price'], FALSE, 2));

       
}
        $response
->setDataForCsv($data, 'myfile.csv', $header);
       
return $response;
}

Cordialement,
Pascal MARTINEZ

Jose Puertas

unread,
Feb 10, 2016, 4:51:46 PM2/10/16
to ZnetDK
Hola Pascal, al hilo de esta conversación, el ejemplo que has puesto para el csv ¿seria válido también para el pdf?

Saludos

sejadah...@gmail.com

unread,
Feb 11, 2016, 7:12:25 AM2/11/16
to ZnetDK
Merci beaucoup ça marche 
et pour le pdf???

Pascal Martinez

unread,
Feb 11, 2016, 3:59:57 PM2/11/16
to ZnetDK
Hola José,

Es es el mismo principio para generar la lista de productos en formato PDF.
Un ejemplo de acción de controlador a continuación.

    static protected function action_download() {
        $response
= new \Response();

       
// FPDF is installed in the applications/default/app/fpdf directory
       
require('app' . DIRECTORY_SEPARATOR.'fpdf'.DIRECTORY_SEPARATOR.'fpdf.php');
        $pdf
= new \FPDF();
        $pdf
->AddPage();
        $pdf
->SetFont('Arial','B',16);

        $pdf
->Cell(0,10,'List of products',0,1,'C');
        $pdf
->Ln(2);

        $productsDAO
= new \app\model\ProductsDAO();
       
while($row = $productsDAO->getResult()) {

            $pdf
->SetFont('Arial','B',12);
            $pdf
->Cell(0,5,$row['part_number'] . ' - ' . $row['name'],0,1);
            $pdf
->SetFont('Arial','I',11);
            $pdf
->Cell(140,5,$row['description'],'B');
            $pdf
->SetFont('Arial','',12);
            $pdf
->Cell(0,5,\Convert::toMoney($row['price'],FALSE),'B',1,'R');
            $pdf
->Ln(2);
       
}
        $response
->setPrinting($pdf, 'products.pdf');
       
return $response;
   
}

Y el resultado...


Saludos,

Pascal MARTINEZ

Jose Puertas

unread,
Feb 11, 2016, 4:07:37 PM2/11/16
to ZnetDK
Muchas gracias Pascal, como siempre un gran trabajo y un desarrollo espectacular, gran framework.

Saludos

sejadah...@gmail.com

unread,
Feb 12, 2016, 5:08:40 AM2/12/16
to ZnetDK
Merci c'est géniale 

Pascal Martinez

unread,
Feb 12, 2016, 12:50:02 PM2/12/16
to ZnetDK
Perfecto ;-)

Anderson Florencio

unread,
Mar 16, 2016, 12:08:50 PM3/16/16
to ZnetDK
Hello Pascal, I want to pass parameters to the controller via form and a submit button in order to create dynamic reports. Is it possible or only via link?

Pascal Martinez

unread,
Mar 20, 2016, 5:30:36 AM3/20/16
to ZnetDK
Hello Anderson,

Here is an example of a view that shows how to generate dynamically a PDF document from a value entered in a form and that displays the generated PDF file into another browser tab.

1) The view: when the form validation is OK, the 'window.open' JavaScript function is called to send the GET request to the server side controller. The '_blank' attribute forces the HTTP response to be displayed in another browser tab. 

<form id="dynpdfwithform" class="zdk-form">
   
<label>My value</label>
   
<input name="myvalue" required>
   
<button class="zdk-bt-save" type="submit">Generate PDF</button>
</form>


<script>
    $
(function() {
        $
('#dynpdfwithform').zdkform({
            complete
: function () {
               
var formData = $(this).zdkform('getFormData');
                window
.open("<?php echo \General::getURIforDownload('mypdfcontroller'); ?>"
                 
+ "&my_value=" + formData[0].value, '_blank');
           
}
       
});
   
});
</script>


2) The controller: this is the same controller than the one written previously in this post.

<?php
namespace controller;
class MyPdfController extends \AppController {
   
static protected function action_download() {
        $request
= new \Request();
        $myValue
= $request->my_value;

       
// FPDF is installed in the applications/default/app/fpdf directory
       
require('app' . DIRECTORY_SEPARATOR.'fpdf'.DIRECTORY_SEPARATOR.'fpdf.php');
        $pdf
= new \FPDF();
        $pdf
->AddPage();
        $pdf
->SetFont('Arial','B',16);

        $pdf
->Cell(40,10,"PDF document generated from ZnetDK, value: $myValue");
       
// Response returned to the user's web browser
        $response
= new \Response();
        $response
->setPrinting($pdf, 'mygenerateddoc.pdf');
       
return $response;
   
}
}


Let me know if it suits your need.

Regards, 

Pascal MARTINEZ

Jose Puertas

unread,
Apr 27, 2016, 1:06:18 PM4/27/16
to ZnetDK
Hola Pascal, a la vez que se pueden imprimir los archivos pdf, ¿también se pueden subir y descargarlos más adelante con este sistema?

Saludos

Pascal Martinez

unread,
May 1, 2016, 4:17:37 PM5/1/16
to ZnetDK
Hola José,

He creado un nuevo asunto especifico Upload & Download PDF files para ilustrar la manera de subir y descargar archivos PDF con un ejemplo de vista y de controlador.

Saludos,

Pascal MARTINEZ

Jose Puertas

unread,
May 1, 2016, 4:19:38 PM5/1/16
to ZnetDK
Muchisimas gracias Pascal

Anderson Florencio

unread,
May 4, 2016, 12:08:23 PM5/4/16
to ZnetDK
Hello Pascal, using the sample code that you post here on the topic could generate PDF files with FPDF which normally operate at a conventional PC, but when I generate the PDF on a mobile device can not display the file with the default PDF reader Google Drive. I researched and found that the error can be generated in PDF header, but the very FPDF library generates this header in its class and it already gets out of control the ZnetDK. You would have more or less an idea of how to solve this problem? To work around this problem put the user to download the pdf generated to be able to open it in another PDF viewer installed on the mobile device, such as Acrobat.

Pascal Martinez

unread,
May 7, 2016, 5:08:16 PM5/7/16
to ZnetDK
Hello Anderson,

I didn't know about this issue on PDF documents generated documents when displayed with the Google Drive PDF viewer.

Maybe, you could try to generate documents with an other PDF framework like TCPDF.
I didn't try it but it could be interesting to test it.

Regards,

Pascal MARTINEZ
Reply all
Reply to author
Forward
0 new messages