Nerds who love the symfony-project
4 Feb
Why tcpdf
TCPDF is current, well supported, well used and more up to date than equivalents such as domPDF which have had an unresolved security advisory out since 02/05/2008.
It is also very easy to integrate into a symfony project since it does not require external libraries for basic functions.
Features
The features below are from the TCPDF home page:
* no external libraries are required for the basic functions;
* supports all ISO page formats;
* supports custom page formats, margins and units of measure;
* supports UTF-8 Unicode and Right-To-Left languages;
* supports TrueTypeUnicode, OpenTypeUnicode, TrueType, OpenType, Type1 and CID-0 fonts;
* supports document encryption;
* includes methods to publish some (x)HTML code;
* includes graphic (geometric) and transformation methods;
* includes Javascript and forms support;
* includes a method to print various barcode formats (CODE 39, CODE 39 EXTENDED, Interleaved 2 of 5, CODE 128 A/B/C, EAN 13, UPC-A, POSTNET, CODABAR);
* includes methods to set Bookmarks and print a Table of Content;
* includes a method to move pages;
* includes methods for automatic page header and footer management;
* supports automatic page break;
* supports automatic page numbering and page groups;
* supports automatic line break and text justification;
* supports JPEG and PNG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImagMagick;
* supports stroke and clipping mode for text;
* supports clipping masks;
* supports Grayscale, RGB, CMYK, Spot Colors and Transparencies;
* supports several annotations, including links, text and file attachments;
* supports page compression (requires zlib extension);
* supports user rights management so Adobe Reader users can save filled-in copies of forms they complete.
Using tcpdf in a symfony project
I’m assuming here that you’re using PHP5 and that you’re happy to simply try this out by including the TCPDF libs in a project (as opposed to making them accessible by any project on your system).
Start by downloading TCPDF and unpacking this into your project lib folder … so where PROJECT is your project directory:
cd PROJECT/lib curl -O http://transact.dl.sourceforge.net/sourceforge/tcpdf/tcpdf_4_5_010.zip unzip tcpdf_4_5_010.zip
That’s it you’re ready - before commiting to svn (or your preferred code version repo) I also “clean up” the above PROJECT/lib/tcpdf/ directory by doing this:
rm -rf doc examples CHANGELOG.TXT README.TXTConfiguration
One can modify the properties of the generated PDF documents in the PROJECT/lib/tcpdf/config/tcpdf_config.php file.
These 6 settings are particularly important for the look and feel of the document.
The “my_logo.JPG” file should be placed in the PROJECT/lib/tcpdf/images/ directory.
What follows below is a list of the kind of properties you may wish to modify.
define ('PDF_PAGE_FORMAT', 'A4'); define ('PDF_PAGE_ORIENTATION', 'P'); define ('PDF_UNIT', 'mm'); define ('PDF_MARGIN_HEADER', 5); define ('PDF_MARGIN_FOOTER', 10); define ('PDF_MARGIN_TOP', 27); define ('PDF_MARGIN_BOTTOM', 25); define ('PDF_MARGIN_LEFT', 15); define ('PDF_MARGIN_RIGHT', 15); define ('PDF_FONT_NAME_MAIN', 'helvetica'); define ('PDF_FONT_SIZE_MAIN', 10); define ('PDF_FONT_NAME_DATA', 'helvetica'); define ('PDF_FONT_SIZE_DATA', 8);
Write your own class
Within the lib folder of the PROJECT, write a myPDF.php class that calls the tcpdf lib and writes a pdf file based on your PROJECT requirements.
Coupled with the configuration shown above, and the code below, it is possible to create a PDF document containing a table of data based on an array.
<?php require_once('tcpdf/config/lang/eng.php'); require_once('tcpdf/tcpdf.php'); // extend TCPF with custom functions class myPDF extends TCPDF { // Colored table public function ColoredTable($header,$data) { // setting up colours, widths and normal - not bold fontSetDrawColor(0, 0, 0); $this->SetLineWidth(0.3); $this->SetFillColor(211, 211, 211); $this->SetTextColor(0); $this->SetFont(''); // Data foreach($data as $row) { // custom call to do a two column table on one page // left column is smaller so as to accomodate longer text in the right column $this->Cell(70, 6, $row[0], 'LTR', 0, 'C', 1); $this->Cell(110, 6, $row[1], 'LTR', 0, 'C', 0); $this->Ln(); } $this->Cell(0, 0, '', 'T'); } }
The code above expects an array of data to be rendered into table rows. The array is of this format:
[0] => Array ( [0] => sfNerd: [1] => eHabib ) [1] => Array ( [0] => sfNerd: [1] => BigM ) [2] => Array ( [0] => sfNerd [1] => AK )
The following tcpdf methods are used to render the table with appropriate colours, line widths, populate content in table cells.
You can invoke the above class in the following manner (refactor to suit your needs etc). Place this code you your desired Symfony module/action.
public static function buildPDF($order_page, $myfileloc){ // array used to define the language and charset of the pdf file to be generated $language_meta = Array(); $language_meta['a_meta_charset'] = 'UTF-8'; $language_meta['a_meta_dir'] = 'ltr'; $language_meta['a_meta_language'] = 'en'; $language_meta['w_page'] = 'page'; // create new PDF document $pdf = new myPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); // set document information $pdf->SetAuthor('An Order Form'); $pdf->SetTitle('An Order'); $pdf->SetSubject('An Order'); // set default header data $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING); // set header and footer fonts $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); //set margins $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); //set auto page breaks $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); //set image scale factor $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); //set some language-dependent strings $pdf->setLanguageArray($language_meta); // set font $pdf->SetFont('helvetica', '', 12); // add a page $pdf->AddPage(); //Column titles $header = array('Name', 'Type'); // lets build the array of data that needs to be published in a pdf $value=''; $data = array(); // iterate the orderpage variable and build our array foreach($order_page as $key => $val) { if($val != null) { array_push($data,array($key,$val)); } } // insert a colored table into the document with the above vars // ColoredTable is the function defined in a custom class in lib/ $pdf->ColoredTable($header, $data); //Close and output PDF document $pdf->Output($myfileloc, 'F'); }
All of these methods are documented here
Documentation and further examples
Excellent documentation on all aspects of TCPDF can be found here.
Usage examples can be found here.
Using the documentation and examples, one can quickly establish how to generate PDF documents using TCPDF.
10 Responses for "Generate PDF documents using TCPDF in Symfony"
That’s a pretty cool tutorial, thanks
I have got one little thing to say. You should move the tcpdf library into /lib/vendor instead of /lib. That’s a bit better
It’s interesting, I also use tcpdf on my current sf project.
I’ve stored the general preferencies in my app.yml :
all:
tcpdf:
k_path_images: ‘/images/’ # images directory
pdf_page_format: ‘A4′ # page format
pdf_page_orientation: ‘P’ # page orientation (P=portrait, L=landscape)
pdf_producer: ‘http://www.foobar.com’ # define default PDF document producer
pdf_creator: ‘FooBarProject’ # document creator
pdf_author: ‘FooBarProject’ # document author
pdf_header_title: ‘FooBarProject Example’# header title
pdf_header_string: ‘by FooBar - http://www.foobar.com‘ # header description string
pdf_header_logo: ‘tcpdf_logo.jpg’ # image logo
pdf_header_logo_width: ‘30′ # header logo image width [mm]
pdf_unit: ‘mm’ # document unit of measure [pt=point, mm=millimeter, cm=centimeter, in=inch]
pdf_margin_header: ‘5′ # header margin
pdf_margin_footer: ‘10′ # footer margin
pdf_margin_top: ‘27′ # top margin
pdf_margin_bottom: ‘25′ # bottom margin
pdf_margin_left: ‘15′ # left margin
pdf_margin_right: ‘15′ # right margin
pdf_font_name_main: ‘helvetica’ # main font name
pdf_font_size_main: ‘10′ # main font size
pdf_font_name_data: ‘helvetica’ # data font name
pdf_font_size_data: ‘8′ # data font size
pdf_image_scale_ratio: ‘4′ # Ratio used to scale the images
head_magnification: ‘1.1′ # magnification factor for titles
k_cell_height_ratio: ‘1.25′ # height of cell repect font height
k_title_magnification: ‘1.3′ # title magnification respect main font size
k_small_ratio: ” # reduction factor for small font
Then, in the myapp/lib/vendor/tcpdf/tcpf.php file, I’ve linked the fields. For ex :
define(’PDF_PRODUCER’, sfConfig::get(’app_tcpdf_pdf_producer’));
It’s a little longer to install, but now tcpdf preferencies are stored with the other config parameters of my project.
For the pdf generation, I’ve also extended the TCPDF class.
Where do you store The files that generate pdf ?
I store them in the templates directory for each module.
For ex : showSuccess.pdf.php
thanks @Hugo - good tip re the lib/vendor placement
@eric - thanks - I keep the code that generates the pdf in my actions file. Good tip re using the app.yml config file, it would make things a bit easier to maintain from the config file…
I like this. I’ll be using this and I’ll give feedback about it later…
Has anyone tried to use sfTCPDF to send a PDF as an email attachmeny in symfony?
@Shadley,
I did it in one of my pasts projects (using just the FPDF lib)… My solution was:
- Build the pdf file
- Store it in a special folder
- Attach the file in a mail
- No delete the file
And then I made a task in order to be executed by a cron every night deleting all the pdf files in the special folder I said.
Hope it helps.
Best,
Gustavo G.
please can you help me how to create the form which contain textbox and button. and I have to handle the event of that button.
Couple of questions:
1. How to add current date and Page X of Y at the foot?
2. How to save pdf to file AND launch file to browser at the same time?
Thank you in advance.
Leona
nice tutorial !
i’ve a small tip,
if you want add an .pdf extension you have to add the following rules to your web/.htaccess:
RewriteCond %{REQUEST_URI} !\.pdf$
Leave a reply