Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
TCPDF
https://github.com/tecnickcom/tcpdf
Admin
Official clone of PHP library to generate PDF documents and barcodes
Tokens:
205,713
Snippets:
1,676
Trust Score:
8.8
License:
LGPL-3.0
Update:
1 week ago
Context
Chat
Benchmark
64.55
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Two-column layout example Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/03-pages-cursor.md Shows how to create a two-column layout using setEqualColumns and selectColumn. After AddPage, setEqualColumns(2, 0, 20) defines two equal-width regions starting at Y=20. Writing to column 0 then column 1 places text in the left and right columns respectively. ```php // Two-column layout $pdf->AddPage(); $pdf->setEqualColumns(2, 0, 20); $pdf->selectColumn(0); $pdf->Write(5, 'Left column text...'); $pdf->selectColumn(1); $pdf->Write(5, 'Right column text...'); ``` -------------------------------- ### Creating form fields example Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/09-links-forms-js.md Example usage of TextField, ListBox, CheckBox, and Button methods. `ListBox` uses `[export, display]` pairs. `Button` action is an array with `'S' => 'JavaScript'` and `'JS'` script. `setXY` is used to position fields. ```php $pdf->TextField('name', 60, 8, ['value' => 'John'], ['Subtype' => 'Text', 'T' => 'Name']); $pdf->setXY($pdf->getX(), $pdf->getY() + 10); $pdf->ListBox('lang', 40, 12, ['en' => 'English', 'it' => 'Italiano']); // [export, display] pairs $pdf->setXY($pdf->getX(), $pdf->getY() + 15); $pdf->CheckBox('agree', 8, false, [], [], 'Yes'); $pdf->Button('submit', 30, 10, 'OK', ['S' => 'JavaScript', 'JS' => 'app.alert("ok")']); ``` -------------------------------- ### writeHTML usage example Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/06-html.md Example of using writeHTML to render an HTML fragment with an invoice heading, amount, and a table. The fragment is passed directly to the method. ```php $html = '<h1 style="color:#333;">Invoice</h1>' . '<p>Amount: <b>€ 120.00</b></p>' . '<table border="1"><tr><th>A</th><th>B</th></tr>' . '<tr><td>1</td><td>2</td></tr></table>'; $pdf->writeHTML($html); ``` -------------------------------- ### startLayer() Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/07-graphics.md Starts an optional content layer for subsequent drawing operations. Returns/emits the engine layer operators. ```APIDOC ## startLayer() ### Description Starts an optional content layer for subsequent drawing operations. Returns/emits the engine layer operators. ### Method startLayer ### Parameters - **$_name** (string) - Optional - Layer name. - **$_print** (bool) - Optional - Whether the layer is visible in print. - **$_view** (bool) - Optional - Whether the layer is visible on screen. - **$_lock** (bool) - Optional - Whether the layer is locked. ### Example ```php $pdf->startLayer('Confidential'); // optional content layer ``` ``` -------------------------------- ### startTemplate Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/10-security-output.md Opens a reusable XObject template with the given size (defaults to the page size), returns the template id, and routes subsequent content into it. Requires a page to be started (docstate must be 2). ```APIDOC ## startTemplate ### Description Opens a reusable XObject template with the given size (defaults to the page size), returns the template id, and routes subsequent content into it. Requires a page to be started (docstate must be 2). ### Method PHP method ### Endpoint `startTemplate($_w = 0, $_h = 0, $_group = false)` ### Parameters - **$_w** (number) - Optional - Width of the template (defaults to page width). - **$_h** (number) - Optional - Height of the template (defaults to page height). - **$_group** (boolean) - Optional - Whether to group the template. ### Return Value - **string|false** - Template id, or false on failure. ### Example ```php $tid = $pdf->startTemplate(100, 20); ``` ``` -------------------------------- ### Commit message examples with imperative mood Source: https://github.com/tecnickcom/tcpdf/blob/main/CONTRIBUTING.md Shows recommended commit message formats using prefixes like `fix`, `test`, `docs`, `refactor`, and `chore`. Reference issues where relevant, e.g., `fix: correct X (closes #42)`. ```text fix: correct cell border rendering for RTL text test: add regression test for #123 docs: update CONTRIBUTING workflow refactor: simplify font cache lookup chore: update dependency constraints ``` -------------------------------- ### Write() usage example Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/05-text-rendering.md Example call to Write() for flowing text. Arbitrary user text must be wrapped safely; writeHTML() is used for markup. ```php // Arbitrary user text must be wrapped safely; writeHTML() is used for markup. $pdf->Write(5, 'This paragraph flows automatically and wraps at the right margin.'); ``` -------------------------------- ### Configure K_ALLOWED_HOSTS, K_MAX_REMOTE_SIZE, K_CURLOPTS, and K_ALLOWED_PATHS Source: https://github.com/tecnickcom/tcpdf/blob/main/README.md Enable remote downloads from trusted CDNs, cap remote size at 10 MiB, add a custom cURL timeout, and allow reading shared local assets outside the install tree. Remote loading is off by default; TLS verification and redirect handling cannot be relaxed via K_CURLOPTS. ```php // 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/']); ``` -------------------------------- ### Color usage example Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/07-graphics.md Shows how to set fill, draw, and text colors using RGB values, plus the array form for fill color. ```php $pdf->setFillColor(200, 220, 255); // RGB $pdf->setDrawColor(0, 0, 0); $pdf->setTextColor(120, 20, 20); // or array form: $pdf->setFillColorArray([200, 220, 255]); ``` -------------------------------- ### IncludeJS example Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/09-links-forms-js.md Embeds a JavaScript snippet that triggers the print dialog when the document opens. ```php $pdf->IncludeJS('this.print({bUI:true,bSilent:false,bShrinkToFit:true});'); ``` -------------------------------- ### Template (XObject) API method signatures Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/10-security-output.md Declares the public methods for creating and using reusable XObject templates: startTemplate(), endTemplate(), and printTemplate(). startTemplate() requires docstate 2, otherwise it throws Error('Unable to start a template: no page has been started'). ```php public function startTemplate($_w = 0, $_h = 0, $_group = false) // string|false (template id) public function endTemplate() // string|false (template id) public function printTemplate( $_id, $_x = null, $_y = null, $_w = 0, $_h = 0, $_align = '', $_palign = '', $_fitonpage = false, ) ``` -------------------------------- ### Example usage of setSignature and setSignatureAppearance Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/10-security-output.md Example of setting a digital signature with certificate, private key, password, and info, then defining its appearance on the page. The signature appearance is placed at coordinates (70,120) with width 140 and height 40. ```php $pdf->setSignature('cert.pem', 'key.pem', 'secret', '', 2, [ 'Name' => 'ACME S.p.A.', 'Location' => 'Rome, IT', 'Reason' => 'Digital approval', ]); $pdf->setSignatureAppearance(70, 120, 140, 40); ``` -------------------------------- ### Image usage and mask example Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/08-images-barcodes.md Shows how to place an image with explicit position and size, and how to register a soft mask and apply it to another image. The mask is created with $_ismask=true and then passed as the $_imgmask argument. ```php $pdf->Image('logo.png', 10, 10, 40, 0, 'PNG', '', 'C'); // Mask usage: register a mask, then apply it $mask = $pdf->Image('mask.png', 0, 0, 0, 0, '', '', '', false, 300, '', true); $pdf->Image('photo.png', 20, 40, 60, 40, '', '', '', false, 300, '', false, $mask); ``` -------------------------------- ### Rotate and scale text example Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/07-graphics.md Example usage of StartTransform(), Rotate(), ScaleX(), and StopTransform() to draw rotated and scaled text. The pivot point (100, 100) is used for both rotation and scaling. The comment indicates 50% horizontal scale around (100, 100). ```php $pdf->StartTransform(); $pdf->Rotate(45, 100, 100); $pdf->ScaleX(50, 100, 100); // 50% horizontal scale around (100, 100) $pdf->Text(100, 100, 'rotated'); $pdf->StopTransform(); ``` -------------------------------- ### QR code, Code 39, and EAN-13 barcode examples Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/08-images-barcodes.md Three usage examples: a QR code at the cursor, a Code 39 with label, and an EAN-13 with auto padding. $_align 'N' moves to the next line after drawing. Barcodes that do not fit move to the next page/column automatically. ```php // QR code at the cursor $pdf->write2DBarcode('https://tcpdf.org', 'QRCODE,H', 10, 10, 40, 40, [], 'N'); ``` ```php // Code 39 with label $pdf->write1DBarcode('ABC-123', 'C39', 10, 60, 80, 18, 0.5, [ 'position' => 'L', 'fitwidth' => true, 'text' => true, 'font' => 'helvetica', 'fontsize' => 8, ], 'N'); ``` ```php // EAN-13 with padding $pdf->write1DBarcode('4006381333931', 'EAN13', 10, 90, 70, 16, null, ['padding' => 'auto']); ``` -------------------------------- ### setStartingPageNumber Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/03-pages-cursor.md Sets the starting page number for the document. ```APIDOC ## setStartingPageNumber ### Description Sets the starting page number for the document. ### Method setStartingPageNumber ### Signature public function setStartingPageNumber($_num = 1) ### Parameters - **$_num** (int) - Optional - Starting page number (default 1). ``` -------------------------------- ### startTransaction Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/10-security-output.md Starts a transaction by deep-snapshotting the entire facade and engine graph via serialize()/unserialize(). The closure page-context hook is detached across the snapshot and rebound. ```APIDOC ## startTransaction ### Description Starts a transaction by deep-snapshotting the entire facade and engine graph via serialize()/unserialize(). The closure page-context hook is detached across the snapshot and rebound. ### Method PHP method ### Endpoint `startTransaction()` ### Parameters None ### Return Value None ### Example ```php $pdf->startTransaction(); ``` ``` -------------------------------- ### Set custom font path and use SetFont Source: https://github.com/tecnickcom/tcpdf/blob/main/README.md Example PHP code showing how to use TCPDF with tc-lib font assets. Optionally define K_PATH_FONTS to use font assets from another directory. The $pdf object is assumed to be already instantiated. ```php 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); ``` -------------------------------- ### Create and print a reusable template Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/10-security-output.md Shows the typical workflow: start a template, draw content into it, end it, then print the template at a given position. The template id returned by startTemplate() is passed to printTemplate(). ```php $tid = $pdf->startTemplate(100, 20); $pdf->Cell(100, 20, 'Reusable stamp'); $pdf->endTemplate(); $pdf->printTemplate($tid, 10, 250); ``` -------------------------------- ### startPage Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/03-pages-cursor.md Starts a new page by delegating to the engine's addPage method, sets document state, freezes header/footer flags, and resets the cursor to the top margin. In column mode, re-selects the first column. ```APIDOC ## [POST] startPage ### Description Starts a new page by delegating to the engine's addPage method, sets document state, freezes header/footer flags, and resets the cursor to the top margin. In column mode, re-selects the first column. ### Method POST ### Endpoint startPage ### Parameters #### Path Parameters - `$_orientation` (string) - Optional - `'P'`/`'L'`; empty means "use current orientation" - `$_format` (string | array) - Optional - Format name or `[w,h]`; empty means current format - `$_tocpage` (bool) - Optional - Marks the page as a TOC page (resets `tocpage` at `endPage`) ### Request Example ```php $pdf->startPage(); ``` ### Response #### Success Response (200) No return value. #### Response Example No response body. ``` -------------------------------- ### startPageGroup Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/03-pages-cursor.md Starts a new page group, making the group take effect from the next added page (legacy behavior). ```APIDOC ## startPageGroup ### Description Starts a new page group, making the group take effect from the next added page (legacy behavior). ### Method startPageGroup ### Signature public function startPageGroup($_page = null) ### Parameters - **$_page** (mixed) - Optional - Page number or null for next page. ``` -------------------------------- ### AddPage Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/03-pages-cursor.md Ends the current page and starts a new one. Throws an Error if called on a closed document. ```APIDOC ## [POST] AddPage ### Description Ends the current page and starts a new one. Throws an Error if called on a closed document. ### Method POST ### Endpoint AddPage ### Parameters #### Path Parameters - `$_orientation` (string) - Optional - `'P'`/`'L'`; empty means "use current orientation" - `$_format` (string | array) - Optional - Format name or `[w,h]`; empty means current format - `$_keepmargins` (bool) - Optional - `true` snapshots current left/right margins as the original margins - `$_tocpage` (bool) - Optional - Marks the page as a TOC page (resets `tocpage` at `endPage`) ### Request Example ```php $pdf->AddPage(); ``` ### Response #### Success Response (200) No return value. #### Response Example No response body. ``` -------------------------------- ### Cell usage examples Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/05-text-rendering.md Two example calls to Cell. The first draws a filled, bordered cell with left alignment and vertical top alignment. The second draws a cell with top and bottom borders, centered horizontally, and advances the cursor to the next line. ```php $pdf->Cell(90, 10, 'Invoice #1234', 1, 1, 'L', true, '', 0, false, 'T', 'M'); $pdf->Cell(60, 8, 'Hello', 'TB', 0, 'C'); ``` -------------------------------- ### Drawing Shapes Example Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/07-graphics.md Example usage of setLineWidth, Rect, Ellipse, Polygon, and Arrow methods to draw various shapes on a PDF. Rect uses fill and stroke with a dashed border and light gray fill; Ellipse draws a stroked ellipse; Polygon fills a triangle with a light red color; Arrow draws an arrow from (60,140) to (120,140) with head style 0, arm size 5, and arm angle 15 degrees. ```php $pdf->setLineWidth(0.5); $pdf->Rect(20, 20, 80, 40, 'DF', ['all' => ['width' => 0.5, 'dash' => '2,2']], [240, 240, 240]); $pdf->Ellipse(150, 40, 30, 20, 0, 0, 360, 'D'); $pdf->Polygon([10, 100, 30, 130, 50, 100], 'F', [], [255, 200, 200]); $pdf->Arrow(60, 140, 120, 140, 0, 5, 15); ``` -------------------------------- ### Usage examples for getHTMLUnitToUnits and getCSSPadding Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/06-html.md Shows how to convert pixel and point values to user units using getHTMLUnitToUnits, and how to parse a CSS shorthand padding string with getCSSPadding. The getHTMLUnitToUnits method accepts a default unit and reference size; getCSSPadding returns an associative array with keys T, R, B, L. ```php $px = $pdf->getHTMLUnitToUnits('14px'); // pixels -> user units $pt = $pdf->getHTMLUnitToUnits('12pt', 1, 'pt'); // points $box = $pdf->getCSSPadding('2pt 4pt'); // ['T'=>…, 'R'=>…, 'B'=>…, 'L'=>…] ``` -------------------------------- ### Outlined, filled, clipped and shadowed text example Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/04-fonts-text-state.md Shows how to apply text rendering modes and shadows. The first block outlines text with a stroke width of 0.3 user units, then resets to normal fill. The second block enables a shadow with depth and opacity, draws a cell, then disables the shadow. ```php // Outlined, filled and clipped text $pdf->setTextRenderingMode(0.3, true, false); $pdf->Text(10, 30, 'Outlined text'); $pdf->setTextRenderingMode(0, true, false); ``` ```php // Shadowed text $pdf->setTextShadow(['enabled' => true, 'depth_w' => 0.5, 'depth_h' => 0.5, 'opacity' => 0.5]); $pdf->Cell(0, 8, 'Shadowed cell'); $pdf->setTextShadow(['enabled' => false]); ``` -------------------------------- ### TCPDF Link Usage Example Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/09-links-forms-js.md Shows how to create an internal link target with AddLink(), write text, and draw link rectangles with Link(). The external link uses a URL; $_spaces is a legacy parameter. ```php $lid = $pdf->AddLink(); // target at the current position $pdf->setY($pdf->getY() + 20); $pdf->Write(5, 'Target of the internal link'); $pdf->setY(10); $pdf->Link(10, 10, 40, 8, $lid); // blue box not drawn; a link with the id // external link: $pdf->Link(10, 30, 40, 8, 'https://tcpdf.org'); ``` -------------------------------- ### setAlpha, getAlpha, setOverprint, getOverprint, startLayer, endLayer, setVisibility signatures Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/07-graphics.md Public method signatures for transparency, overprint, optional-content layers, and visibility. setAlpha registers the ExtGState in the open XObject template when applicable; setVisibility closes any open layer and starts one matching 'print', 'view'/'screen', or 'all', raising Error('Incorrect visibility: <v>') for other values. ```php public function setAlpha($_stroking = 1, $_bm = 'Normal', $_nonstroking = null, $_ais = false) public function getAlpha() // array{CA: float, ca: float, BM: string, AIS: bool} public function setOverprint($_stroking = true, $_nonstroking = null, $_mode = 0) public function getOverprint() // array{OP: bool, op: bool, OPM: int} public function startLayer($_name = '', $_print = true, $_view = true, $_lock = true) public function endLayer() public function setVisibility($_v) ``` -------------------------------- ### setProtection() usage with AES-256 and print-only permissions Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/10-security-output.md Example call to setProtection() with AES-256 encryption and print-only permissions, followed by adding a page and writing encrypted content. Must be invoked before the first page is added. ```php // AES-256 with print-only permissions $pdf->setProtection(['print'], 'user123', 'owner456', 3); $pdf->AddPage(); $pdf->Write(5, 'Encrypted content'); ``` -------------------------------- ### Basic page flow with AddPage and Write Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/03-pages-cursor.md Shows the basic flow of creating a two-page PDF: instantiate TCPDF, set the title, add pages, write text, and output the document. AddPage ends the current page and starts a new one; calling it on a closed document raises Error('Unable to add pages on a closed document'). ```php // Basic flow $pdf = new TCPDF(); $pdf->setTitle('Two pages'); $pdf->AddPage(); $pdf->Write(5, 'First page'); $pdf->AddPage(); $pdf->Write(5, 'Second page'); $pdf->Output('two.pdf', 'D'); ``` -------------------------------- ### Legacy-Subclass Compatibility Example Using Magic Accessors Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/02-tcpdf-class.md Shows a user subclass `InvoicePdf` extending `TCPDF` that reads legacy properties via the magic accessors: `$this->w` maps to `getPageWidth()`, `$this->page` to `getPage()`, and `$this->lMargin` to `lmargin`. Use this pattern for backward compatibility with legacy protected properties. ```php // Legacy-subclass compatibility in user code: class InvoicePdf extends TCPDF { public function customMethod() { $width = $this->w; // -> getPageWidth() $page = $this->page; // -> getPage() $lm = $this->lMargin; // -> lmargin return [$width, $page, $lm]; } } ``` -------------------------------- ### Measuring text width and replacing missing characters Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/04-fonts-text-state.md Example of measuring a string width before rendering and checking if a character is defined, then replacing missing glyphs with a substitution map (codepoint 8364 for € replaced by codepoint 101). ```php // Measuring before rendering $w = $pdf->GetStringWidth('Hello world'); if (!$pdf->isCharDefined('€')) { $text = $pdf->replaceMissingChars('Total: € 10', '', '', [8364 => [101]]); } ``` -------------------------------- ### ImageSVG usage example Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/08-images-barcodes.md Example call to ImageSVG() that renders 'chart.svg' at position (15, 70) with width 100 and height 50. ```php $pdf->ImageSVG('chart.svg', 15, 70, 100, 50); ``` -------------------------------- ### Run quality assurance suite Source: https://github.com/tecnickcom/tcpdf/blob/main/CONTRIBUTING.md Runs linting, static analysis, and the unit-test suite to verify everything is working after a change. ```bash make qa ``` -------------------------------- ### getNumLines() and getStringHeight() usage example Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/05-text-rendering.md Example calls to estimate line count and required height before drawing, useful for reserving space. ```php $lines = $pdf->getNumLines($longText, 90); $height = $pdf->getStringHeight(90, $longText); // reserve space before drawing ``` -------------------------------- ### Run full test suite with coverage using make test Source: https://github.com/tecnickcom/tcpdf/blob/main/CONTRIBUTING.md Runs the complete PHPUnit test suite with code coverage. Coverage reports are generated under `target/`. ```bash # Run the full test suite with coverage make test ``` -------------------------------- ### Configure sandbox constants before loading TCPDF Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/configuration.md Define K_TCPDF_EXTERNAL_CONFIG, K_TCPDF_THROW_EXCEPTION_ERROR, K_ALLOWED_HOSTS, K_MAX_REMOTE_SIZE, K_CURLOPTS, and K_ALLOWED_PATHS before requiring autoload. K_ALLOWED_HOSTS empty disables remote loading; K_MAX_REMOTE_SIZE caps downloads at 50 MiB by default; K_CURLOPTS cannot override TLS verification or redirect handling. ```php // Full security example (define BEFORE loading tcpdf.php / requiring autoload) define('K_TCPDF_EXTERNAL_CONFIG', false); define('K_TCPDF_THROW_EXCEPTION_ERROR', true); define('K_ALLOWED_HOSTS', ['cdn.example.com', 'assets.example.org']); define('K_MAX_REMOTE_SIZE', 10 * 1024 * 1024); define('K_CURLOPTS', [CURLOPT_TIMEOUT => 15]); define('K_ALLOWED_PATHS', ['/var/www/shared/assets/', '/tmp/']); require __DIR__ . '/vendor/autoload.php'; $pdf = new TCPDF(); ``` -------------------------------- ### writeHTMLCell usage example Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/06-html.md Example of using writeHTMLCell to render an HTML fragment inside a card at a specific position. The function renderCard wraps the call with fixed dimensions and alignment. ```php function renderCard(TCPDF $pdf, float $x, float $y, string $html): void { $pdf->writeHTMLCell(90, 0, $x, $y, $html, 1, 1, false, true, 'L'); } renderCard($pdf, 10, 10, '<b>Card 1</b><br>Content'); ``` -------------------------------- ### MultiCell usage example Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/05-text-rendering.md Example call to MultiCell with width 120, height 8, text with three lines separated by \n, border 1, justify alignment, no fill, and line position 1 (next line). ```php $pdf->MultiCell(120, 8, "Line one\nLine two\nLine three", 1, 'J', false, 1); ``` -------------------------------- ### Open() method signature Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/02-tcpdf-class.md Public method that sets the legacy state flag docstate to max(1, docstate). No engine action is performed. ```php public function Open() ``` -------------------------------- ### Generate fonts once with make Source: https://github.com/tecnickcom/tcpdf/blob/main/README.md Run this command from the project root to generate tc-lib font assets once. This is an alternative to adding the Composer scripts. ```bash make -C vendor/tecnickcom/tc-lib-pdf-font deps fonts ``` -------------------------------- ### Open() Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/02-tcpdf-class.md Sets the legacy document state flag to at least 1. It performs no engine action and returns void. ```APIDOC ## Open() ### Description Sets the legacy document state flag to at least 1. It performs no engine action and returns void. ### Method public function Open() ### Parameters None ### Returns void ``` -------------------------------- ### Basic TCPDF instantiation Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/02-tcpdf-class.md Creates a TCPDF instance with default orientation, unit, format, and Unicode settings. Requires Composer autoload. ```php require __DIR__ . '/vendor/autoload.php'; $pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false); ``` -------------------------------- ### Clone and build TCPDF locally Source: https://github.com/tecnickcom/tcpdf/blob/main/CONTRIBUTING.md Clones the TCPDF repository and runs the build process. Requires PHP >= 8.2 with the curl extension, Composer v2, make, and git. ```bash git clone https://github.com/tecnickcom/TCPDF.git cd TCPDF make buildall ``` -------------------------------- ### PageNoFormatted Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/03-pages-cursor.md Returns the page number formatted with comma grouping and starting number offset. ```APIDOC ## PageNoFormatted ### Description Returns the page number formatted with comma grouping and starting number offset. ### Method PageNoFormatted ### Signature public function PageNoFormatted() ### Returns - **string** - Comma-grouped page number with starting number offset. ``` -------------------------------- ### getScaleFactor() Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/03-pages-cursor.md Returns the scale factor (points per user unit, kratio). ```APIDOC ## getScaleFactor() ### Description Returns the scale factor (points per user unit, kratio). ### Method PHP method ### Returns - **float** - Points per user unit. ``` -------------------------------- ### setVisibility() Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/07-graphics.md Sets the visibility of subsequent drawing operations. Closes any open layer and starts a new one matching the specified visibility mode. ```APIDOC ## setVisibility() ### Description Sets the visibility of subsequent drawing operations. Closes any open layer and starts a new one matching the specified visibility mode. ### Method setVisibility ### Parameters - **$_v** (string) - Required - Visibility mode: 'print' (print-only), 'view'/'screen' (screen-only), or 'all' (none). Any other value raises an Error. ### Errors - **Error** - Thrown if the visibility value is not one of 'print', 'view', 'screen', or 'all'. ``` -------------------------------- ### Get PDF data and save to file Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/10-security-output.md Shows how to retrieve the raw PDF string with getPDFData() and write it to a file using file_put_contents(). ```php // String output for further processing $data = $pdf->getPDFData(); file_put_contents('/tmp/out.pdf', $data); ``` -------------------------------- ### Write() method signature Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/05-text-rendering.md Flowing text method that prints text at the current position, wrapping to the right margin and next lines/pages automatically. Requires a started page; otherwise raises Error('Unable to write text: no page has been started'). Parameters: $_h line height, $_link link, $_fill row background, $_align '' (left) or 'J' (justify), $_ln true moves to next line, $_maxh caps block height, $_wadj/$_margin adjust available width. ```php public function Write( $_h, $_txt, $_link = '', $_fill = false, $_align = '', $_ln = false, $_stretch = 0, $_firstline = false, $_firstblock = false, $_maxh = 0, $_wadj = 0, $_margin = null, ) ``` -------------------------------- ### ImageSVG Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/08-images-barcodes.md Renders an SVG file through the engine SVG importer. Supports inline SVG data with '@' prefix and local-path sandbox for other paths. Raises an error if no page has been started. ```APIDOC ## ImageSVG ### Description Renders an SVG file through the engine SVG importer. `$_file` may be prefixed with `@` for inline SVG data; other paths go through the local-path sandbox. `$_x`/`$_y` default to the cursor; `$_w`/`$_h` size the drawing (0 = default); when `$_link` and positive size are given, a link rectangle is attached. Raises `Error('Unable to add an SVG image: no page has been started')` without a page. ### Method ImageSVG ### Signature ```php public function ImageSVG( $_file, $_x = null, $_y = null, $_w = 0, $_h = 0, $_link = '', $_align = '', $_palign = '', $_border = 0, $_fitonpage = false, ) ``` ### Parameters - **$_file** (string) - Required - Path to SVG file or inline SVG data prefixed with `@`. - **$_x** (mixed) - Optional - X position; defaults to cursor. - **$_y** (mixed) - Optional - Y position; defaults to cursor. - **$_w** (int) - Optional - Width of the drawing; 0 = default. - **$_h** (int) - Optional - Height of the drawing; 0 = default. - **$_link** (string) - Optional - Link URL; if provided with positive size, a link rectangle is attached. - **$_align** (string) - Optional - Alignment. - **$_palign** (string) - Optional - Page alignment. - **$_border** (int) - Optional - Border. - **$_fitonpage** (bool) - Optional - Fit on page. ### Example ```php $pdf->ImageSVG('chart.svg', 15, 70, 100, 50); ``` ### Errors - Raises `Error('Unable to add an SVG image: no page has been started')` if no page has been started. ``` -------------------------------- ### Basic TCPDF usage with Composer autoloader Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/01-overview.md Shows how to use the TCPDF facade with the Composer autoloader to create a simple PDF. Requires the Composer autoload file and instantiates TCPDF with page format 'P', unit 'mm', page size 'A4', and UTF-8 encoding. ```php require __DIR__ . '/vendor/autoload.php'; $pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false); $pdf->AddPage(); $pdf->SetFont('helvetica', '', 12); $pdf->Cell(40, 10, 'Hello World'); $pdf->Output('hello.pdf', 'I'); ``` -------------------------------- ### Write Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/05-text-rendering.md Flowing text: prints text at the current position and flows it to the right margin, wrapping to the next line (and pages) automatically. Requires a started page. ```APIDOC ## Write ### Description Flowing text: prints text at the current position and flows it to the right margin, wrapping to the next line (and pages) automatically. Requires a started page. ### Method Write ### Signature ```php public function Write( $_h, $_txt, $_link = '', $_fill = false, $_align = '', $_ln = false, $_stretch = 0, $_firstline = false, $_firstblock = false, $_maxh = 0, $_wadj = 0, $_margin = null, ) ``` ### Parameters - `$_h` (mixed) - Required - Line height. - `$_txt` (string) - Required - Text to print. - `$_link` (mixed) - Optional - Link to attach to the run. - `$_fill` (bool) - Optional - Fill the row background. - `$_align` (string) - Optional - Alignment: '' (left) or 'J' (justify). - `$_ln` (bool) - Optional - If true, moves to the next line after writing. - `$_stretch` (int) - Optional - Stretch factor. - `$_firstline` (bool) - Optional - Indicates first line. - `$_firstblock` (bool) - Optional - Indicates first block. - `$_maxh` (float) - Optional - Caps the block height. - `$_wadj` (float) - Optional - Adjusts the available width. - `$_margin` (mixed) - Optional - Adjusts the available width. ### Request Example ```php $pdf->Write(5, 'This paragraph flows automatically and wraps at the right margin.'); ``` ### Error Handling Raises `Error('Unable to write text: no page has been started')` if no page is started. ``` -------------------------------- ### Run a specific test file with XDEBUG_MODE=coverage Source: https://github.com/tecnickcom/tcpdf/blob/main/CONTRIBUTING.md Executes a single PHPUnit test file (e.g., `test/TcpdfCellTest.php`) with coverage enabled via `XDEBUG_MODE=coverage`. ```bash # Run a specific test file XDEBUG_MODE=coverage ./vendor/bin/phpunit test/TcpdfCellTest.php ``` -------------------------------- ### Create a branch for a bug fix Source: https://github.com/tecnickcom/tcpdf/blob/main/CONTRIBUTING.md Creates a new branch from main for a bug fix. Only project collaborators can open pull requests. ```bash git checkout -b fix/short-description-of-bug ``` -------------------------------- ### TCPDF::__construct Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/02-tcpdf-class.md Initializes a new TCPDF instance with the given orientation, unit, format, unicode mode, encoding, disk cache flag, and PDF/A conformance level. Applies legacy defaults and prepares the document for generation. ```APIDOC ## TCPDF::__construct ### Description Initializes a new TCPDF instance with the given orientation, unit, format, unicode mode, encoding, disk cache flag, and PDF/A conformance level. Applies legacy defaults and prepares the document for generation. ### Method Constructor ### Signature ```php public function __construct( $_orientation = 'P', $_unit = 'mm', $_format = 'A4', $_unicode = true, $_encoding = 'UTF-8', $_diskcache = false, $_pdfa = false, ) ``` ### Parameters - **$_orientation** (string) - Optional - Default: `'P'` - Page orientation: `'P'` (portrait) or `'L'` (landscape); any value starting with `L` (case-insensitive) means landscape. - **$_unit** (string) - Optional - Default: `'mm'` - Unit of measure: `'pt'`, `'mm'`, `'cm'`, `'in'`. Empty/whitespace falls back to `'mm'`. - **$_format** (string|array) - Optional - Default: `'A4'` - Page format: a format name string (e.g. `'A4'`, `'Letter'`) or `[width, height]` in user units. - **$_unicode** (bool) - Optional - Default: `true` - Unicode mode flag. - **$_encoding** (string) - Optional - Default: `'UTF-8'` - Document encoding. Only `'UTF-8'` is supported by the engine. - **$_diskcache** (bool) - Optional - Default: `false` - Deprecated and intentionally ignored. - **$_pdfa** (bool|int) - Optional - Default: `false` - PDF/A conformance level: `0`/`false` disables; `1` → `'pdfa1b'`, `2` → `'pdfa2b'`, `3` → `'pdfa3b'`. ### Return void ### Throws Exceptions from the engine constructor (e.g. font asset resolution failures). ### Example ```php require __DIR__ . '/vendor/autoload.php'; $pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false); ``` ### Example ```php $pdf = new TCPDF('L', 'pt', [612, 792], true, 'UTF-8', false, 1); ``` ``` -------------------------------- ### Add font generation scripts to composer.json Source: https://github.com/tecnickcom/tcpdf/blob/main/README.md Add these scripts to your project's composer.json to generate tc-lib font assets during Composer events. This covers composer install, update, require, and dump-autoload. The script checks for the tc-lib-pdf-font package and runs its Makefile targets. ```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" ] } } ``` -------------------------------- ### Polycurve(float $_x0, float $_y0, array $_segments, string $_style = '', array $_line_style = [], array $_fill_color = []) Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/07-graphics.md Draws a polycurve (series of connected curves) starting at (x0,y0). The segments are a list of point arrays. ```APIDOC ## Polycurve(float $_x0, float $_y0, array $_segments, string $_style = '', array $_line_style = [], array $_fill_color = []) ### Description Draws a polycurve (series of connected curves) starting at (x0,y0). The segments are a list of point arrays. ### Method Polycurve ### Parameters - **$_x0** (float) - Required - X coordinate of start point. - **$_y0** (float) - Required - Y coordinate of start point. - **$_segments** (array) - Required - List of point arrays; first point is (x0,y0). - **$_style** (string) - Optional - Style mode letters. - **$_line_style** (array) - Optional - Line style array. - **$_fill_color** (array) - Optional - Fill color override. ### Returns void ``` -------------------------------- ### Using setAlpha, startLayer, endLayer for transparency and optional content Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/07-graphics.md Sets 50% transparency, draws a filled rectangle, resets alpha, then wraps text in an optional-content layer named 'Confidential'. ```php $pdf->setAlpha(0.5); // 50% transparency $pdf->Rect(50, 50, 60, 40, 'F'); $pdf->setAlpha(1); $pdf->startLayer('Confidential'); // optional content layer $pdf->Text(10, 10, 'secret'); $pdf->endLayer(); ``` -------------------------------- ### TCPDF Output method signatures Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/10-security-output.md Declares the public methods for outputting the PDF: Output() with destination handling, getPDFData() to return the raw PDF string, and getPDFFilename() to get the sanitized filename used for file destinations. ```php public function Output($_name = 'doc.pdf', $_dest = 'I') public function getPDFData() public function getPDFFilename() ``` -------------------------------- ### Rollback transaction when content does not fit Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/10-security-output.md Illustrates a typical transaction pattern: start a transaction, write HTML, check if the Y position exceeds 260, and if so roll back to the previous state. Otherwise commit the transaction to discard the snapshot. ```php $pdf->startTransaction(); $y = $pdf->GetY(); if (!empty($fitText)) { $pdf->writeHTML($fitText); } if ($pdf->getY() > 260) { // does not fit $pdf->rollbackTransaction(true); // restore previous state } $pdf->commitTransaction(); ``` -------------------------------- ### TCPDF Link Methods Signatures Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/09-links-forms-js.md Declares the public methods AddLink(), setLink(), and Link() for creating and managing internal and external links. Requires a started page (docstate === 2); otherwise methods no-op. ```php public function AddLink() // int, internal link id public function setLink($_link, $_y = 0, $_page = -1) public function Link($_x, $_y, $_w, $_h, $_link, $_spaces = 0) ``` -------------------------------- ### IncludeJS() Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/09-links-forms-js.md Appends a raw JavaScript block to the document script, executed when the document opens. ```APIDOC ## IncludeJS() ### Description Appends a raw JavaScript block to the document script, executed when the document opens. ### Method IncludeJS ### Parameters - **$_script** (string) - Required - JavaScript code to append ### Return Value - **void** ``` -------------------------------- ### TCPDF Magic Accessors __get and __isset Signatures Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/02-tcpdf-class.md Declares the magic accessors for legacy property compatibility. `__get` returns the mapped state for supported legacy names (e.g., `w` maps to `getPageWidth()`, `page` to `getPage()`); unknown names return `null` and `__isset` returns `false`. ```php public function __get($name) public function __isset($name) ``` -------------------------------- ### TCPDF Annotation and Embedded File Usage Example Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/09-links-forms-js.md Adds a text annotation, embeds a file from a path, and embeds raw string content. The annotation uses Subtype 'Text' with a title; EmbedFile requires a readable file path. ```php $pdf->Annotation(20, 20, 20, 10, 'Note text', ['Subtype' => 'Text', 'T' => 'My note']); $pdf->EmbedFile(['file' => 'asset.pdf', 'mime' => 'application/pdf', 'desc' => 'Attachment']); $pdf->EmbedFileFromString('export.csv', "a,b,c\n1,2,3\n"); ``` -------------------------------- ### Opt into exceptions with K_TCPDF_THROW_EXCEPTION_ERROR Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/02-tcpdf-class.md Define K_TCPDF_THROW_EXCEPTION_ERROR as true to make Error() throw an exception instead of calling die(). The example shows a try/catch around a setProtection() call that is too late after AddPage(), producing the error 'TCPDF ERROR: setProtection() must be called before adding pages'. ```php // Opt into exceptions instead of die(): define('K_TCPDF_THROW_EXCEPTION_ERROR', true); require 'vendor/autoload.php'; try { $pdf = new TCPDF(); $pdf->AddPage(); $pdf->setProtection([], '', ''); // too late after AddPage() -> Error() } catch (\Exception $e) { // "TCPDF ERROR: setProtection() must be called before adding pages" error_log($e->getMessage()); } ``` -------------------------------- ### Custom HTML space and link style example Source: https://github.com/tecnickcom/tcpdf/blob/main/_autodocs/api-reference/06-html.md Shows how to set custom vertical space around headings with setHtmlVSpace and customize HTML link color/style with setHtmlLinksStyle before writing HTML content. The setHtmlVSpace array maps tags to indices with 'h' (height) and 'n' (number) values. ```php // Custom space around headings $pdf->setHtmlVSpace([ 'h1' => [0 => ['h' => 3, 'n' => 1], 1 => ['h' => 2, 'n' => 1]], ]); $pdf->setHtmlLinksStyle([0, 0, 200], 'U'); $pdf->writeHTML('<h1>Title</h1><p>See <a href="https://tcpdf.org">tcpdf.org</a></p>'); ```