Best way to create a PDF link on the entity view

Created on 28 July 2024, 5 months ago

Problem/Motivation

I'd like to create a link on an entity that will then download the PDF

Steps to reproduce

For an article node with a view mode of PDF, I use my theme's preprocess_node hook to add a variable 'pdf_link' that can then be displayed in the node.html.twig

mytheme.theme:

/**
 * Implements hook_preprocess_HOOK() for node.html.twig.
 * Add PDF link to articles
 */
function mytheme_preprocess_node(&$variables) {
  if ($variables['node']->getType()=='article' && \Drupal::currentUser()->hasPermission('view node.article.pdf pdf')) {
    $url_options = [
      'language' => \Drupal::languageManager()->getCurrentLanguage(),
    ];

    $variables['pdf_link'] = \Drupal\Core\Url::fromRoute('entity_pdf.view', [
      'entity_type' => 'node',
      'entity' => $variables['node']->id(),
      'view_mode' => 'pdf'
    ], $url_options)->toString();
  }
}

Proposed resolution

Thought the above might help and I'm interested if there is a better way to do this?

💬 Support request
Status

Active

Version

2.0

Component

Documentation

Created by

🇬🇧United Kingdom matt b

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

Comments & Activities

Production build 0.71.5 2024