I have a node of a particular type that I would like to save as a pdf file (using Entity_print) upon creation or update (whenever a content is saved). The issue I am running into is that some of the variable data used in the template is determined in the preprocessor but the preprocessor has not yet been run at the time. I have a PDF view mode and corresponding templates. When I enter something similar to http://example.com/print/pdf/[entity_type]/[entity_id] I get exactly what I want but that's just at run time. I need this setup 'behind the scenes' and saved into the files. I can generate the pdf file but it is missing the preprocessed variable data. Is the only way to get variable data into twig via preprocessor? Is there a hook that will do this? I have played with a few of them but none seem to be able to capture the variables for the twig templates. By the way I do not want to override the regular preprocessor theme which will be used for page rendering.
1 Answer
I had exactly the same problem. I tried the following simple solution but as it's an intranet with content not available to anonymous users it doesn't work:
$url = "https://{$_SERVER['HTTP_HOST']}/print/pdf/node/" . $node->id();
$pdf_data = file_get_contents($url);
$file = file_save_data($pdf_data, 'private://' . $filename) ;
$node->field_pdf_document->setValue($file);
So I came up with this function, which will return a File object:
function mymodule_entity_print_saver($nid, $filename, $scheme = 'private') {
$pb = new Drupal\entity_print\PrintBuilder(
\Drupal::service('entity_print.renderer_factory'),
\Drupal::service('event_dispatcher'),
\Drupal::service('string_translation')
);
$node = Drupal\node\Entity\Node::load($nid);
$path = $pb->savePrintable(
[$node],
\Drupal::service('plugin.manager.entity_print.print_engine')->createSelectedInstance('pdf'),
$scheme,
$filename
);
$file = File::create([
'uri' => $path,
'uid' => \Drupal::currentUser()->id(),
'status' => FILE_STATUS_PERMANENT,
]);
$file->save();
return $file;
}
You could play around with the exists/replace constant as well if needs be.