Help with the correct functioning of html2pdf in php

0

I need to generate a pdf with personal information of a user (personal data), but I need a button that starts the download on the same screen, I do not need to open any other window to view it. Then.

I already have all the HTML with something like this:

<?php 
  if(isset($_POST['pdf])){
   $pdf = new pdfcontroller();
   $pdf->generarPdf();
 ?>
<html>

<head>
</head>
<body>
  <form>
  {aqui los datos del usuario}

  <input class="btn btn-info" type="submit" name="pdf" value="Descargar pdf">
  </form>

</body>
</html>

And this is my driver class with the imported library correctly:

require_once(dirname(__FILE__).'/../libs/html2pdf/vendor/autoload.php');
use Spipu\Html2Pdf\Html2Pdf;

    class pdfcontroller{


        public function generarPdf(){

        }
    }

Now, I understood that for this library I need to format the HTML and send all the parameters to my driver to generate the pdf and well, that without fail I can solve it, but I hurry the matter that the driver can return an object in pdf or in case to initiate the download of the file.

Thank you very much for your help, I am totally grateful from now on.

    
asked by Neftali Acosta 13.06.2018 в 07:56
source

2 answers

2

Your function generarPDF() should look like this:

public function generarPDF()
{
    // Logic

    if($this->html2pdf->create('save')) 
    {
        $this->downloadPDF(); // Acá es donde se genera la descarga del PDF
    }
}

public function downloadPDF()
{
    if(is_dir("./tu-ruta"))
    {
        $route = base_url("tu-ruta/" . "cualquier-cosa" . ".pdf");
        $filename = "name-file" . ".pdf";

        if(file_exists("././tu-ruta/" . $filename))
        {
            header("Cache-Control: public"); 
            header("Content-Description: File Transfer"); 
            header('Content-disposition: attachment; filename=' .basename($route)); 
            header("Content-Type: application/pdf"); 
            header("Content-Transfer-Encoding: binary"); 
            readfile($route);
        }
    }
}

It is important that in function downloadPDF respect the / as it places them, otherwise it will not work.

    
answered by 13.06.2018 / 17:51
source
0

When in the controller you reach the part of saving the file, do this:

$fichero = "fichero.pdf";
$html2pdf->output($fichero);

return $fichero; // "fichero.pdf"

And then in your HTML the $ pdf- > generatePdf (); will return the name of the file, what you have to do is put a link with the path where your pdfs files are stored

echo "<a class='btn btn-primary' download target="_blank" href='AQUI_LA_RUTA/$fichero'></a>";

And yes, first you would have to save the file locally and then download it with a link.

    
answered by 13.06.2018 в 13:32