Skip to content

JavaScript

Document PDF có thể chứa JavaScript nhúng thực thi trong trình xem. TCPDF-Next cung cấp method để thêm script cấp document qua Content\JavaScriptManager, truy cập qua fluent API của Document.

Mọi method trả về static, nên mỗi lệnh gọi có thể chain.

Tham chiếu nhanh

MethodMục đích
includeJS()Thêm JavaScript cấp document (chạy khi PDF mở)
addJavascriptObject()Thêm JavaScript dạng named PDF object

Ví dụ cơ bản

php
use Yeeefang\TcpdfNext\Core\Document;

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

    // JavaScript cấp document
    ->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);
        }
    ')

    // Trường form dùng 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

Hỗ trợ JavaScript khác nhau tùy trình xem PDF. Adobe Acrobat hỗ trợ đầy đủ Acrobat JavaScript API. Foxit Reader hỗ trợ hầu hết tính năng. Trình xem dựa trên trình duyệt và ứng dụng preview thường không thực thi PDF JavaScript.

includeJS()

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

Thêm JavaScript cấp document, được thực thi khi PDF mở. Dùng cho khai báo hàm, biến toàn cục và logic khởi tạo.

Tham sốKiểuMô tả
$scriptstringMã JavaScript thô

Nhiều lần gọi sẽ nối thêm script. Chúng thực thi theo thứ tự thêm vào.

addJavascriptObject()

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

Thêm JavaScript dạng named PDF object. Hữu ích khi script cần được tham chiếu bởi object PDF khác (action, annotation) thay vì chạy khi document mở.

JavaScript Action trên trường Form

Trường form hỗ trợ JavaScript action trigger qua mảng tùy chọn. Các action này kích hoạt khi người dùng tương tác với trường.

ActionTrigger
onFocusTrường nhận focus
onBlurTrường mất focus
onChangeGiá trị trường thay đổi
validateTrước khi giá trị được commit
calculateKhi trường phụ thuộc thay đổi
formatSau khi giá trị được commit (định dạng hiển thị)
keystrokeTrên mỗi phím bấm
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; }',
]);

Chạy logic khi document mở hoặc in:

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

Mẹo

  • Giữ script ngắn gọn. Block lớn tăng kích thước file và làm chậm mở document.
  • Acrobat JavaScript API được mô tả trong JavaScript for Acrobat API Reference của Adobe.
  • Test PDF tương tác trong Adobe Acrobat để đảm bảo tương thích đầy đủ trước khi phân phối.
  • Chuẩn PDF/A cấm JavaScript. Không thêm script nếu bạn nhắm đến tuân thủ PDF/A.
  • Cho phép tính, dùng hàm Acrobat tích hợp (AFNumber_Format, AFSimple_Calculate, v.v.) khi có thể.

Phân phối theo giấy phép LGPL-3.0-or-later.