FareedR
2 months ago

Return response as a download using Spatie/Browsershot

Posted 2 months ago by FareedR

Anyone using spatie/browsershot ? everything works . pdf file stored on storage. but for the frontend part. how can i return success with automatically download the pdf ?

public function stock_custom($from,$to)
    {
        $stocks = Stock::with(['analyses' => function ($query){
            $query->whereNotNull('time_frame')->whereNotNull('description');
        }])->whereBetween('created_at',[$from.' 00:00:00', $to.' 23:59:59'])->get();

        return view('stocks.custom',compact('from','to','stocks'));
    }

public function get_download_custom(Request $request)
    {
        $from   = $request->get('from');
        $to     = $request->get('to');

        Browsershot::url(route('stock.retrieve.custom', [$from,$to]))
        ->setNodeBinary(env('NODE_PATH'))
        ->setNpmBinary(env('NPM_PATH'))
        ->setOption('landscape', true)
        ->margins(10, 10, 10, 10)
        ->showBackground()
        ->emulateMedia("screen")
        ->format('A4')
        ->save(storage_path('app/public').'/'."stock_".$from.'_'.$to.'.pdf');

        $file_name = storage_path('app/public').'/'."stock_".$from.'_'.$to.'.pdf';
 
        return \Storage::disk('public')->download("stock_".$from.'_'.$to.'.pdf');
    }

//blade javascript

	swal({
                title: "Are you sure?",
                text: "Confirm with your input?",
                icon: "warning",
                buttons: true,
                dangerMode: true,
            })
            .then((willUpdate) => {
                if (willUpdate) {
                    $.ajax({
                        url : "{{ url('stocks-custom') }}",
                        type : "POST",
                        data : {
                            '_method' : 'POST',
                            'from': from,
                            'to': to
                        },
                        success: function(){
                            // i've no idea what to put here. 
                        },
                        error : function(){
                            swal({
                                title: 'Opps...',
                                text : data.message,
                                type : 'error',
                                timer : '1500'
                            })
                        }
                    })
                } else {
                    //
                }
            });

Please sign in or create an account to participate in this conversation.