Installation:
composer require whiteoctober/tcpdf-bundle
For Symfony 3.4+, use the fork instead.
Enable the Bundle:
Add to AppKernel.php (Symfony < 4):
new WhiteOctober\TCPDFBundle\WhiteOctoberTCPDFBundle(),
For Symfony 4+, add to config/bundles.php:
WhiteOctober\TCPDFBundle\WhiteOctoberTCPDFBundle::class => ['all' => true],
First Use Case: Generate a basic PDF in a controller:
use WhiteOctober\TCPDFBundle\TCPDF\TCPDF;
use WhiteOctober\TCPDFBundle\TCPDF\TCPDFException;
public function generatePdfAction()
{
$pdf = new TCPDF();
$pdf->AddPage();
$pdf->SetFont('helvetica', 'B', 20);
$pdf->Cell(0, 10, 'Hello, TCPDF!', 0, 1, 'C');
$pdf->Output('example.pdf', 'D'); // 'D' forces download
}
Where to Look First:
twig/tcpdf.html.twig templates in the bundle.PDF Generation in Controllers:
public function generateInvoicePdf($invoiceId)
{
$pdf = new TCPDF();
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 12);
// Fetch invoice data (e.g., from Doctrine)
$invoice = $this->getDoctrine()->getRepository(Invoice::class)->find($invoiceId);
// Write data to PDF
$pdf->Cell(0, 10, 'Invoice #'.$invoice->getNumber(), 0, 1, 'L');
$pdf->Ln(10);
$pdf->writeHTML($this->renderView('Invoice/pdf_content.html.twig', ['invoice' => $invoice]), true, false, true);
return $pdf->Output('invoice_'.$invoiceId.'.pdf', 'D');
}
Twig Integration (if using Twig):
templates/Invoice/pdf_content.html.twig):
<table>
<tr><td>Customer:</td><td>{{ invoice.customer.name }}</td></tr>
<tr><td>Amount:</td><td>{{ invoice.amount }} €</td></tr>
</table>
$html = $this->renderView('Invoice/pdf_content.html.twig', ['invoice' => $invoice]);
$pdf->writeHTML($html, true, false, true);
Reusable PDF Services: Create a service to encapsulate PDF logic:
# config/services.yaml
services:
App\Service\PdfGenerator:
arguments:
$tcpdf: '@white_october_tcpdf.tcpdf'
// src/Service/PdfGenerator.php
class PdfGenerator {
private $tcpdf;
public function __construct(TCPDF $tcpdf) {
$this->tcpdf = $tcpdf;
}
public function generateFromHtml(string $html, string $filename): string {
$this->tcpdf->AddPage();
$this->tcpdf->writeHTML($html);
return $this->tcpdf->Output($filename, 'S'); // 'S' returns as string
}
}
Streaming PDFs: Return PDF as a stream (e.g., for APIs):
public function streamPdfAction()
{
$pdf = new TCPDF();
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 12);
$pdf->Cell(0, 10, 'Streamed PDF', 0, 1, 'C');
return new StreamedResponse(
function () use ($pdf) {
$pdf->Output('streamed.pdf', 'S');
},
200,
['Content-Type' => 'application/pdf']
);
}
Dynamic Styling: Use TCPDF methods for dynamic styling:
$pdf->SetFont('helvetica', 'B', 14); // Bold, size 14
$pdf->SetTextColor(0, 0, 255); // Blue text
$pdf->SetDrawColor(255, 0, 0); // Red borders
$pdf->Rect(10, 10, 50, 10, 'D'); // Draw a red box
foreach ($invoice->getItems() as $item) {
$pdf->Cell(0, 10, $item->getDescription(), 0, 1);
$pdf->Cell(0, 10, sprintf('%.2f €', $item->getPrice()), 0, 1, 'R');
}
$pdf->AddTTFFont('path/to/font.ttf', 'TrueTypeUnicode', '', 32);
$pdf->Image('path/to/image.png', 15, 15, 20, '', 'PNG');
$pdf->SetHeaderData('path/to/logo.png', 20, 'Title', 'Subtitle');
$pdf->SetFooterData(['Title', 'Page'], PDF_PAGE_COUNT);
$pdf->SetFooterMargin(10);
Font Issues:
.ttf for TrueType).AddTTFFont() with the correct path and encoding.Memory Limits:
memory_limit in php.ini or optimize PDF generation (e.g., use writeHTML() for complex layouts instead of Cell()).Encoding Problems:
é, ü) may render incorrectly.$pdf->SetFont('helvetica', '', '', 'win1252'); // or 'utf-8'
Caching:
$pdf->setFontCache('path/to/cache/dir');
Deprecated Methods:
AddPage() without parameters).Symfony 4+ Autowiring:
TCPDF by default. Use:
services:
App\Service\PdfService:
arguments:
$tcpdf: '@white_october_tcpdf.tcpdf'
Error Handling: Wrap TCPDF calls in try-catch:
try {
$pdf->Output('file.pdf');
} catch (TCPDFException $e) {
// Log or handle error
throw new \RuntimeException('PDF generation failed: '.$e->getMessage());
}
Logging: Enable TCPDF debug mode:
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->setDebug(true); // Logs errors to stdout
Output Modes:
'I': Send inline (browser displays).'D': Force download.'S': Return as string (for APIs).'F': Save to file (specify path).Performance:
writeHTML().TCPDF to add reusable methods:
class CustomTCPDF extends TCPDF {
public function addTitle(string $title, int $size = 16) {
How can I help you explore Laravel packages today?