2 min read

Creating a PDF in a component

This recipe explains how to create a PDF view in a Joomla! MVC component. Adding PDF views is a relatively quick process, and it significantly improves the functionality of a component.

Getting ready

Like any other view format, we must create a new JView subclass to create a PDF view. This should be located in the corresponding view’s folder and the file should be named view.pdf.php. For example, for the myview view in the mycomponent component, we create the components/com_mycomponent/views/myview/view.pdf.php file, in which we place the MycomponentViewMyview class, which extends JView.

How to do it…

The first thing we do is override the display() method in order to change the PDF document. We modify the document using the mutator methods. The first method changes the document title, this is the title normally shown in the title bar of the PDF viewer.

$document->setTitle($title);

The next method changes the filename. This is especially useful if the user is likely to save the file, as this will be the default name the user is prompted to save the file as.

$document->setName($filename);

The next method sets the document description, sometimes referred to as the subject. This should only be a very brief description of the document.

$document->setDescription($description);

The next method sets the document metadata. Currently, only keywords are supported. It is possible to set other metadata, but it will not be used in the document.

$document->setMetaData('keywords', $keywords);

So far, all of the methods do not print anything to the body of the PDF itself. The next method adds a common header to every page. Note that the header text itself is not formatted.

$document->setHeader("My PDF Document TitlenMy Subtitle");

Lastly, we can add content to the main body of the PDF document. We achieve this in the normal way by simply outputting the content.

echo 'This is my PDF! ';

The outputted data can be formatted using some basic HTML tags. The following tags are supported:

Type

Tags

Format

<b>, <u>, <i>, <strong>, <em>, <sup>, <sub>, <small>, <font>

Heading

<h1>, <h2>, <h3>, <h4>, <h5>, <h6>

Indentation

<blockquote>

Linked

<a>, <img>

List

<ol>, <ul>, <li>

Spacing

<p>, <br>, <hr>

Table

<table>, <tr>, <td>, <th>

LEAVE A REPLY

Please enter your comment!
Please enter your name here