TCPDF
Deprecated: PHP PDF library, superseded by tc-lib-pdf (https://github.com/tecnickcom/tc-lib-pdf)
Top Related Projects
HTML to PDF converter for PHP
PHP library generating PDF files from UTF-8 encoded HTML
A pure PHP library for reading and writing word processing documents
A DOMPDF Wrapper for Laravel
A slim PHP wrapper around wkhtmltopdf with an easy to use and clean OOP interface
Quick Overview
TCPDF is a popular PHP library for generating PDF documents. It provides a comprehensive set of tools and functions to create complex PDF files with features like text formatting, images, tables, and more. TCPDF is widely used in web applications and content management systems for generating reports, invoices, and other document types.
Pros
- Extensive feature set for creating complex PDF documents
- Supports various fonts, including Unicode and right-to-left languages
- Includes barcode generation capabilities
- Well-documented with many examples and tutorials
Cons
- Large codebase, which can lead to slower performance compared to simpler PDF libraries
- Steep learning curve for beginners due to its extensive functionality
- Some users report occasional issues with text alignment and positioning
- Limited support for newer PHP versions (primarily targets PHP 5.x)
Code Examples
- Creating a simple PDF document:
require_once('tcpdf/tcpdf.php');
$pdf = new TCPDF();
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 12);
$pdf->Cell(0, 10, 'Hello, World!', 0, 1);
$pdf->Output('hello_world.pdf', 'F');
- Adding an image to a PDF:
$pdf->Image('path/to/image.jpg', 10, 10, 90, 0, 'JPG');
- Creating a table in the PDF:
$html = '
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
</tr>
</table>';
$pdf->writeHTML($html, true, false, true, false, '');
Getting Started
-
Install TCPDF using Composer:
composer require tecnickcom/tcpdf -
Create a new PHP file and include the TCPDF library:
require_once('vendor/autoload.php'); -
Create a new TCPDF instance and start generating your PDF:
$pdf = new TCPDF(); $pdf->AddPage(); $pdf->SetFont('helvetica', '', 12); $pdf->Cell(0, 10, 'Your PDF content goes here', 0, 1); $pdf->Output('output.pdf', 'F');
This will create a basic PDF file named 'output.pdf' in the same directory as your PHP script.
Competitor Comparisons
HTML to PDF converter for PHP
Pros of dompdf
- Easier to use for converting HTML/CSS to PDF
- Better support for modern CSS features
- More actively maintained with frequent updates
Cons of dompdf
- Slower performance for large documents
- Less extensive feature set compared to TCPDF
- May have compatibility issues with complex layouts
Code Comparison
dompdf:
require_once 'dompdf/autoload.inc.php';
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->render();
$dompdf->stream("document.pdf");
TCPDF:
require_once('tcpdf/tcpdf.php');
$pdf = new TCPDF();
$pdf->AddPage();
$pdf->writeHTML($html);
$pdf->Output('document.pdf', 'I');
Both libraries offer straightforward ways to generate PDFs from HTML, but dompdf's approach is slightly more concise. TCPDF provides more granular control over the PDF creation process, which can be beneficial for complex documents but may require more code for simple tasks.
dompdf is generally easier to use for basic HTML-to-PDF conversion, while TCPDF offers more advanced features and better performance for large documents. The choice between the two depends on the specific requirements of your project, such as document complexity, performance needs, and desired CSS support.
PHP library generating PDF files from UTF-8 encoded HTML
Pros of mpdf
- Better support for CSS and HTML5, allowing for easier styling and layout
- Faster rendering speed, especially for complex documents
- More active development and community support
Cons of mpdf
- Larger file size and memory footprint
- Less extensive documentation compared to TCPDF
- Fewer built-in features for advanced PDF manipulation
Code Comparison
mpdf:
$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML('<h1>Hello World</h1>');
$mpdf->Output('document.pdf', 'F');
TCPDF:
$pdf = new TCPDF();
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 12);
$pdf->Cell(0, 10, 'Hello World', 0, 1);
$pdf->Output('document.pdf', 'F');
Both libraries offer PHP-based PDF generation, but mpdf focuses on HTML-to-PDF conversion, while TCPDF provides more low-level PDF creation methods. mpdf's approach is generally more intuitive for web developers familiar with HTML and CSS, while TCPDF offers finer control over PDF elements and structure.
A pure PHP library for reading and writing word processing documents
Pros of PHPWord
- Specialized for creating and manipulating Word documents
- Supports a wider range of Word-specific features and formatting options
- More intuitive API for working with Word document structures
Cons of PHPWord
- Limited to Word document generation, less versatile than TCPDF
- May have a steeper learning curve for users familiar with PDF-centric libraries
- Potentially slower performance when dealing with large documents
Code Comparison
PHPWord:
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$section->addText('Hello World!');
$writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$writer->save('helloWorld.docx');
TCPDF:
$pdf = new TCPDF();
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 12);
$pdf->Cell(0, 10, 'Hello World!');
$pdf->Output('helloWorld.pdf', 'F');
Both libraries offer straightforward ways to create documents, but PHPWord is tailored for Word documents, while TCPDF focuses on PDF generation. PHPWord provides more Word-specific features, while TCPDF offers greater flexibility for creating various types of PDF documents.
A DOMPDF Wrapper for Laravel
Pros of laravel-dompdf
- Seamless integration with Laravel framework
- Easy to use with Laravel's Facade system
- Supports HTML5 and CSS3 for more modern styling options
Cons of laravel-dompdf
- Limited support for complex layouts and advanced PDF features
- May have performance issues with large or complex documents
- Less frequent updates compared to TCPDF
Code Comparison
laravel-dompdf:
use Barryvdh\DomPDF\Facade\Pdf;
$pdf = Pdf::loadView('pdf.invoice', $data);
return $pdf->download('invoice.pdf');
TCPDF:
$pdf = new TCPDF();
$pdf->AddPage();
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output('document.pdf', 'D');
Both libraries offer straightforward ways to generate PDFs, but laravel-dompdf provides a more Laravel-centric approach with its Facade. TCPDF offers more granular control over the PDF creation process, which can be beneficial for complex documents but may require more code for basic tasks.
A slim PHP wrapper around wkhtmltopdf with an easy to use and clean OOP interface
Pros of phpwkhtmltopdf
- Renders HTML/CSS accurately, including complex layouts and modern web features
- Supports JavaScript execution, allowing dynamic content generation
- Faster PDF generation for complex documents with many elements
Cons of phpwkhtmltopdf
- Requires external dependencies (wkhtmltopdf binary)
- Less control over low-level PDF structure and metadata
- May have compatibility issues with some server environments
Code Comparison
TCPDF:
$pdf = new TCPDF();
$pdf->AddPage();
$pdf->writeHTML($html);
$pdf->Output('document.pdf', 'F');
phpwkhtmltopdf:
$pdf = new Pdf($html);
$pdf->saveAs('document.pdf');
TCPDF offers more granular control over PDF creation, while phpwkhtmltopdf provides a simpler API for converting HTML to PDF. TCPDF is better suited for generating PDFs from scratch or with precise layout requirements, whereas phpwkhtmltopdf excels at converting existing web pages or complex HTML/CSS layouts into PDFs with high fidelity.
Choose TCPDF for fine-grained control and server-side PDF generation without external dependencies. Opt for phpwkhtmltopdf when dealing with modern web layouts or when accurate HTML/CSS rendering is crucial.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
TCPDF (DEPRECATED â use tc-lib-pdf)
[!WARNING] TCPDF is in maintenance-only mode. Active development has moved to tc-lib-pdf, its modern, modular successor â new projects should start there.
TCPDF is still installed 100M+ times across 500+ PHP packages. If your product depends on it, sponsor continued maintenance â to keep this shared infrastructure secure and patched.
Overview
TCPDF is a pure-PHP library for generating PDF documents and barcodes directly in application code.
It has been widely used across many PHP stacks and still provides a complete feature set for text rendering, page composition, graphics, signatures, forms, and standards-oriented output.
| Package | tecnickcom/tcpdf |
| Author | Nicola Asuni info@tecnick.com |
| License | GNU LGPL v3 (see LICENSE.TXT) |
| Website | http://www.tcpdf.org |
| Source | https://github.com/tecnickcom/TCPDF |
Architecture: Compatibility Facade over tc-lib-pdf
Starting with version 7, the TCPDF class no longer contains its own PDF engine.
It is a compatibility facade: every public TCPDF method is a thin wrapper that
delegates the actual PDF generation to the modern tecnickcom/tc-lib-pdf engine
(\Com\Tecnick\Pdf\Tcpdf), while a small internal state layer reproduces the legacy
stateful cursor and page model (current X/Y, margins, fonts, colors, automatic page
breaks, headers/footers).
What this means in practice:
- The public API is (mostly) unchanged. All 291 public method signatures (names, parameters,
defaults) are identical to legacy TCPDF; existing integrations keep calling
new TCPDF(...),AddPage(),SetFont(),Cell(),writeHTML(),Output()exactly as before. One method is new:getPDFFilename()returns the file nameOutput()used, which the engine sanitizes. - Rendering is done by the modern engine. Text layout, HTML/CSS, fonts, graphics,
barcodes, encryption, signatures and output generation come from the
tc-lib-*libraries. - Per-method delegation status is documented. See MAPPING.md for the
status of every public method (
delegated,adapter,shim,intentional-noop,blocked) with notes; the table is machine-verified against the class. - Output is structurally equivalent, not byte-identical. Documents render with the same page sizes and content, but the modern engine's line-breaking and font metrics can differ slightly from the legacy implementation (long flowing documents may paginate one page earlier or later).
- Some legacy behaviors are intentionally not reproduced. A few features are dropped or changed where the modern engine's model takes precedence (legacy font definitions, EPS/AI vector import, always-on stream compression, policy-based local file access, assorted no-ops). See Breaking Changes below and the per-method notes in MAPPING.md for the full list.
Deprecation Notice
TCPDF is deprecated and in maintenance-only mode.
Active feature development has moved to tc-lib-pdf, the modern and modular successor.
For new projects, use tecnickcom/tc-lib-pdf. This repository remains available for legacy systems and critical compatibility fixes.
Migration Path
- New projects: install
tecnickcom/tc-lib-pdf. - Existing TCPDF users: keep TCPDF for current production workloads and migrate in phases.
- Teams seeking modern architecture, Composer-first design, and stronger type-safety should prioritize
tc-lib-pdf.
Migrating Font Assets
TCPDF has migrated font loading to the tc-lib font stack (see "Breaking Changes" below).
tecnickcom/tc-lib-pdfis the Composer entrypoint.- Font assets are provided by
tecnickcom/tc-lib-pdf-fontand discovered undervendor/tecnickcom/tc-lib-pdf-font/target/fonts/. - Repository-shipped
fonts/assets are removed; TCPDF now resolves bundled fonts from tc-lib assets.
Who is affected:
- Deployments that relied on local
fonts/files without Composer dependencies. - Applications with custom
K_PATH_FONTSassumptions tied to a repository-relative fonts folder. - Integrations that use custom or generated font definitions and expect PHP-only descriptor files.
How to migrate custom font usage:
- Install dependencies with Composer.
- Ensure tc-lib font assets are available in
vendor/tecnickcom/tc-lib-pdf-font/target/fonts/. - Keep using
SetFont()/AddFont()from TCPDF, but validate that each custom family resolves from tc-lib assets or from your explicit font path. - Update deployment packaging so
vendor/font assets are shipped in production.
Font generation procedure:
Font assets are generated at install time and are not shipped in the package. Composer runs the scripts declared by the root project only, so a project that requires TCPDF as a dependency must run the generation itself.
In a project that requires TCPDF, add the step to its own composer.json:
{
"scripts": {
"tc-lib-pdf-fonts": [
"[ -d vendor/tecnickcom/tc-lib-pdf-font ] && make -C vendor/tecnickcom/tc-lib-pdf-font deps fonts || true"
],
"post-install-cmd": [
"@tc-lib-pdf-fonts"
],
"post-update-cmd": [
"@tc-lib-pdf-fonts"
],
"post-autoload-dump": [
"@tc-lib-pdf-fonts"
]
}
}
This covers composer install, composer update, composer require and composer dump-autoload. To generate them once instead, run the build from the project root:
make -C vendor/tecnickcom/tc-lib-pdf-font deps fonts
In a checkout of this repository, use the Makefile targets:
- Run
make depsto install Composer dependencies and initialize tc-lib font assets. - Run
make fontsto initialize fonts only when missing. - Run
make fonts-rebuildto force a full font asset rebuild.
Expected generated asset sentinel:
vendor/tecnickcom/tc-lib-pdf-font/target/fonts/core/helvetica.json
A missing asset directory is reported as unable to read file: helvetica.json on the first page. The full font documentation is at tcpdf.org/docs/fonts.
Compatibility notes:
- TCPDF checks configured font paths and tc-lib font assets.
- JSON font descriptors from tc-lib are accepted by the TCPDF
AddFont()path. - Legacy PHP font descriptors (
fontname.php+fontname.z) are no longer supported (see "Breaking Changes" below); convert the original TTF/OTF with thetc-lib-pdf-fontimporter instead.
Example:
require __DIR__.'/vendor/autoload.php';
// Optional: TCPDF resolves the installed tc-lib-pdf-font package on its own.
// Define the constant only to use font assets from another directory.
define('K_PATH_FONTS', '/opt/app/fonts/');
$pdf->SetFont('helvetica', '', 11);
Safe migration checklist:
- Require
tecnickcom/tc-lib-pdfin Composer and install dependencies. - Confirm the font asset directory exists under
vendor/tecnickcom/tc-lib-pdf-font/target/fonts/. - Run your PDF smoke tests for headers, body text, bold/italic, RTL text, and Unicode text.
- Verify no runtime path assumptions require repository
fonts/files. - Remove legacy
K_PATH_FONTSoverrides that point to removed directories. - Re-run regression output comparisons on representative documents.
Why Migrate to tc-lib-pdf
- Larger feature set: tc-lib-pdf offers many more features than TCPDF, and it is where new ones are added.
- Modern architecture: modular libraries and cleaner component boundaries improve maintainability.
- Better extensibility: new features are easier to add without patching a monolithic legacy core.
- Stronger tooling fit: modern package structure works better with static analysis, CI, and automated tests.
- Lower long-term risk: reduces technical debt tied to legacy APIs and supports ongoing PHP ecosystem evolution.
- Improved delivery speed: teams can implement and ship new PDF capabilities with less friction.
Migration still requires planning and regression checks to preserve rendering parity for existing documents.
Breaking Changes
The facade favors the modern engine model over bug-for-bug legacy emulation in the following areas. Each is a deliberate, documented contract change:
-
Font model. Fonts are resolved exclusively through the tc-lib-pdf-font stack: JSON definition files discovered under
K_PATH_FONTS(vendor/tecnickcom/tc-lib-pdf-font/target/fonts/, generated bymake fonts). The legacy TCPDF font definition format (fontname.php+fontname.z/fontname.ctg.z) is not supported and is not converted at runtime:SetFont()/AddFont()accept families known to the tc-lib font stack (core fonts, DejaVu, FreeFont, CID-0, ...) or definition files in the tc-lib JSON format via the font-file parameter.- Legacy-only bundled fonts (e.g.
aefurat,aealarabiya) are unavailable; requesting them throws a font exception. Use a tc-lib font with equivalent coverage (e.g.freeserif/dejavusansfor Arabic) or import the original TTF/OTF with thetc-lib-pdf-fontimporter. - Font subsetting, kerning and metrics follow the tc-lib implementation.
See "Migrating Font Assets" above for the step-by-step migration procedure.
-
Stream compression is always on.
setCompression(false)is a no-op; the engine always compresses content streams. -
EPS/AI vector import is dropped. The modern engine has no PostScript interpreter, so
ImageEps()ignores EPS/AI input. Convert EPS/AI artwork to SVG (e.g.inkscape file.eps --export-filename=file.svg) and useImageSVG()instead. As a convenience,ImageEps()dispatches SVG and raster file names to the modern paths. -
RC4 encryption is legacy-only.
setProtection()modes 0/1 still work, but the engine deprecates RC4; AES modes (2/3) are recommended.setProtection()must be called before the first page is added. -
Resource loading is policy-based. The engine restricts where external resources (images, fonts, SVG, imported PDFs) may be loaded from: local reads are limited to an allowlist of trusted directories and remote (HTTP/HTTPS) reads are disabled by default. The legacy
setAllowLocalFiles()toggle no longer widens access; the policy is driven by configuration constants instead (see Resource Loading Security).
Smaller deliberate no-ops (disk caching, setDocInfoUnicode(), header XObject template
caching, vector-image rasterization toggles, ...) are listed with their reasons in
MAPPING.md.
Resource Loading Security
External resources are fetched through the sandboxed file helper provided by
tc-lib-pdf / tc-lib-file. The sandbox enforces two independent allowlists, both
configurable via define() constants (read by tcpdf_autoconfig.php, overridable in
config/tcpdf_config.php or before the autoconfig runs):
| Constant | Type | Default | Purpose |
|---|---|---|---|
K_ALLOWED_PATHS | string[] | [] | Extra trusted local directory prefixes, merged on top of the built-in defaults. |
K_ALLOWED_HOSTS | string[] | [] | Trusted remote host names that enable HTTP/HTTPS loading. Empty keeps remote loading disabled. |
K_MAX_REMOTE_SIZE | int | 52428800 | Byte cap for a single remote download (50 MiB). |
K_CURLOPTS | array | [] | Extra CURLOPT_* => value pairs merged over the cURL defaults. |
Local reads. The built-in allowlist always covers the system temp directory,
K_PATH_MAIN, the bundled vendor/tecnickcom/ directory, the current working directory,
K_PATH_FONTS, K_PATH_IMAGES and the running script's directory. K_ALLOWED_PATHS
only ever widens this set â paths are resolved with realpath(), so non-existent or
unresolvable entries are silently ignored and traversal/symlink tricks collapse to their
canonical prefix. There is no way to read below the built-in roots.
Remote reads. Remote URL loading is off by default â the single most important
defense against SSRF when rendering untrusted HTML/markup. To opt in, list the exact
host names you trust in K_ALLOWED_HOSTS. TLS certificate verification and redirect
handling are enforced upstream and cannot be relaxed through K_CURLOPTS.
// Enable downloads from two trusted CDNs, cap them at 10 MiB, and add a custom timeout.
define('K_ALLOWED_HOSTS', ['cdn.example.com', 'assets.example.org']);
define('K_MAX_REMOTE_SIZE', 10 * 1024 * 1024);
define('K_CURLOPTS', [CURLOPT_TIMEOUT => 15]);
// Allow reading shared assets from outside the install tree.
define('K_ALLOWED_PATHS', ['/var/www/shared/assets/']);
Document encryption is a separate concern: setProtection() (item 4 above) controls
the PDF permission flags and password/public-key encryption and is unaffected by these
resource-loading constants.
Requirements
- PHP 8.2 or later
ext-curl
Optional extensions for richer output in some workflows: gd (automatic raster format conversion), zlib.
Development & Quality Assurance
This repository ships a real validation harness:
| Command | Purpose |
|---|---|
make deps | Install Composer dependencies, tooling, and initialize tc-lib font assets |
make qa | Full gate: mago lint + static analysis + PHPUnit suite |
make test | Run the PHPUnit suite (test/) |
make smoke | Run all 68 example scripts headless and verify the produced PDF documents |
make inventory | Regenerate the public method inventory reports |
make mapping | Verify the delegation map and regenerate MAPPING.md |
The example smoke runner (scripts/example_smoke.php) requires
pdfinfo (poppler-utils) and treats any warning, notice, or deprecation as a failure.
Examples that exercise a declared breaking change can be tracked as expected failures with
a documented reason (currently none: all 68 examples pass).
Third-Party Fonts
Third-party bundled font assets are provided through tecnickcom/tc-lib-pdf-font under vendor/tecnickcom/tc-lib-pdf-font/target/fonts/.
TCPDF no longer ships a repository-local fonts/ directory.
For full details, see the bundled notices shipped by tecnickcom/tc-lib-pdf-font.
Top Related Projects
HTML to PDF converter for PHP
PHP library generating PDF files from UTF-8 encoded HTML
A pure PHP library for reading and writing word processing documents
A DOMPDF Wrapper for Laravel
A slim PHP wrapper around wkhtmltopdf with an easy to use and clean OOP interface
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot