Quick tutorial on how to serve a PDF that downloads automatically in your browser in drupal 8.

namespace Drupal\MYMODULE\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

 * Class PdfGeneratorController.
class PdfGeneratorController extends ControllerBase {

  public function Render($uuid) {

    // In my case, I render a file by UUID
    // This actually does not matter too much here
    // String below contains the url of the file
    $uri = 'private://'.$uuid.'.pdf';

    $headers = array(
      'Content-Type'     => 'application/pdf',
      'Content-Disposition' => 'attachment;filename="download"');

    return new BinaryFileResponse($uri, 200, $headers, true);

So if i put a link like '/download/550e8400-e29b-41d4-a716-446655440000', then it would automatically download my PDF file in my browser. Inside the controller you could generate the pdf, or check if it exists, ... before you serve the download. Enjoy!

Saved you some valuable time?

Donate and get more free time-saving code on this website in the future.