04
Jul '17

This was a bit of a challenge to myself to make PDF rendering much more simple to implement.

I came up with this middleware which will trigger if the request contains a ‘pdf’ parameter. As an additional nice-to-have if the request has a ‘ls’ parameter it will render landscape rather than portrait.

This uses Snappy PDF and assumes it is aliased simply as ‘PDF’ in the app config.

namespace App\Http\Middleware;

use Closure;

class PDF
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if($request->pdf) {

            //Useful to have in case there are any view changes that help with the render
            view()->share('pdf', true);
            view()->share('print', true);

            //Grab the response into a variable
            $response = $next($request);

            //Try to get title from the response, if not just take app name
            $title = (is_object($response->original) && $response->original->title) ? $response->original->title : config('app.name') . '.pdf';
            $orientation = $request->ls ? 'landscape' : 'portrait';
            return \PDF::loadHTML($response->content())->setOrientation($orientation)->stream($title);
        }

        return $next($request);
    }
}