Download TCPDF
Go to the github.com/tecnickcom/tcpdf and download the code. You can use this direct link to download zip file.
Minimal example
Here’s a very basic and only required code to create a pdf.
$path = getcwd() . '/TCPDF-main/tcpdf.php';
if ( file_exists($path) ) {
require_once($path);
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->setPrintHeader(false); // remove default page header
$pdf->SetFooterMargin(10); // add default page footer with margin
$pdf->AddPage(); // adding a page
$html = 'Hello World!';
$pdf->writeHtml($html);
$pdf->Output('example.pdf', 'I'); // sending pdf inline to browser
} else {
error_log('TCPDF file not found.');
}
Complete Example
$path = getcwd() . '/TCPDF-main/tcpdf.php';
if ( file_exists($path) ) {
require_once($path);
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->setPrintHeader(false); // remove default page header
$pdf->SetFooterMargin(10); // add default page footer with margin
$pdf->AddPage(); // adding a page
$html = 'Hello World!';
$pdf->writeHtml($html);
$pdf->Output('example.pdf', 'I'); // sending pdf inline to browser
} else {
error_log('TCPDF file not found.');
}
Set Margins
// set margins left, top, right
$pdf->SetMargins(5, 10, 5);
// set page header margin top
$pdf->SetHeaderMargin(25);
// set page footer margin bottom
$pdf->SetFooterMargin(8);
Set automatic page breaks
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
Add Font
$pdf->setFontSubsetting(true);
$pdf->SetFont('dejavusans', '', 12, '', true);
Remove default Header and Footer
Create pdf file without header and footer date. You can optionally remove the header but keep the footer as it contains the number of page related data.
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
Output PDF file
Send the document to a given destination: string, local file or browser. In the last case, the plug-in of a browser to display pdf file may be used (if present) or a download (“Save as” dialog box) may be forced. The method first calls Close() if necessary to terminate the document.
- I: send the file inline to the browser (default).
- D: send to the browser and force a file download with the name given.
- F: save to a local server file with the name given by name.
- S: return the document as a string. name is ignored.
- FI: equivalent to F + I option.
- FD: equivalent to F + D option.
$pdf->Output('my-pdf-file.pdf', 'D');
Bonus Tips
Get current page number with $this->PageNo()
as integer. This is useful when you want to align text to the right because $this->getAliasNumPage()
does not return integer but returns a placeholder string ”{:pnp:}“.
class MyPDF extends TCPDF {
function Footer(){
$curr_page = $this->PageNo();
$this->Cell(0, 0, 'Page ' . $curr_page, 'T', 1, 'R');
}
}