-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdfmerger.py
More file actions
804 lines (675 loc) · 32.5 KB
/
pdfmerger.py
File metadata and controls
804 lines (675 loc) · 32.5 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
import sys
import glob
import re
import os
import json
import shutil
import datetime
import getpass
from pathlib import Path
from typing import List, Dict, Optional, Tuple, Any, Union
from pypdf import PdfWriter, PdfReader, Transformation
import fitz # PyMuPDF per alcune operazioni avanzate
from pypdf.generic import (
DictionaryObject,
NumberObject,
FloatObject,
NameObject,
TextStringObject,
ArrayObject,
DecodedStreamObject,
EncodedStreamObject,
ByteStringObject,
)
import logging
import tempfile
from zlib import compress, decompress
class PdfPermissions:
"""Gestisce i permessi del PDF."""
def __init__(self):
self.printing = False
self.degraded_printing = False
self.modify_contents = False
self.assembly = False
self.copy_contents = False
self.screen_readers = False
self.modify_annotations = False
self.fill_in = False
self.all_features = False
def from_args(self, permissions: List[str]) -> None:
"""Imposta i permessi da una lista di stringhe."""
for perm in permissions:
perm = perm.lower()
if perm == 'printing':
self.printing = True
elif perm == 'degradedprinting':
self.degraded_printing = True
elif perm == 'modifycontents':
self.modify_contents = True
self.assembly = True
elif perm == 'assembly':
self.assembly = True
elif perm == 'copycontents':
self.copy_contents = True
self.screen_readers = True
elif perm == 'screenreaders':
self.screen_readers = True
elif perm == 'modifyannotations':
self.modify_annotations = True
self.fill_in = True
elif perm == 'fillin':
self.fill_in = True
elif perm == 'allfeatures':
self.all_features = True
self.printing = True
self.degraded_printing = True
self.modify_contents = True
self.assembly = True
self.copy_contents = True
self.screen_readers = True
self.modify_annotations = True
self.fill_in = True
def to_pypdf(self) -> Dict[str, bool]:
"""Converte i permessi nel formato pypdf."""
perms = {
"print": self.printing or self.all_features,
"modify": self.modify_contents or self.all_features,
"copy": self.copy_contents or self.all_features,
"annotate": self.modify_annotations or self.all_features
}
return perms
class PdfTool:
"""Classe principale che implementa le funzionalità di pdftk."""
VERSION = "2.0.0"
COPYRIGHT = """Copyright (C) 2025 - Python Version of pdftk
This is free software; see the source code for copying conditions.
There is NO warranty, not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."""
def __init__(self):
self.input_files: Dict[str, str] = {} # handle -> filepath
self.input_passwords: Dict[str, str] = {} # handle -> password
self.output_file: Optional[str] = None
self.operation: Optional[str] = None
self.operation_args: List[str] = []
self.encrypt_40bit: bool = False
self.encrypt_128bit: bool = False
self.owner_pw: Optional[str] = None
self.user_pw: Optional[str] = None
self.permissions = PdfPermissions()
self.compress: bool = True
self.flatten: bool = False
self.verbose: bool = False
self.do_ask: bool = True # Modalità interattiva di default
self.repair_mode: bool = False
self.logger = self._setup_logger()
def _setup_logger(self) -> logging.Logger:
"""Configura il logger per la modalità verbose."""
logger = logging.getLogger("pdfmerger")
handler = logging.StreamHandler()
formatter = logging.Formatter('%(levelname)s: %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger
def prompt_for_input(self, prompt_text: str, password: bool = False) -> str:
"""Gestisce l'input interattivo."""
if not self.do_ask:
print(f"Errore: richiesto input per '{prompt_text}' ma la modalità do_ask è disabilitata")
sys.exit(1)
if password:
return getpass.getpass(prompt_text)
return input(prompt_text)
def parse_page_range(self, range_str: str) -> Optional[List[int]]:
"""Converte una stringa range in una lista di numeri di pagina."""
if '-' not in range_str:
return [int(range_str)]
start, end = range_str.split('-')
if end == 'end':
return None # Sarà gestito dopo aver aperto il PDF
start = int(start)
end = int(end)
step = 1 if start <= end else -1
return list(range(start, end + step, step))
def read_pdf_with_password(self, filepath: str, password: Optional[str] = None) -> PdfReader:
"""Legge un PDF, gestendo la password se necessario."""
try:
return PdfReader(filepath, password=password)
except:
if password:
print(f"Password non valida per il file: {filepath}")
sys.exit(1)
return PdfReader(filepath)
def apply_encryption(self, writer: PdfWriter) -> None:
"""Applica la crittografia al PDF."""
if self.encrypt_40bit or self.encrypt_128bit or self.owner_pw or self.user_pw:
encryption_length = 40 if self.encrypt_40bit else 128
writer.encrypt(
user_password=self.user_pw or '',
owner_password=self.owner_pw or '',
use_128bit=encryption_length == 128,
permissions_flag=self.permissions.to_pypdf()
)
def operation_cat(self, input_specs: List[Tuple[str, List[Optional[List[int]]]]], output: str) -> None:
"""Unisce i PDF specificati in un unico file."""
writer = PdfWriter()
for pdf_path, page_ranges in input_specs:
try:
password = self.input_passwords.get(pdf_path, None)
pdf = self.read_pdf_with_password(pdf_path, password)
if not page_ranges:
writer.append_pages_from_reader(pdf)
continue
for range_spec in page_ranges:
if range_spec is None: # caso "end"
pages = list(range(1, len(pdf.pages) + 1))
else:
pages = [p for p in range_spec if 1 <= p <= len(pdf.pages)]
for page_num in pages:
writer.add_page(pdf.pages[page_num - 1])
except Exception as e:
print(f"Errore nel processare {pdf_path}: {str(e)}")
sys.exit(1)
self.apply_encryption(writer)
with open(output, 'wb') as out_file:
writer.write(out_file)
def operation_burst(self, input_file: str, output_pattern: Optional[str] = None) -> None:
"""Divide un PDF in pagine singole."""
if not output_pattern:
output_pattern = "pg_%04d.pdf"
password = self.input_passwords.get(input_file, None)
pdf = self.read_pdf_with_password(input_file, password)
for i in range(len(pdf.pages)):
writer = PdfWriter()
writer.add_page(pdf.pages[i])
output_file = output_pattern % (i + 1)
self.apply_encryption(writer)
with open(output_file, 'wb') as out:
writer.write(out)
# Crea anche il report
self.operation_dump_data(input_file, "doc_data.txt")
def operation_dump_data(self, input_file: str, output_file: Optional[str] = None) -> None:
"""Estrae i metadati e altre informazioni dal PDF."""
try:
password = self.input_passwords.get(input_file, None)
pdf = self.read_pdf_with_password(input_file, password)
data = {
"PDF Version": pdf.pdf_header,
"Metadata": pdf.metadata,
"Number of Pages": len(pdf.pages),
}
output_str = json.dumps(data, indent=2)
if output_file:
with open(output_file, 'w', encoding='utf-8') as f:
f.write(output_str)
else:
print(output_str)
except Exception as e:
print(f"Errore durante l'estrazione dei dati: {str(e)}")
sys.exit(1)
def operation_background(self, input_file: str, background_file: str, output: str) -> None:
"""Applica un PDF come sfondo."""
try:
# Usa PyMuPDF per questa operazione
doc = fitz.open(input_file)
bg_doc = fitz.open(background_file)
if not bg_doc.page_count:
print("Il file di sfondo è vuoto")
sys.exit(1)
bg_page = bg_doc[0]
for page in doc:
# Scala lo sfondo per adattarlo alla pagina
rect = page.rect
bg_page.set_rotation(0)
matrix = fitz.Matrix(rect.width/bg_page.rect.width,
rect.height/bg_page.rect.height)
pix = bg_page.get_pixmap(matrix=matrix)
page.insert_image(rect, pixmap=pix)
doc.save(output)
except Exception as e:
print(f"Errore durante l'applicazione dello sfondo: {str(e)}")
sys.exit(1)
def operation_fill_form(self, input_file: str, fdf_file: str, output: str) -> None:
"""Compila un modulo PDF con dati FDF."""
try:
password = self.input_passwords.get(input_file, None)
pdf = self.read_pdf_with_password(input_file, password)
writer = PdfWriter()
writer.append_pages_from_reader(pdf)
# Leggi i dati FDF (implementazione semplificata)
form_data = {}
with open(fdf_file, 'r', encoding='utf-8') as f:
for line in f:
if '=' in line:
key, value = line.strip().split('=', 1)
form_data[key.strip()] = value.strip()
# Compila il form
writer.update_page_form_field_values(
writer.pages[0], # Aggiorna la prima pagina
form_data
)
if self.flatten:
writer.flatten_annotations()
self.apply_encryption(writer)
with open(output, 'wb') as out_file:
writer.write(out_file)
except Exception as e:
print(f"Errore durante la compilazione del form: {str(e)}")
sys.exit(1)
def handle_stream_compression(self, pdf_obj: Union[DecodedStreamObject, EncodedStreamObject]) -> None:
"""Gestisce la compressione/decompressione degli stream PDF."""
if isinstance(pdf_obj, DecodedStreamObject):
if self.compress:
pdf_obj.compress()
elif isinstance(pdf_obj, EncodedStreamObject):
if not self.compress:
pdf_obj.decompress()
def repair_pdf(self, input_file: str, output_file: str) -> None:
"""Tenta di riparare un PDF corrotto."""
try:
# Usa PyMuPDF per tentare la riparazione
doc = fitz.open(input_file)
doc.save(output_file, clean=True, deflate=True, garbage=3)
doc.close()
self.logger.info(f"PDF riparato con successo: {output_file}")
except Exception as e:
self.logger.error(f"Impossibile riparare il PDF: {str(e)}")
sys.exit(1)
def operation_attach_files(self, input_file: str, attachments: List[str], page_number: Optional[int] = None) -> None:
"""Allega file al PDF."""
try:
reader = self.read_pdf_with_password(input_file, self.input_passwords.get(input_file))
writer = PdfWriter()
writer.append_pages_from_reader(reader)
for attachment in attachments:
if not os.path.exists(attachment):
self.logger.error(f"File da allegare non trovato: {attachment}")
continue
with open(attachment, 'rb') as file:
data = file.read()
# Crea l'oggetto FileSpec
file_spec = DictionaryObject()
file_spec.update({
NameObject("/Type"): NameObject("/Filespec"),
NameObject("/F"): TextStringObject(os.path.basename(attachment)),
NameObject("/EF"): DictionaryObject({
NameObject("/F"): writer.add_attachment(attachment, data)
})
})
if page_number is not None:
if 1 <= page_number <= len(writer.pages):
page = writer.pages[page_number - 1]
if "/Annots" not in page:
page[NameObject("/Annots")] = ArrayObject()
page["/Annots"].append(file_spec)
else:
# Allega a livello documento
if "/Names" not in writer.root:
writer.root[NameObject("/Names")] = DictionaryObject()
if "/EmbeddedFiles" not in writer.root["/Names"]:
writer.root["/Names"][NameObject("/EmbeddedFiles")] = DictionaryObject({
NameObject("/Names"): ArrayObject()
})
writer.root["/Names"]["/EmbeddedFiles"]["/Names"].append(
TextStringObject(os.path.basename(attachment)))
writer.root["/Names"]["/EmbeddedFiles"]["/Names"].append(file_spec)
self.apply_encryption(writer)
with open(self.output_file, 'wb') as out_file:
writer.write(out_file)
except Exception as e:
self.logger.error(f"Errore durante l'allegamento dei file: {str(e)}")
sys.exit(1)
def operation_unpack_files(self, input_file: str, output_dir: Optional[str] = None) -> None:
"""Estrae i file allegati dal PDF."""
try:
if output_dir is None:
output_dir = os.getcwd()
elif output_dir.upper() == "PROMPT":
output_dir = self.prompt_for_input("Inserisci la directory di output: ")
os.makedirs(output_dir, exist_ok=True)
reader = self.read_pdf_with_password(input_file, self.input_passwords.get(input_file))
if "/Names" in reader.trailer["/Root"] and "/EmbeddedFiles" in reader.trailer["/Root"]["/Names"]:
names = reader.trailer["/Root"]["/Names"]["/EmbeddedFiles"]["/Names"]
for i in range(0, len(names), 2):
filename = names[i]
filespec = names[i+1]
if "/EF" in filespec and "/F" in filespec["/EF"]:
stream = filespec["/EF"]["/F"].get_data()
output_path = os.path.join(output_dir, filename)
with open(output_path, 'wb') as f:
f.write(stream)
self.logger.info(f"Estratto: {filename}")
# Cerca anche allegati a livello pagina
for i, page in enumerate(reader.pages):
if "/Annots" in page:
for annot in page["/Annots"]:
if "/Type" in annot and annot["/Type"] == "/Filespec":
if "/EF" in annot and "/F" in annot["/EF"]:
stream = annot["/EF"]["/F"].get_data()
filename = f"page_{i+1}_{annot['/F']}"
output_path = os.path.join(output_dir, filename)
with open(output_path, 'wb') as f:
f.write(stream)
self.logger.info(f"Estratto: {filename} (dalla pagina {i+1})")
except Exception as e:
self.logger.error(f"Errore durante l'estrazione degli allegati: {str(e)}")
sys.exit(1)
def operation_dump_data_fields(self, input_file: str, output_file: Optional[str] = None) -> None:
"""Estrae informazioni sui campi del form."""
try:
reader = self.read_pdf_with_password(input_file, self.input_passwords.get(input_file))
form_fields = []
if reader.get_fields():
for field_name, field_data in reader.get_fields().items():
field_info = {
"FieldName": field_name,
"FieldType": field_data.get("/FT", "Unknown"),
"FieldFlags": field_data.get("/Ff", 0),
"Value": field_data.get("/V", ""),
"DefaultValue": field_data.get("/DV", "")
}
form_fields.append(field_info)
output_str = json.dumps({"FormFields": form_fields}, indent=2)
if output_file:
with open(output_file, 'w', encoding='utf-8') as f:
f.write(output_str)
else:
print(output_str)
except Exception as e:
self.logger.error(f"Errore durante l'estrazione dei campi: {str(e)}")
sys.exit(1)
def operation_update_info(self, input_file: str, info_file: str) -> None:
"""Aggiorna i metadati del PDF."""
try:
reader = self.read_pdf_with_password(input_file, self.input_passwords.get(input_file))
writer = PdfWriter()
writer.append_pages_from_reader(reader)
# Leggi il file info
with open(info_file, 'r', encoding='utf-8') as f:
info_data = json.load(f)
# Aggiorna i metadati
writer.add_metadata(info_data)
self.apply_encryption(writer)
with open(self.output_file, 'wb') as out_file:
writer.write(out_file)
except Exception as e:
self.logger.error(f"Errore durante l'aggiornamento dei metadati: {str(e)}")
sys.exit(1)
def parse_arguments(self, args: List[str]) -> bool:
"""Analizza gli argomenti della linea di comando in stile pdftk."""
if len(args) < 2:
return False
# Gestione help e versione
if args[1] in ['--help', '-h']:
self.print_help()
sys.exit(0)
elif args[1] == '--version':
print(f"pdfmerger versione {self.VERSION}")
print(self.COPYRIGHT)
sys.exit(0)
# Rimuovi il nome del programma
args = args[1:]
i = 0
while i < len(args):
arg = args[i].lower()
# Gestione handle e password
if '=' in args[i] and len(args[i]) > 2:
handle, value = args[i].split('=', 1)
if len(handle) == 1 and handle.isupper():
self.input_files[handle] = value
# Gestione input_pw
elif arg == 'input_pw' and i + 1 < len(args):
i += 1
pw_spec = args[i]
if '=' in pw_spec:
handle, pw = pw_spec.split('=', 1)
if handle in self.input_files:
self.input_passwords[self.input_files[handle]] = pw
# Gestione operazioni
elif arg in ['cat', 'burst', 'dump_data', 'background', 'fill_form']:
self.operation = arg
i += 1
# Raccogli argomenti dell'operazione fino a output
while i < len(args) and args[i].lower() != 'output':
self.operation_args.append(args[i])
i += 1
i -= 1
# Gestione output
elif arg == 'output' and i + 1 < len(args):
i += 1
self.output_file = args[i]
# Gestione encrypt
elif arg in ['encrypt_40bit', 'encrypt_128bit']:
setattr(self, arg, True)
# Gestione password
elif arg in ['owner_pw', 'user_pw'] and i + 1 < len(args):
i += 1
setattr(self, arg, args[i])
# Gestione permessi
elif arg == 'allow' and i + 1 < len(args):
i += 1
self.permissions.from_args([args[i]])
# Gestione altre opzioni
elif arg == 'flatten':
self.flatten = True
elif arg == 'compress':
self.compress = True
elif arg == 'uncompress':
self.compress = False
elif arg == 'verbose':
self.verbose = True
self.logger.setLevel(logging.DEBUG)
elif arg == 'repair':
self.repair_mode = True
elif arg == 'do_ask':
self.do_ask = True
elif arg == 'dont_ask':
self.do_ask = False
elif arg == "prompt":
# Gestione input interattivo
if i > 0 and args[i-1].lower() in ['output', 'input_pw', 'owner_pw', 'user_pw']:
return self.prompt_for_input(f"Inserisci {args[i-1]}: ",
password=args[i-1].endswith('_pw'))
elif not arg.startswith('-') and self.operation is None:
# File di input senza handle
if arg.upper() == "PROMPT":
filepath = self.prompt_for_input("Inserisci il percorso del file: ")
else:
filepath = arg
self.input_files[str(len(self.input_files))] = filepath
i += 1
return bool(self.output_file)
def print_help(self) -> None:
"""Stampa il messaggio di aiuto dettagliato."""
help_text = f"""pdfmerger versione {self.VERSION}
{self.COPYRIGHT}
SINOSSI
pdfmerger <input PDF files | - | PROMPT>
[input_pw <input PDF owner passwords | PROMPT>]
[<operation> <operation arguments>]
[output <output filename | - | PROMPT>]
[encrypt_40bit | encrypt_128bit]
[allow <permissions>]
[owner_pw <owner password | PROMPT>]
[user_pw <user password | PROMPT>]
[flatten] [compress | uncompress]
[verbose] [dont_ask | do_ask]
Dove:
<operation> può essere:
[cat | attach_files | unpack_files | burst |
fill_form | background |
dump_data | dump_data_fields | update_info]
DESCRIZIONE
Se PDF è carta elettronica, allora pdfmerger è una
pinzatrice elettronica, una perforatrice, una rilegatura,
un anello decodificatore segreto e occhiali a raggi X.
OPERAZIONI
cat [<page ranges>]
Concatena le pagine dai PDF di input
burst
Divide un PDF in pagine singole
attach_files <file> [to_page <number>]
Allega file al PDF
unpack_files
Estrae i file allegati
fill_form <FDF file>
Compila un modulo PDF
background <PDF file>
Applica un PDF come sfondo
dump_data
Estrae metadati e segnalibri
dump_data_fields
Estrae informazioni sui campi form
update_info <info file>
Aggiorna i metadati del PDF
OPZIONI
allow <permissions>
Permessi disponibili:
Printing, DegradedPrinting, ModifyContents,
Assembly, CopyContents, ScreenReaders,
ModifyAnnotations, FillIn, AllFeatures
[compress | uncompress]
Gestisce la compressione degli stream
[flatten]
Appiattisce i campi form
[encrypt_40bit | encrypt_128bit]
Imposta la crittografia
[verbose]
Mostra informazioni dettagliate
[do_ask | dont_ask]
Abilita/disabilita l'input interattivo
ESEMPI
Unione PDF:
pdfmerger 1.pdf 2.pdf cat output 3.pdf
Crittografia:
pdfmerger in.pdf output out.pdf encrypt_128bit owner_pw foo
Riparazione:
pdfmerger broken.pdf output fixed.pdf repair
Estrazione allegati:
pdfmerger in.pdf unpack_files output ./allegati/"""
print(help_text)
def process(self) -> None:
"""Processa l'operazione richiesta."""
try:
input_file = next(iter(self.input_files.values())) if self.input_files else None
# Se repair_mode è attivo, tenta di riparare il PDF prima
if self.repair_mode and input_file:
temp_file = tempfile.mktemp(suffix='.pdf')
self.repair_pdf(input_file, temp_file)
input_file = temp_file
self.input_files = {next(iter(self.input_files.keys())): temp_file}
if self.operation == 'cat':
# Prepara gli input_specs per cat
input_specs = []
if not self.operation_args:
# Usa tutti i file nell'ordine dato
for file in self.input_files.values():
input_specs.append((file, []))
else:
# Processa i range specificati
for range_spec in self.operation_args:
match = re.match(r'([A-Z])?(\d+(?:-(?:\d+|end))?)?', range_spec)
if match:
handle, page_range = match.groups()
if handle and handle in self.input_files:
file_path = self.input_files[handle]
elif not handle and self.input_files:
file_path = next(iter(self.input_files.values()))
else:
self.logger.error(f"Handle {handle} non trovato")
sys.exit(1)
page_numbers = self.parse_page_range(page_range) if page_range else []
input_specs.append((file_path, [page_numbers]))
self.operation_cat(input_specs, self.output_file)
elif self.operation == 'burst':
if len(self.input_files) != 1:
self.logger.error("L'operazione burst richiede esattamente un file di input")
sys.exit(1)
self.operation_burst(input_file, self.output_file)
elif self.operation == 'dump_data':
if len(self.input_files) != 1:
self.logger.error("L'operazione dump_data richiede esattamente un file di input")
sys.exit(1)
self.operation_dump_data(input_file, self.output_file)
elif self.operation == 'dump_data_fields':
if len(self.input_files) != 1:
self.logger.error("L'operazione dump_data_fields richiede esattamente un file di input")
sys.exit(1)
self.operation_dump_data_fields(input_file, self.output_file)
elif self.operation == 'background':
if len(self.input_files) != 1 or not self.operation_args:
self.logger.error("L'operazione background richiede un file di input e un file di sfondo")
sys.exit(1)
self.operation_background(input_file, self.operation_args[0], self.output_file)
elif self.operation == 'fill_form':
if len(self.input_files) != 1 or not self.operation_args:
self.logger.error("L'operazione fill_form richiede un file di input e un file FDF")
sys.exit(1)
self.operation_fill_form(input_file, self.operation_args[0], self.output_file)
elif self.operation == 'attach_files':
if len(self.input_files) != 1 or not self.operation_args:
self.logger.error("L'operazione attach_files richiede un file di input e almeno un file da allegare")
sys.exit(1)
# Controlla se c'è l'opzione to_page
page_number = None
files_to_attach = []
i = 0
while i < len(self.operation_args):
if self.operation_args[i].lower() == 'to_page' and i + 1 < len(self.operation_args):
page_number = int(self.operation_args[i + 1])
i += 2
else:
files_to_attach.append(self.operation_args[i])
i += 1
self.operation_attach_files(input_file, files_to_attach, page_number)
elif self.operation == 'unpack_files':
if len(self.input_files) != 1:
self.logger.error("L'operazione unpack_files richiede esattamente un file di input")
sys.exit(1)
self.operation_unpack_files(input_file, self.output_file)
elif self.operation == 'update_info':
if len(self.input_files) != 1 or not self.operation_args:
self.logger.error("L'operazione update_info richiede un file di input e un file info")
sys.exit(1)
self.operation_update_info(input_file, self.operation_args[0])
elif not self.operation:
# Modalità filtro: processa un singolo PDF applicando solo le opzioni di output
if len(self.input_files) != 1:
self.logger.error("La modalità filtro richiede esattamente un file di input")
sys.exit(1)
reader = self.read_pdf_with_password(input_file, self.input_passwords.get(input_file))
writer = PdfWriter()
writer.append_pages_from_reader(reader)
if self.flatten:
writer.flatten_annotations()
self.apply_encryption(writer)
with open(self.output_file, 'wb') as out_file:
writer.write(out_file)
# Pulisci i file temporanei se necessario
if self.repair_mode and 'temp_file' in locals():
try:
os.remove(temp_file)
except:
pass
except Exception as e:
self.logger.error(f"Errore durante l'elaborazione: {str(e)}")
sys.exit(1)
def main():
tool = PdfTool()
if not tool.parse_arguments(sys.argv):
print("Utilizzo:")
print(" Unione PDF:")
print(" pdfmerger file1.pdf file2.pdf ... cat output output.pdf")
print(" pdfmerger A=file1.pdf B=file2.pdf cat A1-2 B3-end output output.pdf")
print("\n Divisione in pagine:")
print(" pdfmerger input.pdf burst [output pg_%04d.pdf]")
print("\n Estrazione metadati:")
print(" pdfmerger input.pdf dump_data [output metadata.txt]")
print("\n Applicazione sfondo:")
print(" pdfmerger input.pdf background background.pdf output output.pdf")
print("\n Compilazione form:")
print(" pdfmerger input.pdf fill_form data.fdf output output.pdf [flatten]")
print("\n Crittografia:")
print(" pdfmerger input.pdf output output.pdf encrypt_128bit owner_pw foo user_pw bar")
sys.exit(1)
tool.process()
if __name__ == '__main__':
main()