[Drupal] How to generate a PDF file by passing custom data using TCPDF library?

| | 2 min read

In this article I like to explain how to create a pdf document in Drupal. We will be using a PHP library called TCPDF. TCPDF is the only PHP free and open source library which comprise full support for right-to-left languages, also includes bidirectional algorithm and UTF-8.

TCPDF is an external library for Drupal, so we need to download the files and put it in the appropriate location. TCPDF can be downloaded from http://www.tcpdf.org. Download the library you will be getting a zip file, extract and move the files to drupal inststallion folder. Move the files to path /sites/all/libraries/.

We will be working with tcpdf inside module files. Include files 'tcpdf_include.php, tcpdf.php' to the module which contains implementation functions. Lets have a look at simple example rendering pdf using tcpdf.


SetCreator(PDF_CREATOR);

  $pdf->SetAuthor('Mike');

  $pdf->SetTitle('Hello PDF');

  $pdf->SetSubject('TCPDF Article');

  $pdf->SetKeywords('TCPDF, PDF, article, test, guide');

  $pdf->SetFont('dejavusans', '', 14, '', true);  

  $pdf->AddPage(); 

  $html = <<Heading

Hello World

EOD; // Print content using writeHTMLCell() $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true); //Close and output PDF document $pdf->Output('helloworld.pdf', 'I'); ?>

In the above code SetCreator, SetAuthor, AddPage are set of methods which are used to customize the pdf. Using tcpdf contents are arranged using coordinates. From the above snippet $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true); "0,0" represents the coordinates system. For line break use Ln();

We will be creating a order detail sheet as an implementation of tcpdf in drupal. For the order detail page I have came across the following functions in tcpdf.

  • SetFillColor([val], [val], [val]): We could set fill color as RGB color model to this method.
  • SetTextColor(): Pass color codes to this method.
  • SetFont(): Formats the style of text. This method accepts 3 parameters font name, font weight and font size. For example, SetFont('helvetica', 'B', 20);
  • Ln(): Function used for new line.
  • SetMargins(): The method accepts 3 parameters left, top and right (in cm).
  • SetFooterMargin(): Bottom margin can be set with this function.
  • Cell(): Used to print text. Method accepts text with margins left, right etc.

You could get more features/functions of tcpdf from the tcpdf.org site. In the next article we will be discussing a more detailed implementation of tcpdf in Drupal.

Hope you have found this note useful. Thank you.

Please feel free to share your thoughts and suggestions regarding this here.