php-pdftk

repository·master·Indexed 21 days ago

https://github.com/mikehaertl/php-pdftk

A PHP utility providing a high-level API for the pdftk (PDF Toolkit) command-line tool. It enables advanced PDF manipulation including form filling via XFDF/FDF or PHP arrays, merging, splitting, layering (backgrounds and overlays), and security management. The library is designed for pdftk 2.x and includes helper classes like XfdfFile, FdfFile, DataFields, and InfoFields for handling PDF metadata and form data.

Tokens
8.3K
Snippets
34
Records
39
Agent score
76%

What's inside php-pdftk

  1. Overview of php-pdftk features

    master

    php-pdftk is a PHP wrapper that provides access to the full power of the pdftk command-line utility. Key capabilities include:

    • Form Handling: Fill PDF forms using XFDF/FDF files or PHP arrays (UTF-8 safe for unflattened forms with pdftk 2.x).
    • File Generation: Create XFDF/FDF files from PHP arrays or create FDF files from existing filled PDF forms.
    • Page Manipulation: Combine pages from multiple PDFs into one, or split a single PDF into individual pages.
    • Layering: Add background or overlay PDF files.
    • Metadata & Security: Read PDF/form field metadata, set/remove passwords, and manage permissions.
  2. How to perform multiple operations on a single PDF

    master

    A single Pdf instance can only perform one operation (e.g., you cannot cat() and then fillForm() on the same instance).

    Workaround: To chain operations, pass the first Pdf instance into the constructor of a second Pdf instance.

    // Step 1: Perform first operation
    $pdf = new Pdf('/path/my.pdf');
    $pdf->cat(1, 5)->cat([7, 4, 9]);
    
    // Step 2: Pass the first instance into a new instance for the next operation
    $pdf2 = new Pdf($pdf);
    $result = $pdf2->fillForm(['name' => 'John Doe'])
        ->saveAs('/path/filled.pdf');
  3. System Requirements for php-pdftk

    master

    Before using this library, ensure your environment meets the following requirements:

    • pdftk CLI: The pdftk command must be installed and accessible in your system's PATH.
    • pdftk Version: This library is designed for pdftk 2.x. While it may work with 1.x, not all methods are guaranteed to function.
    • Ubuntu/Snap Warning: If you are on Ubuntu and installed pdftk via snap, you may encounter permission issues writing to /tmp.
      • Workaround 1: Set a different temporary directory (see 'Temporary File' section in documentation).
      • Workaround 2: Use the pdftk-java package via apt (available for Ubuntu 18.10+ or manually for 18.04).
      • Workaround 3: Use an alternative installation method as suggested in community resources.
  4. Fill PDF forms

    master

    Fill a PDF form using either a PHP associative array or an existing XFDF/FDF file.

    Important for UTF-8: When using UTF-8 data, always chain ->needAppearances() to ensure the PDF reader uses the correct fonts. If using pdftk-java >= 3.3.0, you can also use ->replacementFont('/path/to/font.ttf') if the embedded font lacks UTF-8 support.

    Note: flatten() may not work well with special characters in your data.

    use mikehaertldftk// Note: The example in source uses mikehaertl\pdftk\Pdf
    use mikehaertl\[pdftk\Pdf;
    
    // Fill with array
    $pdf = new Pdf('/path/to/form.pdf');
    $result = $pdf->fillForm([
            'name'=>'ÄÜÖ äüö мирано čárka',
            'nested.name' => 'valX',
        ])
        ->needAppearances()
        ->saveAs('filled.pdf');
    
    // Fill from XFDF/FDF
    $pdf = new Pdf('form.pdf');
    $result = $pdf->fillForm('data.xfdf')->saveAs('filled.pdf');
    
    // Error handling
    if ($result === false) {
        $error = $pdf->getError();
    }
  5. Configure the PDF shell command

    master

    The library uses php-shellcommand to run pdftk. You can customize the command path and environment via the constructor's second argument.

    Solving UTF-8 filename issues: If filenames contain UTF-8 characters, set the correct locale and procEnv (e.g., LANG => 'en_US.utf-8') in the options array.

    $pdf = new Pdf('/path/my.pdf', [
        'command' => '/usr/bin/pdftk', // Custom path
        'useExec' => true,             // May help on Windows
        'locale'  => 'en_US.utf8',    // For UTF-8 filename support
        'procEnv' => ['LANG' => 'en_US.utf-8'],
    ]);
  6. Assemble PDFs with cat() and shuffle()

    master

    cat()

    Assemble a new PDF by selecting specific pages from one or more files. You can use handles (aliases) defined during file addition to reference files.

    shuffle()

    Similar to cat(), but creates "streams" where the resulting PDF contains one page from each stream in rotation (e.g., A1, B3, A2, B4...).

    use mikehaertl\pdftk\Pdf;
    
    // Cat: Combine pages from multiple files using handles
    $pdf = new Pdf([
        'A' => '/path/file1.pdf',
        'B' => ['/path/file2.pdf','pass**word'],
    ]);
    $result = $pdf->cat(1, 5, 'A')                // pages 1-5 from A
        ->cat(3, null, 'B')                     // page 3 from B
        ->cat(7, 'end', 'B', null, 'east')      // page 7-end from B, rotated East
        ->saveAs('/path/new.pdf');
    
    // Shuffle: Interleave pages from streams
    $pdf = new Pdf([
        'A' => '/path/file1.pdf',
        'B' => '/path/file2.pdf',
    ]);
    $result = $pdf->shuffle(1, 5, 'A')    // pages 1-5 from A
        ->shuffle(3, 8, 'B')              // pages 3-8 from B
        ->saveAs('/path/new.pdf');
  7. Access binary content via Temporary Files

    master

    The library uses php-tmpfile internally. If you need the raw binary content of a processed PDF without saving it to a permanent file, use execute() followed by getTmpFile().

    $pdf = new Pdf('/path/my.pdf');
    $result = $pdf->fillForm(['name' => 'My Name'])->execute();
    
    if ($result !== false) {
        $content = file_get_contents((string) $pdf->getTmpFile());
    }
    
    // You can also set a custom directory for temp files
    $pdf->tempDir = '/home/john/temp';
  8. Create XFDF or FDF files from PHP arrays

    master

    The library provides XfdfFile and FdfFile classes to generate data files from PHP arrays, a feature not natively available in the pdftk CLI.

    use mikehaertl\pdftk\XfdfFile;
    use mikehaertl\pdftk\FdfFile;
    
    $xfdf = new XfdfFile(['name' => 'Jürgen мирано']);
    $xfdf->saveAs('/path/to/data.xfdf');
    
    $fdf = new FdfFile(['name' => 'Jürgen мирано']);
    $fdf->saveAs('/path/to/data.fdf');
  9. Split, Overlay, and Background PDFs

    master

    Burst

    Split a PDF into individual files (one per page) using a printf() style pattern.

    Background and Overlay

    • background() / multiBackground(): Add a PDF as a background layer.
    • stamp() / multiStamp(): Add a PDF as an overlay (stamp) layer.

    Attach and Unpack Files

    • attachFiles($files, $page): Add file attachments to the document or a specific page.
    • unpackFiles($dir): Extract all file attachments from a PDF to a directory.
    // Burst
    $pdf->burst('/path/page_%d.pdf');
    
    // Background
    $pdf->background('/path/back.pdf')->saveAs('out.pdf');
    
    // Overlay
    $pdf->stamp('/path/overlay.pdf')->saveAs('out.pdf');
    
    // Attach
    $pdf->attachFiles(['/path/to/file1', '/path/to/file2'], 7);
    
    // Unpack
    $pdf->unpackFiles('/path/to/dir');
  10. Initialize a Pdf instance with files

    master

    You can initialize a Pdf instance with a single file, multiple files, or files with specific handles and passwords. Handles (aliases) are useful for referencing specific files in operations like cat() or shuffle(). In pdftk 2.x, handles are one or more uppercase letters.

    Ways to provide files:

    • Single file: Pass the path to the constructor.
    • Multiple files: Use addFile($path, $handle, $password).
    • Shortcut constructor: Pass an associative array where keys are handles and values are arrays containing the path and optional password.
    // Single file
    $pdf = new Pdf('/path/to/form.pdf');
    
    // Add files later with handles and passwords
    $pdf = new Pdf();
    $pdf->addFile('/path/to/file1.pdf', 'A');
    $pdf->addFile('/path/to/file2.pdf', 'B', 'secret*password');
    
    // Shortcut constructor
    $pdf = new Pdf([
      'A' => ['/path/to/file1.pdf', 'secret*password1'],
      'B' => ['/path/to/file2.pdf', 'secret*password2'],
    ]);
  11. Extract metadata and form data

    master

    Use getData() to retrieve metadata or form field information. The returned object can be treated as a string, an array, or accessed via __toArray().

    $pdf = new Pdf('/path/my.pdf');
    $data = $pdf->getData(); // or $pdf->getDataFields()
    
    // Accessing data
    $txt = (string) $data;
    $arr = (array) $data;
    $field1 = $data->__toArray()[0]['Field1'];