Dompdf returns PDF on Controller function but not on Submit Form function I'm using Drupal's Form api to create a form which returns some values inside a PDF document based on some selected inputs. I'm importing the form like so:

public function content(){
    $form = \Drupal::formBuilder()-&gt;getForm('Drupal\custom_module_name\Form\ContributeForm');
    ...
    ... and so on


In my ContributeForm::submitForm I have this code:

public function submitForm(array &amp;$form, FormStateInterface $form_state)
{
    $dompdf = new Dompdf();
    $dompdf-&gt;loadHtml('&lt;h1&gt;hello world&lt;/h1&gt;');
    $dompdf-&gt;setPaper('A4');
    $dompdf-&gt;render();
    $dompdf-&gt;stream("example.pdf", array("Attachment"=&gt;0));
    if ($dompdf){
        drupal_set_message("DOMPDF");
    }
    foreach($form_state-&gt;getValues() as $key =&gt; $value){
        drupal_set_message($key . ': ' . $value);
    }


and I don't get a pdf doc on the reloading of the page, though I do get the contents selected in the form returned to me in the drupal_set_message call.

Now to sanity check, I created a dummy module with only a controller (no form import) and this one DOES return the PDF with the content inside ::loadHtml:

public function content(){

    $domp = new Dompdf();
    $domp-&gt;loadHtml('&lt;h1&gt;Hi&lt;/h1&gt;');
    $domp-&gt;setPaper('A4');
    $domp-&gt;render();
    $domp-&gt;stream('example.pdf');

    return array(
        //'#type' =&gt; 'markup',
        '#markup' =&gt; $this-&gt;t('Hello World yall'),
    );

}


Am I missing something on the form return? Am I adding an unnecessary layer of complications by importing the form into the controller, and should I just have the form load to it's own url?
By default after form submit drupal makes a redirect, if there is no redirect defined intentionally allways will go to current url. To prevent this, you need call to disableRedirect() method from FormState at the final of submitForm().

Example:

public function submitForm(array &amp;$form, FormStateInterface $form_state)
{
    $dompdf = new Dompdf();
    $dompdf-&gt;loadHtml('&lt;h1&gt;hello world&lt;/h1&gt;');
    $dompdf-&gt;setPaper('A4');
    $dompdf-&gt;render();
    $dompdf-&gt;stream("example.pdf", array("Attachment"=&gt;0));
    if ($dompdf){
        drupal_set_message("DOMPDF");
    }
    foreach($form_state-&gt;getValues() as $key =&gt; $value){
        drupal_set_message($key . ': ' . $value);
    }
    // Prevent form redirection to print PDF.
    $form_state-&gt;disableRedirect();
}


Source: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21FormState.php/function/FormState%3A%3AdisableRedirect/8.2.x

Other option, more dirty, is call to exit() method from PHP (http://php.net/manual/es/function.exit.php) also at the final of the function.