Level 23
You might want to take a look at file download responses.
1 like
Hi everyone,
I have a function that retrieve a base64 data, transform to pdf file and force download when I click in the pdf icon. How can I preview that pdf before download? And how can I change the name of the downloaded file?
Here is the table from invoice.blade.php
<table class="table table-hover table-responsive" id="tabla_documentos">
<thead>
<tr>
<th scope="col">Tipo</th>
<th scope="col">Cliente</th>
<th scope="col">RUC/CI</th>
<th scope="col">Estado</th>
<th scope="col">Número</th>
<th scope="col">Valor</th>
<th scope="col">Fecha Emisión</th>
<th scope="col">Fecha Autorización</th>
<th scope="col">XML</th>
<th scope="col">PDF</th>
</tr>
</thead>
<tbody>
@foreach($factura as $value)
<tr>
<td>{{ $value->id_documento }}</td>
<td>{{ $value->persona_nombre }}</td>
<td>{{ $value->ruc_cliente_proveedor }}</td>
<td>{{ $value->estado }}</td>
<td>{{ $value->numero_documento }}</td>
<td>{{ $value->valor_total }}</td>
<td>{{ $value->fecha_emision_documento }}</td>
<td>{{ $value->fecha_autorizacion }}</td>
<td><a href="{{ route('ruta.documentos.xml', $value->numero_autorizacion) }}" target="_blank"><i class="far fa-file-code fa-lg"></i></td>
<!-- This is the PDF icon -->
<td><a href="{{ route('ruta.documentos.pdf', $value->numero_autorizacion) }}" target="_blank"><i class="far fa-file-pdf fa-lg"></i></a></td>
</tr>
@endforeach
</tbody>
</table>
The PDF function from DocumentsController.php
public function pdf($id)
{
$pdf = Emproservis::where('numero_autorizacion', $id)->firstOrFail();
$base64 = $pdf->reporte_pdf;
$my_bytea = stream_get_contents($base64); //This transform the bytea data to string. Is this ok?
$decoded = base64_decode($my_bytea);
$file = 'invoice.pdf'; //I want to name the file dynamically
file_put_contents($file, $decoded);
if (file_exists($file))
{
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
}
And the web route from web.php
Route::get('/home/descargar/pdf/{id}', 'DocumentsController@pdf')
->name('ruta.documentos.pdf');
The solution for me was edit my DocumentsController.php like this:
public function pdf($id)
{
$base64 = Emproservis::where('numero_autorizacion', $id)->firstOrFail();
$pdf = $base64->reporte_pdf;
$my_bytea = stream_get_contents($pdf);
$decoded = base64_decode($my_bytea);
$file = "$base64->numero_documento.pdf";
file_put_contents($file, $decoded);
return response()->file($file)->deleteFileAfterSend(true);
}
Please or to participate in this conversation.