forked from nextcloud/richdocuments
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPdfService.php
More file actions
92 lines (78 loc) Β· 2.25 KB
/
Copy pathPdfService.php
File metadata and controls
92 lines (78 loc) Β· 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Richdocuments\Service;
use mikehaertl\pdftk\Pdf;
use OCP\Files\Node;
use OCP\Files\Template\FieldFactory;
use OCP\Files\Template\FieldType;
use Psr\Log\LoggerInterface;
class PdfService {
public function __construct(
private LoggerInterface $logger,
) {
}
public function extractFields(Node $file): array {
$filePath = $file->getStorage()->getLocalFile($file->getInternalPath());
try {
$pdf = new Pdf($filePath);
$fields = $pdf->getDataFields() ?: [];
$templateFields = [];
$index = 0;
foreach ($fields as $field) {
$fieldType = self::matchFieldType($field['FieldType']);
if ($fieldType === null) {
continue;
}
$templateField = FieldFactory::createField(
(string)$index,
$fieldType,
);
$templateField->setValue($field['FieldValue']);
$templateField->alias = $field['FieldName'];
$templateFields[] = $templateField;
$index++;
}
return $templateFields;
} catch (\Exception $e) {
$this->logger->error('Failed to extract fields from PDF: {error}', ['error' => $e->getMessage(), 'exception' => $e]);
return [];
}
}
public function fillFields(Node $file, array $fieldValues) {
if (!$file instanceof \OCP\Files\File) {
return;
}
$filePath = $file->getStorage()->getLocalFile($file->getInternalPath());
try {
$pdf = new Pdf($filePath);
$fields = $pdf->getDataFields();
$fillData = [];
foreach ($fieldValues as $index => $field) {
if (!isset($fields[$index])) {
continue;
}
$fieldName = $fields[$index]['FieldName'];
$fieldData = $field['content'] ?? $fields[$index]['FieldValue'];
$fillData[$fieldName] = $fieldData;
}
unset($pdf);
$pdf = new Pdf($filePath);
$pdf->fillForm($fillData);
$pdf->flatten();
$pdf->saveAs($filePath);
return file_get_contents($filePath);
} catch (\Exception $e) {
$this->logger->error('Failed to fill fields in PDF: {error}', ['error' => $e->getMessage(), 'exception' => $e]);
throw $e;
}
}
public static function matchFieldType(string $type): ?FieldType {
return match ($type) {
'Text' => FieldType::RichText,
default => null
};
}
}