TCPDF

The TCPDF module integrates the TCPDF library, which generates PDF documents in PHP and converts HTML snippets to PDF with UTF-8 support. It is an API for developers: the module has no user interface of its own.

Features

  • tcpdf_get_instance() returns a \Drupal\tcpdf\TCPDFDrupal object, which extends \TCPDF, so every TCPDF method is available.
  • DrupalInitialize() sets the document information (title, author, subject, keywords; defaults to the site name), margins and fonts, and adds the first page.
  • Headers and footers can be HTML or any PHP callable (function name, [$object, 'method'], closure), without writing a custom TCPDF subclass.
  • Custom subclasses of TCPDFDrupal and custom TCPDF configuration files can be passed to tcpdf_get_instance().
  • The status report shows whether the TCPDF library and its fonts are available.
  • The included TCPDF Example module shows a complete PDF download.

Versions

  • 3.x: TCPDF 7, Drupal 11.3 or later and Drupal 12. Recommended.
  • 2.1.x: TCPDF 6, Drupal 10.6, 11.3 or later and Drupal 12. TCPDF 6 has reached end of life and receives no fixes anymore, including security fixes (TCPDF#867). Use it only for Drupal 10 sites.

Installation

composer require drupal/tcpdf
drush pm:install tcpdf

TCPDF 7 needs font files that the package tecnickcom/tc-lib-pdf-font does not include. Build them once, and again after every update of that package:

php vendor/tecnickcom/tc-lib-pdf-font/util/build_fonts.php

To rebuild them automatically, or to keep them outside of vendor/ with $settings['tcpdf_fonts_path'], see the README. The status report shows whether TCPDF finds the fonts.

Usage

$pdf = tcpdf_get_instance();
$pdf->DrupalInitialize([
  'title' => 'Report',
  'footer' => ['html' => '<p>Generated by Drupal</p>'],
]);
$pdf->writeHTML('<h1>Hello</h1><p>Some content.</p>');
$content = $pdf->Output('report.pdf', 'S');

TCPDF 7 only reads local files, such as images, from trusted directories: the system temporary directory, the Drupal root and its own library directories. Image URLs are downloaded without the user's session. To embed files from the private file system, pass a local path, for example \Drupal::service('file_system')->realpath('private://image.png'), and add the directory to K_ALLOWED_PATHS in settings.php, as described in the README.

Similar projects

  • Entity Print: PDF output of entities with a choice of PDF engines, including a user interface.

Project information

Releases