Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
16 / 16 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| FdfWriter | |
100.00% |
16 / 16 |
|
100.00% |
2 / 2 |
4 | |
100.00% |
1 / 1 |
| generate | |
100.00% |
14 / 14 |
|
100.00% |
1 / 1 |
3 | |||
| escapeString | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Phpdftk\Pdf\Core\Interactive\Form; |
| 6 | |
| 7 | /** |
| 8 | * FDF (Forms Data Format) file writer — ISO 32000-2 §12.7.8. |
| 9 | * |
| 10 | * Generates a standalone .fdf file containing field name/value pairs |
| 11 | * that can be used to fill a PDF form. |
| 12 | */ |
| 13 | final class FdfWriter |
| 14 | { |
| 15 | /** |
| 16 | * Generate FDF file content from a field name → value map. |
| 17 | * |
| 18 | * @param array<string, string> $fields Field name => value |
| 19 | * @param string|null $pdfPath Optional /F entry pointing to the PDF file |
| 20 | */ |
| 21 | public static function generate(array $fields, ?string $pdfPath = null): string |
| 22 | { |
| 23 | $chunks = []; |
| 24 | $chunks[] = "%FDF-1.2\n"; |
| 25 | |
| 26 | // Build the /Fields array |
| 27 | $fieldsArray = ''; |
| 28 | foreach ($fields as $name => $value) { |
| 29 | $fieldsArray .= '<< /T ' . self::escapeString($name) |
| 30 | . ' /V ' . self::escapeString($value) . " >>\n"; |
| 31 | } |
| 32 | |
| 33 | // Build /FDF dictionary |
| 34 | $fdfDict = "<< /Fields [\n" . $fieldsArray . "]\n"; |
| 35 | if ($pdfPath !== null) { |
| 36 | $fdfDict .= '/F ' . self::escapeString($pdfPath) . "\n"; |
| 37 | } |
| 38 | $fdfDict .= ">>"; |
| 39 | |
| 40 | // Catalog |
| 41 | $chunks[] = "1 0 obj\n<< /FDF " . $fdfDict . " >>\nendobj\n"; |
| 42 | |
| 43 | // Trailer |
| 44 | $chunks[] = "trailer\n<< /Root 1 0 R >>\n"; |
| 45 | $chunks[] = '%%EOF'; |
| 46 | |
| 47 | return implode('', $chunks); |
| 48 | } |
| 49 | |
| 50 | private static function escapeString(string $value): string |
| 51 | { |
| 52 | $escaped = str_replace(['\\', '(', ')'], ['\\\\', '\\(', '\\)'], $value); |
| 53 | return '(' . $escaped . ')'; |
| 54 | } |
| 55 | } |