Skip to content

JavaScript

PDF documents can contain embedded JavaScript that executes in the viewer. TCPDF-Next provides methods for adding document-level scripts through Content\JavaScriptManager, accessed via the Document fluent API.

All methods return static, so every call can be chained.

Quick Reference

MethodPurpose
includeJS()Add document-level JavaScript (runs when the PDF opens)
addJavascriptObject()Add JavaScript as a named PDF object

Basic Example

php
use Yeeefang\TcpdfNext\Core\Document;

$pdf = Document::create()
    ->addPage()
    ->setFont('Helvetica', '', 12)
    ->cell(0, 10, 'Interactive Form with JavaScript', newLine: true)

    // Document-level JavaScript
    ->includeJS('
        function validateEmail(field) {
            var email = field.value;
            var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!re.test(email)) {
                app.alert("Please enter a valid email address.");
                return false;
            }
            return true;
        }

        function calculateTotal() {
            var qty = this.getField("qty").value;
            var price = this.getField("price").value;
            this.getField("total").value = (qty * price).toFixed(2);
        }
    ')

    // Form fields that use the JavaScript
    ->textField('email', 45, null, 80, 8, [
        'onBlur' => 'validateEmail(event.target)',
    ])
    ->textField('qty', 45, null, 30, 8)
    ->textField('price', 80, null, 30, 8)
    ->textField('total', 115, null, 40, 8, [
        'readonly' => true,
    ]);

WARNING

JavaScript support varies by PDF viewer. Adobe Acrobat has full support for the Acrobat JavaScript API. Foxit Reader supports most features. Browser-based viewers and preview apps generally do not execute PDF JavaScript.

includeJS()

php
$pdf->includeJS(string $script): static

Adds document-level JavaScript that is executed when the PDF is opened. Use this for function definitions, global variables, and initialization logic.

ParameterTypeDescription
$scriptstringRaw JavaScript code

Multiple calls append additional scripts. They execute in the order they are added.

addJavascriptObject()

php
$pdf->addJavascriptObject(string $script): static

Adds JavaScript as a named PDF object. Useful when scripts need to be referenced by other PDF objects (actions, annotations) rather than running at document open.

JavaScript Actions on Form Fields

Form fields support JavaScript action triggers through their options array. These actions fire in response to user interaction with the field.

ActionTrigger
onFocusField receives focus
onBlurField loses focus
onChangeField value changes
validateBefore the value is committed
calculateWhen dependent fields change
formatAfter the value is committed (format display)
keystrokeOn each keystroke
php
$pdf->textField('price', 45, null, 40, 8, [
    'format'    => 'AFNumber_Format(2, 0, 0, 0, "$", true);',
    'keystroke' => 'AFNumber_Keystroke(2, 0, 0, 0, "$", true);',
    'validate'  => 'if (event.value < 0) { app.alert("Price cannot be negative."); event.rc = false; }',
]);

Run logic when the document is opened or printed:

php
$pdf->includeJS('
    app.alert("Welcome! Please fill in all required fields.");
')
->includeJS('
    var pp = this.addScript("willPrint", "app.alert(\'This document is confidential.\');");
');

Tips

  • Keep scripts concise. Large blocks increase file size and slow document opening.
  • The Acrobat JavaScript API is documented in Adobe's JavaScript for Acrobat API Reference.
  • Test interactive PDFs in Adobe Acrobat to ensure full compatibility before distributing.
  • PDF/A standards prohibit JavaScript. Do not include scripts if you target PDF/A compliance.
  • For calculations, use built-in Acrobat functions (AFNumber_Format, AFSimple_Calculate, etc.) where possible.

Released under the LGPL-3.0-or-later License.