Home > database >  How to open the PDF generated in new tab
How to open the PDF generated in new tab

Time:08-31

I have a Leave application project that generates a PDF file. this is the code that generates the pdf after I click submit.

 $id = DB::table('leave')->where('user_id', auth()->user()->id)->max('id');
    $data = leave::where('id', $id)->select('*')->get();
    $filename = auth()->user()->name." - S - ". "LEAVE - ".$randomString->randomString(8)."-".$request->filing_date.".pdf";
        $path = storage_path('app/leave_file/'.$filename);
        PDF::loadView('pdf_views.leave_pdf', $data[0])->setPaper('legal')->save($path);
        if(file_exists($path)){
            DB::table('leave_files')->insert([
                'filename' => $filename,
                'leave_id' => DB::table('leave')->where('user_id', auth()->user()->id)->max('id'),
            ]);
        }
    
    return redirect()->route('leave')->with('success', "success");

I wonder if I can make the newly generated pdf open in the new tab after I click submit on my leave application. thank you to anyone who can help

CodePudding user response:

According to the Laravel docs this is what you need: https://laravel.com/docs/9.x/responses#file-responses

File Responses

The file method may be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download. This method accepts the path to the file as its first argument and an array of headers as its second argument:

return response()->file($pathToFile);

return response()->file($pathToFile, $headers);

CodePudding user response:

Use the Cache Facade, to store the generated pdf temporary.

$uuid = Str::uuid();

return response()->stream(function () use ($uuid) {
    echo Cache::remember($uuid, 300, function() {
        return 'genertated pdf content'
    });
}, 200, [
    'Content-Type' => 'application/pdf',
    'Content-Disposition' => sprintf('attachment; filename=%s;', $uuid),
]);

Create a route to access to cached file. Name the route. Now you can open it in a new tab from you frontend e.g. Generate the route with route('routename', ['param' => 123]) and pass it to your FE with a REST endpoint for example.

window.open(url,'_blank');
  • Related