How to print the output of a controller

Created on 6 January 2020, almost 5 years ago
Updated 3 July 2024, 5 months ago

I have a situation where I need to print the output of a controller, but this does not appear in the list of entities that Entity Print sees. Is there a way I can declare the output of the controller as an entity? Is there some other way to get this done?

πŸ’¬ Support request
Status

Active

Version

2.1

Component

User interface

Created by

πŸ‡ΊπŸ‡ΈUnited States Ben Coleman

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • πŸ‡ͺπŸ‡ΈSpain uridrupal

    This is old, but this is how I did it:

        $html = Drupal::service('renderer')->renderRoot($array);
        /** @var PrintBuilder $print_builder*/
        $print_builder = Drupal::service('entity_print.print_builder');
        /** @var RendererInterface $renderer*/
        $renderer = Drupal::service('entity_print.renderer_factory')->create([$entity]);
        $print_engine = Drupal::service('plugin.manager.entity_print.print_engine')->createInstance('dompdf');
        $print_engine->addPage($html);
        $content = $renderer->render([$entity]);
        $render = [
          '#theme' => 'your_template',
          '#title' => $this->t('View @type', ['@type' => $print_engine->getExportType()->label()]),
          '#content' => $content,
          '#attached' => ['your_module/library'],
        ];
    
        $print_engine->addPage($renderer->generateHtml([$entity], $render, FALSE, TRUE));
    
        return (new StreamedResponse(function () use ($print_builder, $entity, $print_engine) {
          // The printed document is sent straight to the browser.
          $print_builder->deliverPrintable([$event_notes], $print_engine, FALSE, TRUE);
        }))->send();
    

    As far as I understood, the module requires an entity to work, you can't make it work only with a render array. So I did setup in a random entity a "PDF" view mode (which I knew I wouldn't need to export to PDF later), created the template twig. That template Twig shows nothing, it's just there to make the genereateHtml() method work.

    $array is the result of

    return [
          '#theme' => 'your_template',
          '#var1' => $var1,
          '#var2' => $var2,
          '#var3' => $var3
        ];

    Hope it helps somebody else.

Production build 0.71.5 2024