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
| Method | Purpose |
|---|---|
includeJS() | Add document-level JavaScript (runs when the PDF opens) |
addJavascriptObject() | Add JavaScript as a named PDF object |
Basic Example
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()
$pdf->includeJS(string $script): staticAdds document-level JavaScript that is executed when the PDF is opened. Use this for function definitions, global variables, and initialization logic.
| Parameter | Type | Description |
|---|---|---|
$script | string | Raw JavaScript code |
Multiple calls append additional scripts. They execute in the order they are added.
addJavascriptObject()
$pdf->addJavascriptObject(string $script): staticAdds 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.
| Action | Trigger |
|---|---|
onFocus | Field receives focus |
onBlur | Field loses focus |
onChange | Field value changes |
validate | Before the value is committed |
calculate | When dependent fields change |
format | After the value is committed (format display) |
keystroke | On each keystroke |
$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; }',
]);Print Trigger and Open Actions
Run logic when the document is opened or printed:
$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.