Is it possible to render a twig template for "later use"? I have been asked to create a custom module that outputs a node's content in a way that it will be easy to print or export to pdf. 

I came accross this question and this is litteraly what I'd like to do, but I can't manage to adapt it to Drupal. I've seen quite a lot of potential solutions, but I don't know if they'd help.

Here is what I did so far:

// My module's route is '/pdf/node/{nid}

$route_match = \Drupal::service('current_route_match');
$node = $route_match-&gt;getParameter('nid');
$node_storage = \Drupal::entityTypeManager()-&gt;getStorage('node');
$result = $node_storage-&gt;load($node);

$response['title'] = $result-&gt;getTitle();
$path = DRUPAL_ROOT . '/modules/custom/mymodule_pdf/templates/node.html.twig';

// It would look like so:
$template = $this-&gt;get('twig')-&gt;render($path, 'title' =&gt; $response['title']);


So far, the twig file just contains the following:

&lt;h1&gt;{{ title }}&lt;/h1&gt;


So $twig would contain &lt;h1&gt;The node's title&lt;/h1&gt;

And all I'd need to to is to put the $twig content as my future pdf's content, but this is the easiest part.

Is this possible to do this?
Normally you don't render twig templates directly, but build the content in a render array and use the render service:

public function nodeExportPdf(NodeInterface $node) {
  $view_builder = \Drupal::entityTypeManager()-&gt;getViewBuilder('node');
  $build = $view_builder-&gt;view($node, 'full');
  $html = \Drupal::service('renderer')-&gt;renderPlain($build);
  ...
}


This will use the node template configured for the view mode you specify in the view builder. In this example full, but probably you want to create a custom view mode for the pdf.

When you are in a controller you get the route parameters in the function arguments. How to build the route for this see https://www.drupal.org/docs/8/api/routing-system/using-parameters-in-routes