### Example PDFTK Constructor Configuration Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/types.md An example demonstrating how to set the command path, execution method, locale, and environment variables when initializing the PDFTK class. ```php [ 'command' => '/usr/bin/pdftk', 'useExec' => false, 'locale' => 'en_US.utf8', 'procEnv' => [ 'LANG' => 'en_US.utf-8', ], ] ``` -------------------------------- ### Check pdftk Installation via Command Line Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/configuration.md Verify pdftk installation and functionality directly from the command line. ```bash pdftk --version ``` -------------------------------- ### Command Constructor Example Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Command.md Shows how to create a new Command instance. The pdftk binary path can be configured using the 'command' option. ```php $cmd = new Command(); $cmd->setOptions(['command' => '/usr/bin/pdftk']); ``` -------------------------------- ### Install PHP-PDFTK using Composer Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/README.md Use Composer to install the PHP-PDFTK library. This command adds the library as a dependency to your project. ```bash composer require mikehaertl/php-pdftk ``` -------------------------------- ### Configure PDFtk for Windows Non-Standard Installation Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/configuration.md Specify the custom 'command' path and set 'useExec' to true when PDFtk is not installed in the default location on a Windows system. ```php $pdf = new Pdf('C:\\Users\\John\\form.pdf', [ 'command' => 'C:\\Program Files (x86)\\PDFtk\\bin\\pdftk.exe', 'useExec' => true, ]); $pdf->fillForm(['field' => 'value'])->saveAs('C:\\output.pdf'); ``` -------------------------------- ### Configure custom pdftk path and environment Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Pdf.md Example showing how to specify a custom pdftk command path, use 'exec' on Windows, and set locale and process environment variables. ```php $pdf = new Pdf('/path/form.pdf', [ 'command' => '/usr/local/bin/pdftk', 'useExec' => true, // May help on Windows 'locale' => 'en_US.utf8', 'procEnv' => [ 'LANG' => 'en_US.utf8', ], ]); ``` -------------------------------- ### Build pdftk Command Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Command.md Demonstrates building a complex pdftk command by adding files, operations, page ranges, and options. This example shows the fluent interface for constructing invocations. ```php $cmd = new Command(); // File definitions $cmd->addFile('/path/file1.pdf', 'A') ->addFile('/path/file2.pdf', 'B'); // Operation and arguments $cmd->setOperation('cat') ->addPageRange(1, 5, 'A') ->addPageRange(1, 10, 'B'); // Options $cmd->addOption('compress') ->addOption('owner_pw', 'secret', true); // Execute with output $cmd->execute('/path/output.pdf'); ``` -------------------------------- ### Linux (RHEL/CentOS/Fedora) pdftk Paths Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/configuration.md Standard and EPEL repository installation paths for pdftk on RHEL-based systems. ```bash # Standard /usr/bin/pdftk # From EPEL repo /usr/bin/pdftk ``` -------------------------------- ### Windows pdftk Path Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/configuration.md Default installation path for pdftk on Windows systems. ```text C:\Program Files (x86)\PDFtk\bin\pdftk.exe ``` -------------------------------- ### macOS pdftk Paths Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/configuration.md Installation paths for pdftk on macOS via Homebrew and MacPorts. ```bash # From Homebrew /usr/local/bin/pdftk # From MacPorts /opt/local/bin/pdftk ``` -------------------------------- ### Configure PDFtk Command Path Source: https://github.com/mikehaertl/php-pdftk/blob/master/README.md Instantiate the Pdf class with custom options to specify the pdftk command path or use `exec`. This is useful for non-standard installations or Windows systems. ```php use mikehaertl\pdftk\Pdf; $pdf = new Pdf('/path/my.pdf', [ 'command' => '/some/other/path/to/pdftk', // or on most Windows systems: // 'command' => 'C:\\Program Files (x86)\\PDFtk\\bin\\pdftk.exe', 'useExec' => true, // May help on Windows systems if execution fails ]); ``` -------------------------------- ### Handling 'Command Not Found' Error in PHP-PDFTK Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/errors.md Ensure the pdftk binary is installed and accessible. Specify the correct command path during Pdf class initialization if it's not in the system's PATH. ```php $pdf = new Pdf('/path/form.pdf', [ 'command' => '/nonexistent/path/pdftk', ]); if (!$pdf->fillForm(['field' => 'value'])->saveAs('/path/output.pdf')) { echo $pdf->getError(); // Command not found } ``` ```php // Find pdftk location // On Unix: which pdftk // On Windows: where pdftk $pdf = new Pdf('/path/form.pdf', [ 'command' => '/usr/bin/pdftk', // Or correct path ]); ``` -------------------------------- ### Get the underlying Command instance Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Pdf.md Returns the Command instance that manages the pdftk process. ```php public function getCommand(): Command ``` -------------------------------- ### Linux (Debian/Ubuntu) pdftk Paths Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/configuration.md Standard and alternative installation paths for pdftk on Debian/Ubuntu systems. ```bash # Standard installation /usr/bin/pdftk # From custom PPA /usr/bin/pdftk # From snap (not recommended due to /tmp permission issues) /snap/bin/pdftk # pdftk-java alternative /usr/bin/pdftk ``` -------------------------------- ### Getting File Count Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Command.md Demonstrates how to retrieve the number of PDF files that have been added to the command instance using the getFileCount method. ```php $cmd = new Command(); $cmd->addFile('/path/file1.pdf', 'A'); $cmd->addFile('/path/file2.pdf', 'B'); echo $cmd->getFileCount(); // 2 ``` -------------------------------- ### PHP FDF Encoding Example Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/FdfFile.md Illustrates the internal FDF generation process in PHP, showing how to convert a string to UTF-16BE encoding and prepend the BOM. This is handled automatically by the FdfFile constructor. ```php // Internal FDF generation (simplified) $utf16Value = mb_convert_encoding($value, 'UTF-16BE', 'UTF-8'); $fdfValue = chr(0xFE) . chr(0xFF) . $utf16Value; // Add BOM ``` -------------------------------- ### Bookmark Block Example Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/InfoFile.md This snippet demonstrates the structure for the optional 'Bookmark' block, used to define document bookmarks with their titles, levels, and corresponding page numbers. ```php $data = [ 'Bookmark' => [ [ 'Title' => 'Chapter 1', 'Level' => '1', 'PageNumber' => '1', ], [ 'Title' => 'Chapter 2', 'Level' => '1', 'PageNumber' => '5', ], ], ]; ``` -------------------------------- ### Execute pdftk Operations Directly with Command Class Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Command.md Use the Command class for lower-level control over pdftk operations. This example adds a file and sets an operation to dump data, retrieving the output upon successful execution. ```php use mikehaertl\pdftk\Command; $cmd = new Command(); $cmd->addFile('/path/file.pdf', 'A') ->setOperation('dump_data'); if ($cmd->execute()) { $metadata = $cmd->getOutput(); } ``` -------------------------------- ### Get the temporary output file instance Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Pdf.md Returns the temporary output file instance for direct access without saving or sending. ```php public function getTmpFile(): File ``` -------------------------------- ### PageMedia Block Example Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/InfoFile.md This snippet illustrates the structure for the optional 'PageMedia' block, which can specify media box dimensions for pages. ```php $data = [ 'PageMedia' => [ [ 'MediaBox' => '0 0 612 792', ], ], ]; ``` -------------------------------- ### Execute pdftk Command and Get Output Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Command.md Use this method to build and execute a pdftk command. It processes input files, operations, and options before execution. Check the return value for success or failure, and use getOutput() or getError() to retrieve results. ```php $cmd = new Command(); $cmd->addFile('/path/file.pdf', 'A') ->setOperation('dump_data'); if ($cmd->execute()) { echo $cmd->getOutput(); // PDF metadata } else { echo "Error: " . $cmd->getError(); } ``` -------------------------------- ### Generated Info File Structure Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/InfoFile.md Example of the text file format generated by InfoFile, compatible with pdftk's update_info command for setting document metadata and bookmarks. ```text InfoBegin InfoKey: Title InfoValue: My Document InfoBegin InfoKey: Author InfoValue: John Doe InfoBegin InfoKey: Subject InfoValue: A test document BookmarkBegin BookmarkTitle: Chapter 1 BookmarkLevel: 1 BookmarkPageNumber: 1 BookmarkBegin BookmarkTitle: Chapter 2 BookmarkLevel: 1 BookmarkPageNumber: 5 ``` -------------------------------- ### Check pdftk Availability with PHP Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/configuration.md Test if pdftk is installed and accessible by the PHP script. This snippet attempts to execute the '--version' argument and reports success or failure. ```php // Test pdftk availability $cmd = new \mikehaertl\pdftk\Command(); $cmd->setOptions(['command' => 'pdftk']); $cmd->addArg('--version'); if ($cmd->execute()) { echo "pdftk version: " . $cmd->getOutput(); } else { echo "pdftk not found or error: " . $cmd->getError(); } ``` -------------------------------- ### Parameter Type Union: Metadata Input Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/types.md Example of a parameter that accepts various types including string, array, InfoFields object, or InfoFile instance for metadata input. ```php // Metadata input string|array|InfoFields|InfoFile $data - string: filename path - array: associative array - InfoFields: parsed metadata object - InfoFile: InfoFile instance ``` -------------------------------- ### Specify pdftk Command Path Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/configuration.md Set the full path to the pdftk binary if it's not in the system's PATH or if multiple versions are installed. This is particularly useful on Windows or within containerized environments. ```php [ 'command' => '/usr/local/bin/pdftk', ] ``` ```php [ 'command' => 'C:\\Program Files (x86)\\PDFtk\\bin\\pdftk.exe', ] ``` ```php [ 'command' => '/usr/bin/pdftk-java', ] ``` -------------------------------- ### Legacy InfoFile Format Example Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/InfoFile.md This snippet shows the legacy format for InfoFile, where document fields are provided directly at the root level. This format is supported for backward compatibility and is internally converted to the new format. ```php // Legacy format (supported for backwards compatibility) $data = [ 'Title' => 'My Document', 'Author' => 'John Doe', 'Subject' => 'Test', // ... other Info fields ]; // Automatically converted to new format internally ``` -------------------------------- ### Set All Standard PDF Metadata Fields Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/InfoFile.md This example demonstrates how to set all common standard metadata fields for a PDF, including Title, Author, Subject, Keywords, Creator, Producer, CreationDate, ModDate, and Trapped. Ensure the date format is correct. ```php $pdf = new Pdf('/path/document.pdf'); $result = $pdf->updateInfo([ 'Info' => [ 'Title' => 'My Document', 'Author' => 'John Doe', 'Subject' => 'A PDF document example', 'Keywords' => 'pdf, example, document', 'Creator' => 'My Application', 'Producer' => 'pdftk', 'CreationDate' => 'D:' . date('YmdHis'), 'ModDate' => 'D:' . date('YmdHis'), 'Trapped' => 'False', ], ]) ->saveAs('/path/updated.pdf'); ``` -------------------------------- ### Mapping Database Records to PDF Form Fields Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/FdfFile.md An example of how to fetch data from a database (using PDO) and map it to the fields of a PDF form for filling. It highlights that FDF requires simple field names. ```php // Assume PDO connection $stmt = $pdo->prepare('SELECT * FROM applicants WHERE id = ?'); $stmt->execute([$applicantId]); $row = $stmt->fetch(PDO::FETCH_ASSOC); // Map database columns to form fields // Note: FDF doesn't support hierarchical names, use simple names $formData = [ 'FirstName' => $row['first_name'], 'LastName' => $row['last_name'], 'Email' => $row['email'], 'Phone' => $row['phone'], 'StreetAddress' => $row['address_street'], 'City' => $row['address_city'], 'State' => $row['address_state'], 'ZipCode' => $row['address_zip'], ]; $pdf = new Pdf('/path/template.pdf'); $pdf->fillForm($formData, 'UTF-8', true, 'fdf') ->needAppearances() ->saveAs('/path/applicant_' . $applicantId . '.pdf'); ``` -------------------------------- ### Working with Different Metadata Encodings Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/InfoFile.md This example illustrates how to handle PDF metadata with specific encodings, such as Latin-1 (ISO-8859-1). Use the `InfoFile` class to explicitly set the encoding when creating metadata arrays. ```php use mikehaertl\pdftk\InfoFile; // If data is in Latin-1 encoding $data = [ 'Info' => [ 'Title' => 'São Paulo Document', 'Author' => 'José García', ], ]; // Create with explicit encoding $infoFile = new InfoFile($data, null, null, null, 'ISO-8859-1'); $pdf = new Pdf('/path/document.pdf'); $pdf->updateInfo($infoFile) ->saveAs('/path/updated.pdf'); ``` -------------------------------- ### Document Information (Info Block) Example Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/InfoFile.md This snippet shows the structure for the 'Info' block, which contains standard document metadata like Title, Author, Subject, and dates. Ensure date formats are correct. ```php $data = [ 'Info' => [ 'Title' => 'Document Title', 'Author' => 'Author Name', 'Subject' => 'Document Subject', 'Keywords' => 'keyword1, keyword2, keyword3', 'Creator' => 'Creating Application', 'Producer' => 'PDF Producer', 'CreationDate' => 'D:20231201120000Z', 'ModDate' => 'D:20231215100000Z', 'Trapped' => 'False', ], ]; ``` -------------------------------- ### Execute PDF Operations and Get Binary Content Source: https://github.com/mikehaertl/php-pdftk/blob/master/README.md Perform PDF operations, such as filling a form, and then retrieve the resulting PDF content as a binary string from a temporary file. Useful when you don't need to save the file directly. ```php use mikehaertl\pdftk\Pdf; $pdf = new Pdf('/path/my.pdf'); $result = $pdf->fillForm(['name' => 'My Name']) ->execute(); if ($result === false) { $error = $pdf->getError(); } $content = file_get_contents( (string) $pdf->getTmpFile() ); ``` -------------------------------- ### Get FDF File Name Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/FdfFile.md Demonstrates how to get the temporary file path of an FDF file object. This method is inherited from the parent File class. ```php $fdf = new FdfFile(['Name' => 'John']); echo $fdf->getFileName(); // /tmp/php_pdftk_fdf_abc123def.fdf ``` -------------------------------- ### Initialize Pdf Instance Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Pdf.md Create a new Pdf instance. Can be initialized with a single PDF file, a password-protected file with options, multiple files using handles, or as an empty instance to add files later. ```php use mikehaertl\pdftk\Pdf; // Simple initialization with a file $pdf = new Pdf('/path/to/file.pdf'); ``` ```php // With password-protected file $pdf = new Pdf('/path/to/protected.pdf', [ 'command' => '/usr/bin/pdftk', ]); ``` ```php // Multiple files with handles $pdf = new Pdf([ 'A' => '/path/to/file1.pdf', 'B' => ['/path/to/file2.pdf', 'password123'], 'C' => '/path/to/file3.pdf', ]); ``` ```php // Empty instance, add files later $pdf = new Pdf(); $pdf->addFile('/path/to/file.pdf'); ``` -------------------------------- ### Command Constructor Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Command.md Initializes a new Command instance. The pdftk binary path can be configured. ```APIDOC ## Constructor ```php public function __construct(): Command ``` Creates a new Command instance. The pdftk binary is set to `'pdftk'` by default. **Example:** ```php $cmd = new Command(); $cmd->setOptions(['command' => '/usr/bin/pdftk']); ``` ``` -------------------------------- ### Create PDF Instance for Files Source: https://github.com/mikehaertl/php-pdftk/blob/master/README.md Instantiate the Pdf class with PDF files. Files can be added to the constructor or later using addFile(). Handles can be assigned for specific operations. Passwords can also be included. ```php // Create an instance for a single file $pdf = new Pdf('/path/to/form.pdf'); ``` ```php // Alternatively add files later. Handles are autogenerated in this case. $pdf = new Pdf(); $pdf->addFile('/path/to/file1.pdf'); $pdf->addFile('/path/to/file2.pdf'); ``` ```php // Add files with own handle $pdf = new Pdf(); $pdf->addFile('/path/to/file1.pdf', 'A'); $pdf->addFile('/path/to/file2.pdf', 'B'); ``` ```php // Add file with handle and password $pdf->addFile('/path/to/file3.pdf', 'C', 'secret*password'); ``` ```php // Shortcut to pass all files to the constructor $pdf = new Pdf([ 'A' => ['/path/to/file1.pdf', 'secret*password1'], 'B' => ['/path/to/file2.pdf', 'secret*password2'], ]); ``` -------------------------------- ### Initialize Pdf Constructor with Options Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/configuration.md Configure the Pdf object by passing an options array to the constructor. This sets the pdftk command path, execution method, locale, and process environment variables. ```php use mikehaertl\pdftk\Pdf; $pdf = new Pdf('/path/form.pdf', [ 'command' => '/usr/bin/pdftk', 'useExec' => true, 'locale' => 'en_US.utf8', 'procEnv' => [ 'LANG' => 'en_US.utf-8', ], ]); ``` -------------------------------- ### Adding PDF Files with Handles Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Command.md Illustrates how to add PDF files to the command using the addFile method. Each file is assigned a handle (e.g., 'A', 'B') for referencing in operations. Optionally, a password can be provided for encrypted files. ```php $cmd = new Command(); $cmd->addFile('/path/file1.pdf', 'A') ->addFile('/path/file2.pdf', 'B', 'password123'); ``` -------------------------------- ### Get the last error message Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Pdf.md Returns the last error message encountered during pdftk execution. ```php public function getError(): string ``` -------------------------------- ### PHP Configuration for Windows Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/configuration.md Configure the pdftk command path and execution method in PHP for Windows systems. ```php [ 'command' => 'C:\\Program Files (x86)\\PDFtk\\bin\\pdftk.exe', 'useExec' => true, ] ``` -------------------------------- ### Get Info File Path Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/InfoFile.md Returns the absolute path to the temporary info file. This method is inherited from the File class. ```php public function getFileName(): string ``` ```php $infoFile = new InfoFile(['Info' => ['Title' => 'My Document']]); echo $infoFile->getFileName(); // /tmp/php_pdftk_info_abc123def.txt ``` -------------------------------- ### execute() Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Command.md Builds the pdftk command and executes it. Processes input files, operation, and options first. Returns true on success, false on failure. ```APIDOC ## execute() ### Description Builds the pdftk command and executes it. Processes input files, operation, and options first. ### Method `public function execute(string|null $filename = null): bool` ### Parameters #### Path Parameters - **$filename** (string|null) - Optional - Output filename. If null, no output option is added. ### Return - **bool** - `true` on success, `false` on failure ### Example ```php $cmd = new Command(); $cmd->addFile('/path/file.pdf', 'A') ->setOperation('dump_data'); if ($cmd->execute()) { echo $cmd->getOutput(); // PDF metadata } else { echo "Error: " . $cmd->getError(); } ``` ``` -------------------------------- ### Handle PDF fill form errors Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Pdf.md Example demonstrating how to check the result of fillForm and retrieve error messages using getError(). ```php $pdf = new Pdf('/path/form.pdf'); $result = $pdf->fillForm(['field' => 'value'])->saveAs('/path/output.pdf'); if (!$result) { echo "Error: " . $pdf->getError(); } ``` -------------------------------- ### Configure Legacy System with UTF-8 Issues Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/configuration.md Use 'C.UTF-8' locale settings for 'locale', 'LANG', and 'LC_ALL' to ensure compatibility with legacy systems that may have UTF-8 encoding problems. ```php $pdf = new Pdf('/path/form.pdf', [ 'locale' => 'C.UTF-8', // Universal UTF-8 locale 'procEnv' => [ 'LANG' => 'C.UTF-8', 'LC_ALL' => 'C.UTF-8', // Override all locale categories ], ]); ``` -------------------------------- ### Simple FDF Data Structure Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/FdfFile.md An example of a simple associative array representing data for an FDF file. Field names are simple strings. ```php $data = [ 'FirstName' => 'John', 'Email' => 'john@example.com', 'Age' => '30', ]; ``` -------------------------------- ### Accessing PDF Form Fields as an Array Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/DataFields.md Demonstrates how to get all form fields from a PDF and access them like an array. Useful for iterating through fields or accessing them by index. ```php getDataFields(); // Iterate over all fields foreach ($fields as $field) { if (isset($field['FieldName'])) { echo $field['FieldName']; } } // Access specific field by index $firstField = $fields[0]; echo $firstField['FieldName']; echo $firstField['FieldType']; echo $firstField['FieldValue']; // Get array representation for easier manipulation $fieldsArray = (array) $fields; $fieldCount = count($fieldsArray); ?> ``` -------------------------------- ### Configure PDF Library with Locale and Environment Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/errors.md Set the 'locale' and 'procEnv' options during PDF object instantiation for proper language and encoding handling. Customize the temporary directory for PDF operations. ```php $pdf = new Pdf('/path/form.pdf', [ 'locale' => 'en_US.utf8', 'procEnv' => [ 'LANG' => 'en_US.utf-8', ], ]); $pdf->tempDir = sys_get_temp_dir() . '/myapp_pdftk'; ``` -------------------------------- ### Parameter Type Union: PDF File Input Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/types.md Example of a parameter that accepts either a string (file path) or a Pdf object for PDF file input. ```php // PDF file input string|Pdf $name ``` -------------------------------- ### Configure pdftk Command with Options Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Command.md Configures the Command instance with various options including the pdftk binary path, execution method, locale, and environment variables. This is useful for customizing pdftk execution in different environments. ```php $cmd = new Command(); $cmd->setOptions([ 'command' => '/usr/bin/pdftk', 'useExec' => true, 'locale' => 'en_US.utf8', 'procEnv' => [ 'LANG' => 'en_US.utf-8', ], ]); ``` -------------------------------- ### Get PDF Data Source: https://github.com/mikehaertl/php-pdftk/blob/master/README.md Read out metadata or form field information from a PDF file. Data can be retrieved as a boolean false on error, or as an object that can be cast to string or array. ```php use mikehaertl\pdftk\Pdf; // Get data $pdf = new Pdf('/path/my.pdf'); $data = $pdf->getData(); if ($data === false) { $error = $pdf->getError(); } // Get form data fields $pdf = new Pdf('/path/my.pdf'); $data = $pdf->getDataFields(); if ($data === false) { $error = $pdf->getError(); } // Get data as string echo $data; $txt = (string) $data; $txt = $data->__toString(); // Get data as array $arr = (array) $data; $arr = $data->__toArray(); $field1 = $data[0]['Field1']; ``` -------------------------------- ### Pdf Constructor Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Pdf.md Initializes a new Pdf instance. It can be used to load one or more PDF files, optionally with passwords, and configure pdftk options. ```APIDOC ## Constructor Creates a new Pdf instance and optionally initializes it with one or more PDF files. ### Parameters #### `$pdf` - Type: `string|Pdf|array|null` - Required: No - Default: `null` - Description: A PDF filename, Pdf instance, or associative array indexed by handle. Array values can be filenames or arrays of `[$filename, $password]` for password-protected files. #### `$options` - Type: `array` - Required: No - Default: `[]` - Description: Options to pass to the Command instance, such as the pdftk binary path or execution environment. ### Return Pdf instance ### Example ```php use mikehaertl\pdftk\Pdf; // Simple initialization with a file $pdf = new Pdf('/path/to/file.pdf'); // With password-protected file $pdf = new Pdf('/path/to/protected.pdf', [ 'command' => '/usr/bin/pdftk', ]); // Multiple files with handles $pdf = new Pdf([ 'A' => '/path/to/file1.pdf', 'B' => ['/path/to/file2.pdf', 'password123'], 'C' => '/path/to/file3.pdf', ]); // Empty instance, add files later $pdf = new Pdf(); $pdf->addFile('/path/to/file.pdf'); ``` ``` -------------------------------- ### Get Raw pdftk Output as String Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/DataFields.md Retrieve the original, unparsed output string from pdftk's dump_data_fields command. This can be useful for debugging or when the parsed data is not sufficient. ```php $pdf = new Pdf('/path/form.pdf'); $fields = $pdf->getDataFields(); echo (string) $fields; // Raw pdftk output ``` -------------------------------- ### InfoFile Constructor Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/InfoFile.md Creates a temporary info file for updating PDF metadata. Accepts metadata as an array or InfoFields instance, along with optional parameters for file naming and directory. ```APIDOC ## Constructor ```php public function __construct( array|InfoFields $data, ?string $suffix = null, ?string $prefix = null, ?string $directory = null, ?string $encoding = 'UTF-8' ): InfoFile ``` ### Description Creates a temporary info file for updating PDF metadata. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | |-----------|------|----------|---------| | `$data` | `array|InfoFields` | Yes | — | | `$suffix` | `string|null` | No | `'.txt'` | | `$prefix` | `string|null` | No | `'php_pdftk_info_'` | | `$directory` | `string|null` | No | `null` | | `$encoding` | `string` | No | `'UTF-8'` | ### Return InfoFile instance ### Throws Exception if encoding is not UTF-8 and `mbstring` extension is not available ### Example ```php use mikehaertl\pdftk\InfoFile; use mikehaertl\pdftk\Pdf; // Create InfoFile and update PDF metadata $infoFile = new InfoFile([ 'Info' => [ 'Title' => 'My Document', 'Author' => 'John Doe', 'Subject' => 'Test PDF', 'Keywords' => 'pdf, test, document', 'Creator' => 'My Application', ], ]); $pdf = new Pdf('/path/document.pdf'); $pdf->updateInfo($infoFile) ->saveAs('/path/updated.pdf'); ``` ``` -------------------------------- ### Create and Use InfoFile to Update PDF Metadata Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/InfoFile.md Instantiate InfoFile with metadata and use it to update a PDF document's information, saving the result to a new file. Ensure the Pdf class is imported. ```php use mikehaertl\pdftk\InfoFile; use mikehaertl\pdftk\Pdf; // Create InfoFile and update PDF metadata $infoFile = new InfoFile([ 'Info' => [ 'Title' => 'My Document', 'Author' => 'John Doe', 'Subject' => 'Test PDF', 'Keywords' => 'pdf, test, document', 'Creator' => 'My Application', ], ]); $pdf = new Pdf('/path/document.pdf'); $pdf->updateInfo($infoFile) ->saveAs('/path/updated.pdf'); ``` -------------------------------- ### Direct Usage of Command Class Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Command.md Demonstrates advanced direct usage of the Command class for lower-level control over pdftk operations. This includes adding files with handles, setting operations, specifying page ranges, adding options, and executing the command. ```php use mikehaertl\pdftk\Command; $cmd = new Command(); $cmd->addFile('/path/file1.pdf', 'A') ->addFile('/path/file2.pdf', 'B') ->setOperation('cat') ->addPageRange(1, 5, 'A') ->addOption('compress') ->execute('/path/output.pdf'); if (!$cmd->execute()) { echo "Error: " . $cmd->getError(); } ``` -------------------------------- ### Retrieve Last Error Message with Pdf::getError() Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/errors.md Use Pdf::getError() to get the last error message after an operation fails. It returns an empty string if no error occurred. ```php $pdf = new Pdf('/path/form.pdf'); if (!$pdf->fillForm(['field' => 'value'])->saveAs('/path/output.pdf')) { echo "Error: " . $pdf->getError(); } ``` -------------------------------- ### Creating and Using FDF File Separately Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/FdfFile.md Demonstrates creating an FDF file object first with specific form data, then using its path later to fill a PDF. The temporary FDF file is automatically cleaned up. ```php use mikehaertl\pdftk\FdfFile; $formData = [ 'Name' => 'John Doe', 'Email' => 'john@example.com', ]; // Create FDF file $fdf = new FdfFile($formData); $fdfPath = (string) $fdf; // Use it later $pdf = new Pdf('/path/form.pdf'); $pdf->fillForm($fdfPath)->saveAs('/path/filled.pdf'); // FDF file is automatically cleaned up when $fdf goes out of scope ``` -------------------------------- ### Set Command Options Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Command.md Sets options for the Command instance, such as custom pdftk path or execution method. Use this to configure the pdftk binary location and execution behavior. ```php $cmd = new Command(); $cmd->setOptions([ 'command' => '/usr/local/bin/pdftk', 'useExec' => true, ]); ``` -------------------------------- ### Instantiate FdfFile and Fill PDF Form Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/FdfFile.md Create an FdfFile instance with form data and use it to fill a PDF form. The temporary FDF file is automatically managed and deleted. ```php use mikehaertl\pdftk\FdfFile; use mikehaertl\pdftk\Pdf; // Simple form filling $fdf = new FdfFile([ 'FirstName' => 'John', 'LastName' => 'Doe', 'Email' => 'john@example.com', ]); $pdf = new Pdf('/path/form.pdf'); $pdf->fillForm($fdf) ->needAppearances() ->saveAs('/path/filled.pdf'); // The FdfFile is automatically deleted after use ``` -------------------------------- ### Add PDF Files to Instance Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Pdf.md Use this method to add PDF files to the Pdf instance for processing. You can specify a handle for each file and an optional password if the file is encrypted. ```php $pdf = new Pdf(); $pdf->addFile('/path/to/file1.pdf', 'A') ->addFile('/path/to/file2.pdf', 'B', 'secret_password') ->cat(1, 5, 'A') ->saveAs('/path/to/output.pdf'); ``` -------------------------------- ### Secure Production Server Configuration Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/configuration.md Configure locale and temporary directory settings for a production environment with security considerations, ensuring restricted permissions for temporary files. ```php $pdf = new Pdf('/var/www/secure/form.pdf', [ 'locale' => 'en_US.utf8', 'procEnv' => [ 'LANG' => 'en_US.utf-8', 'TMPDIR' => '/var/lib/myapp/tmp', // Restricted permissions ], ]); $pdf->tempDir = '/var/lib/myapp/tmp'; // Only readable by app user $pdf->fillForm($_POST['form_data'])->saveAs('/var/www/output/result.pdf'); ``` -------------------------------- ### Get Temporary XFDF File Name Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/XfdfFile.md Retrieves the absolute path to the temporary XFDF file created by the XfdfFile object. This path can be used directly with PDF form filling functions. ```php $xfdf = new XfdfFile(['Name' => 'John']); echo $xfdf->getFileName(); // /tmp/php_pdftk_xfdf_abc123def.xfdf ``` -------------------------------- ### Get Raw dump_data Output as String Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/InfoFields.md Convert an InfoFields instance to a string to retrieve the original, unparsed output from the pdftk dump_data command. This is useful for debugging or when the raw output is needed. ```php $pdf = new Pdf('/path/document.pdf'); $info = $pdf->getData(); echo (string) $info; // Raw pdftk output ``` -------------------------------- ### Chain Multiple PDF Operations Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/README.md Demonstrates chaining multiple operations, such as extracting pages and then filling a form, using the library's fluent interface. The result of one operation can be used as input for the next. ```php // Operation 1: Extract pages $pdf1 = new Pdf('/path/original.pdf'); $pdf1->cat(1, 10); // Operation 2: Use result from operation 1 $pdf2 = new Pdf($pdf1); $pdf2->fillForm(['field' => 'value']) ->needAppearances() ->saveAs('/path/final.pdf'); ``` -------------------------------- ### PDFTK Constructor Configuration Options Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/types.md Specifies the structure of the configuration array for the PDFTK constructor, including the path to the binary, execution method, locale, and environment variables. ```php array [ 'command' => string, // Path to pdftk binary 'useExec' => bool, // Use exec() instead of shell_exec() 'locale' => string, // Locale for pdftk execution 'procEnv' => array, // Environment variables ] ``` -------------------------------- ### Set Environment Variables for PHP Execution Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/configuration.md Configure locale environment variables before running PHP scripts to ensure proper pdftk operation. Examples for bash and Apache .htaccess are provided. ```bash export LANG=en_US.utf-8 export LC_ALL=en_US.utf-8 php /path/to/script.php ``` ```apache SetEnv LANG en_US.utf-8 SetEnv LC_ALL en_US.utf-8 ``` ```nginx env[LANG] = en_US.utf-8 env[LC_ALL] = en_US.utf-8 ``` -------------------------------- ### Manage Output File Permissions in PHP-PDFTK Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/errors.md This solution addresses 'Failed to open output file' errors by ensuring the output directory exists and is writable. It includes code to create the directory and set appropriate permissions if necessary. ```php $pdf = new Pdf('/path/form.pdf'); $result = $pdf->fillForm(['field' => 'value']) ->saveAs('/readonly/output.pdf'); // Directory read-only if (!$result) { echo $pdf->getError(); } ``` ```php $outputDir = '/path/to/output'; if (!is_dir($outputDir)) { mkdir($outputDir, 0755, true); } if (!is_writable($outputDir)) { chmod($outputDir, 0755); } $pdf->fillForm(['field' => 'value']) ->saveAs($outputDir . '/output.pdf'); ``` -------------------------------- ### Parameter Type Union: Form Data Input Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/types.md Example of a parameter that accepts either a string (file path) or an array (associative array of field data) for form data input. ```php // Form data input string|array $data - string: filename path - array: associative array of field data ``` -------------------------------- ### Accessing PDF InfoFields Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/InfoFields.md Demonstrates how to instantiate the Pdf class, retrieve document information, and access various fields like NumberOfPages, PdfID, document metadata, bookmarks, and page media information. ```APIDOC ## Accessing PDF InfoFields InfoFields instances can be accessed as arrays: ```php $pdf = new Pdf('/path/document.pdf'); $info = $pdf->getData(); // Access simple properties echo $info['NumberOfPages']; // "15" echo $info['PdfID0']; // PDF ID hash // Access document info (metadata) if (isset($info['Info'])) { echo $info['Info']['Title']; // Document title echo $info['Info']['Author']; // Document author echo $info['Info']['Producer']; // PDF producer } // Access bookmarks if (isset($info['Bookmark'])) { foreach ($info['Bookmark'] as $bookmark) { echo $bookmark['Title']; // Bookmark title echo $bookmark['Level']; // Nesting level echo $bookmark['PageNumber']; // Target page } } // Access page information if (isset($info['PageMedia'])) { foreach ($info['PageMedia'] as $page) { echo $page['MediaBox']; // Page dimensions } } if (isset($info['PageLabel'])) { foreach ($info['PageLabel'] as $label) { echo $label['PageLabels']; // Custom page label } } ``` ``` -------------------------------- ### Instantiate InfoFields and Access Metadata Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/InfoFields.md Create a Pdf instance, extract data using getData(), and access parsed metadata like 'NumberOfPages'. This is useful for retrieving document properties after processing. ```php use mikehaertl\pdftk\Pdf; $pdf = new Pdf('/path/document.pdf'); $info = $pdf->getData(); if ($info !== false) { // InfoFields instance with parsed metadata echo $info['NumberOfPages']; // Total page count } ``` -------------------------------- ### Dynamic Form Filling from User Input Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/XfdfFile.md Populate a PDF form using data submitted by a user, for example, from a web form. Uses the null coalescing operator for safe access to POST data. ```php // Process form submission $userData = [ 'FirstName' => $_POST['first_name'] ?? '', 'LastName' => $_POST['last_name'] ?? '', 'Email' => $_POST['email'] ?? '', ]; $pdf = new Pdf('/path/form.pdf'); $result = $pdf->fillForm($userData) ->needAppearances() ->saveAs('/path/filled_' . time() . '.pdf'); if ($result) { echo "Form filled successfully"; } else { echo "Error: " . $pdf->getError(); } ``` -------------------------------- ### Create Document Template with Metadata Function Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/InfoFile.md This example defines a reusable function `updatePdfMetadata` to consistently apply metadata to PDF documents. It accepts PDF object, title, author, subject, and keywords as arguments. ```php // Create a reusable function for consistent metadata function updatePdfMetadata( Pdf $pdf, string $title, string $author, string $subject = '', array $keywords = [] ): bool { $keywordString = implode(', ', $keywords); return $pdf->updateInfo([ 'Info' => [ 'Title' => $title, 'Author' => $author, 'Subject' => $subject, 'Keywords' => $keywordString, 'Creator' => 'My Application v1.0', 'Producer' => 'pdftk', 'ModDate' => 'D:' . date('YmdHis'), ], ])->saveAs('/path/output.pdf'); } // Usage $pdf = new Pdf('/path/template.pdf'); updatePdfMetadata( $pdf, 'Invoice #12345', 'Accounting Department', 'Monthly Invoice', ['invoice', 'billing', 'accounting'] ); ``` -------------------------------- ### Define Bookmark Structure Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/InfoFields.md Assign an array of bookmarks to the 'Bookmark' key. Each bookmark requires a 'Title', 'Level', and 'PageNumber'. ```php $info['Bookmark'] = [ [ 'Title' => 'Chapter 1', 'Level' => '1', 'PageNumber' => '1', ], [ 'Title' => 'Chapter 1.1', 'Level' => '2', 'PageNumber' => '3', ], [ 'Title' => 'Chapter 2', 'Level' => '1', 'PageNumber' => '8', ], ]; ``` -------------------------------- ### PHP Configuration for Linux (Debian/Ubuntu) Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/configuration.md Configure the pdftk command path in PHP for Debian/Ubuntu systems. ```php [ 'command' => '/usr/bin/pdftk', ] ``` -------------------------------- ### Get PDF Metadata Using the Pdf Class Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Command.md The recommended way to interact with PDF files is through the Pdf class, which simplifies common operations like retrieving metadata. It handles temporary files and validation automatically. ```php use mikehaertl\pdftk\Pdf; $pdf = new Pdf('/path/file.pdf'); $metadata = $pdf->getData(); ``` -------------------------------- ### Programmatic Date Formatting for PDF Metadata Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/InfoFile.md This example shows how to programmatically format dates for PDF metadata fields like CreationDate and ModDate. It uses a helper function to ensure the correct 'D:YYYYMMDDHHMMSS' format. ```php function getCurrentPdfDate(): string { return 'D:' . date('YmdHis'); } $pdf = new Pdf('/path/document.pdf'); $result = $pdf->updateInfo([ 'Info' => [ 'Title' => 'My Document', 'CreationDate' => getCurrentPdfDate(), 'ModDate' => getCurrentPdfDate(), ], ]) ->saveAs('/path/updated.pdf'); ``` -------------------------------- ### addPageRange() Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Command.md Adds a page range specification to the operation argument, used for operations like 'cat', 'shuffle', etc. This method supports specifying start and end pages, file handles, qualifiers (even/odd), and rotation. ```APIDOC ## addPageRange() ### Description Adds a page range specification to the operation argument (used by cat, shuffle, etc.). ### Method Signature ```php public function addPageRange( int|string|array $start, int|string|null $end = null, string|null $handle = null, string|null $qualifier = null, string|null $rotation = null ): self ``` ### Parameters #### Path Parameters * **$start** (int|string|array) - Required - Start page number, array of page numbers, or 'end' for last page. * **$end** (int|string|null) - Optional - End page number or null for single page. * **$handle** (string|null) - Optional - File handle (A, B, C, etc.). Omit if only one file added. * **$qualifier** (string|null) - Optional - Qualifier: 'even' or 'odd' or null. * **$rotation** (string|null) - Optional - Rotation: '0', '90', '180', '270', 'north', 'east', 'south', 'west', 'left', 'right', 'down'. ### Return `self` (for method chaining) ### Throws Exception if command has already been executed ### Example ```php $cmd = new Command(); $cmd->addFile('/path/file1.pdf', 'A') ->addFile('/path/file2.pdf', 'B') ->setOperation('cat') ->addPageRange(1, 5, 'A') ->addPageRange(1, 'end', 'B', 'odd', 'east'); ``` ``` -------------------------------- ### Chaining InfoFile with Pdf Operations Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/InfoFile.md Demonstrates how to use InfoFile's updateInfo method in a chain with other Pdf operations like fillForm and saveAs. ```php $pdf = new Pdf('/path/document.pdf'); $result = $pdf->fillForm(['field' => 'value']) ->updateInfo([ 'Info' => [ 'Title' => 'Filled Form', ], ]) ->saveAs('/path/output.pdf'); ``` -------------------------------- ### PHP Configuration for macOS Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/configuration.md Configure the pdftk command path in PHP for macOS systems. ```php [ 'command' => '/usr/local/bin/pdftk', ] ``` -------------------------------- ### Add Page Range to PDF Operation Source: https://github.com/mikehaertl/php-pdftk/blob/master/_autodocs/api-reference/Command.md Use this method to specify page ranges for operations like 'cat' or 'shuffle'. It supports various formats for start and end pages, file handles, qualifiers (even/odd), and rotation. ```php $cmd = new Command(); $cmd->addFile('/path/file1.pdf', 'A') ->addFile('/path/file2.pdf', 'B') ->setOperation('cat') ->addPageRange(1, 5, 'A') ->addPageRange(1, 'end', 'B', 'odd', 'east'); ```