Posted in

Generar PDF con Laravel

Para generar PDFs usaremos la clase DomPDF y para instalarla realizaremos los siguientes pasos:

1 – Añadimos

"thujohn/pdf": "dev-master"

a nuestro composer.json
2 – Abrimos CMD, accedemos a la carpeta principal de nuestro proyecto y tecleamos composer update
3 – Abrimos app/config/app.php y añadimos en el array de providers:

'Thujohn\Pdf\PdfServiceProvider',

4 – En el mismo archivo, en el array de alias:

'PDF' => 'Thujohn\Pdf\PdfFacade',

4 – Publicamos la configuración a través de CMD:

php artisan config:publish thujohn/pdf

Uso
Mostrar PDF en pantalla

Route::get('/', function()
{
    $html = '<html><body>'
            . '<p>Put your html here, or generate it with your favourite '
            . 'templating system.</p>'
            . '</body></html>';
    return PDF::load($html, 'A4', 'portrait')->show();
});

Descargar PDF

Route::get('/', function()
{
    $html = '<html><body>'
            . '<p>Put your html here, or generate it with your favourite '
            . 'templating system.</p>'
            . '</body></html>';
    return PDF::load($html, 'A4', 'portrait')->download('my_pdf');
});

Devuelve un PDF como string

Route::get('/', function()
{
    $html = '<html><body>'
            . '<p>Put your html here, or generate it with your favourite '
            . 'templating system.</p>'
            . '</body></html>';
    $pdf = PDF::load($html, 'A4', 'portrait')->output();
});

Ejemplos
Guardar el PDF en una carpeta específica y lo envía vía mail como adjunto.

define('BUDGETS_DIR', public_path('uploads/budgets')); // I define this in a constants.php file

if (!is_dir(BUDGETS_DIR)){
    mkdir(BUDGETS_DIR, 0755, true);
}

$outputName = str_random(10); // str_random is a [Laravel helper](http://laravel.com/docs/helpers#strings)
$pdfPath = BUDGETS_DIR.'/'.$outputName.'.pdf';
File::put($pdfPath, PDF::load($view, 'A4', 'portrait')->output());

Mail::send('emails.pdf', $data, function($message) use ($pdfPath){
    $message->from('us@example.com', 'Laravel');
    $message->to('you@example.com');
    $message->attach($pdfPath);
});


Ejemplo propio de generar un PDF pasándole valores

public function pdfFactura($id_factura){
o$facturas = Factura::find($id_factura);
$conceptos = Concepto::where('id_factura', '=', $id_factura)->get();
$total_pagar = Concepto::where('id_factura', '=', $id_factura)->sum('total');
$cliente = Client::where('id', '=', $facturas->id_cliente)->get();
$html = View::make('pdf.factura')->with(array('facturas' => $facturas, 'conceptos' => $conceptos, 'total_pagar' => $total_pagar, 'cliente' => $cliente))->render();
return PDF::load($html, 'A4', 'portrait')->show();
    }

Deixa un comentari

L'adreça electrònica no es publicarà. Els camps necessaris estan marcats amb *


The reCAPTCHA verification period has expired. Please reload the page.