A
A
AleDv2017-05-19 23:36:11
Laravel
AleDv, 2017-05-19 23:36:11

How to do pdf generation and upload on the fly?

Hello. There is such a task: to generate a pdf-file on the button, and immediately give this file to the user for downloading, without saving the file on the server. If that's even possible, I don't know.
Source: laravel 5, barryvdh/laravel-dompdf package for generating pdf. Until I got to this:

$pdf = \App::make('dompdf.wrapper');
    $pdf = $pdf->loadView('pdf.offer', [ 'offer' => $offer ]);
    $filename = public_path().'/files/pdf/offers/'.str_slug($offer->title . '_' . $offer->id).'.pdf';
     $pdf->save($filename);

      return 'http://'.request()->getHost().'/files/pdf/offers/'.str_slug($offer->title . '_' . $offer->id).'.pdf';

Through ajax, I send the necessary data for generation to the controller. The controller generates a PDF, saves it to disk and returns a download link.
In the success'e of the ajax request, I simply open this file and the user downloads.
....
    success: function(data){
        window.open(data);
     }
....

The file is generated, the user downloads - everything is fine. But I don’t need these pdfs on the server, is it possible to somehow generate all this on the fly? Maybe I don’t see an obvious solution, my eye is already blurry.
UPD. It turned out to do the generation on the fly, but the PDF is sent to the browser as a string:
a4049ac11a2a4294aed916e68607d04f.PNG

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2017-05-20
@thewind

Load not via ajax, but as src of an invisible iframe. Or submit the form with target=Your iframe.
And instead of save, do something like output, something like this

B
Barmunk, 2017-05-20
@Barmunk

Route::post('/invoice/pdf', '[email protected]')->name('getInvoice');

<form role="form" action="{{ route('getInvoice') }}" method="post"> 
{{ csrf_field() }} 
<input type="hidden" name="invoice_id" value="{{ $item->DocID }}"> 
<button type="submit" class="btn btn-link">скачать</button> 
</form>

/** 
     * @param Request $request 
     * 
     * @return $this 
     */ 
    public function getInvoice(Request $request) 
    { 
      //валидируем
 
      //подключаем пдф
      $pdf = app('dompdf.wrapper'); 
 
     //формируем пдф вью
      $pdf->loadView('docs.invoice'); 
 
      //возвращаем на скачивание
      return $pdf->download('invoice.pdf'); 
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question