-
Notifications
You must be signed in to change notification settings - Fork 26
/
cpdfcommand.ml
5074 lines (4777 loc) · 188 KB
/
cpdfcommand.ml
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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(* cpdf command line tools *)
let demo = false
let agpl = true
let major_version = 2
let minor_version = 8
let minor_minor_version = 1
let version_date = "(devel, 19th December 2024)"
open Pdfutil
open Pdfio
let combine_with_spaces strs =
String.trim
(fold_left (fun x y -> x ^ (if x <> "" then " " else "") ^ y) "" strs)
let tempfiles = ref []
let exit n =
begin try iter Sys.remove !tempfiles with _ -> exit n end;
exit n
let null () = ()
let initial_file_size = ref 0
let empty = Pdf.empty ()
(* Wrap up the file reading functions to exit with code 1 when an encryption
problem occurs. This happens when object streams are in an encrypted document
and so it can't be read without the right password... The existing error
handling only dealt with the case where the document couldn't be decrypted once
it had been loaded. *)
let pdfread_pdf_of_input ?revision a b c =
try Pdfread.pdf_of_input ?revision a b c with
Pdf.PDFError s when String.length s >=10 && String.sub s 0 10 = "Encryption" ->
raise (Cpdferror.SoftError "Bad owner or user password when reading document")
let pdfread_pdf_of_channel_lazy ?revision ?source b c d =
try Pdfread.pdf_of_channel_lazy ?revision ?source b c d with
Pdf.PDFError s when String.length s >=10 && String.sub s 0 10 = "Encryption" ->
raise (Cpdferror.SoftError "Bad owner or user password when reading document")
let pdfread_pdf_of_file ?revision a b c =
try Pdfread.pdf_of_file ?revision a b c with
Pdf.PDFError s when String.length s >=10 && String.sub s 0 10 = "Encryption" ->
raise (Cpdferror.SoftError "Bad owner or user password when reading document")
let optstring = function
| "" -> None
| x -> Some x
let _ =
set_binary_mode_in stdin true;
set_binary_mode_out stdout true
let stay_on_error = ref false
exception StayOnError
(* Fatal error reporting. *)
let error s =
Pdfe.log (s ^ "\nUse -help for help.\n");
if not !stay_on_error then exit 2 else raise StayOnError
let soft_error s =
Pdfe.log (Printf.sprintf "%s\n" s);
if not !stay_on_error then exit 1 else raise StayOnError
let parse_pagespec pdf spec =
try Cpdfpagespec.parse_pagespec pdf spec with
Failure x -> error x
(* We allow an operation such as ScaleToFit on a range such as 'portrait' to be silently null to allow, for example:
cpdf -scale-to-fit a4portrait in.pdf portrait AND -scale-to-fit a4landscape landscape -o out.pdf
*)
let parse_pagespec_allow_empty pdf spec =
try Cpdfpagespec.parse_pagespec pdf spec with
Pdf.PDFError ("Page range specifies no pages") -> []
(* Operations. *)
type op =
| CopyFont of string
| CountPages
| Version
| Encrypt
| Decrypt
| StampOn of string
| StampUnder of string
| CombinePages of string
| TwoUp
| TwoUpStack
| Impose of bool
| RemoveBookmarks
| AddBookmarks of string
| AddText of string
| AddRectangle
| RemoveText
| Draft
| PadBefore
| PadAfter
| PadEvery of int
| PadMultiple of int
| PadMultipleBefore of int
| Shift
| ShiftBoxes
| Scale
| ScaleToFit
| Stretch
| CenterToFit
| ScaleContents of float
| AttachFile of string list
| RemoveAttachedFiles
| ListAttachedFiles
| DumpAttachedFiles
| RemoveAnnotations
| ListAnnotations
| CopyAnnotations of string
| SetAnnotations of string
| Merge
| Split
| SplitOnBookmarks of int
| SplitMax of int
| Spray
| Clean
| Info
| PageInfo
| Metadata
| SetMetadata of string
| RemoveMetadata
| Fonts
| RemoveFonts
| Compress
| Decompress
| Crop
| Trim
| Bleed
| Art
| RemoveCrop
| RemoveArt
| RemoveTrim
| RemoveBleed
| CopyBox
| MediaBox
| HardBox of string
| Rotate of int
| Rotateby of int
| RotateContents of float
| Upright
| VFlip
| HFlip
| ThinLines of float
| SetAuthor of string
| SetTitle of string
| SetSubject of string
| SetKeywords of string
| SetCreate of string
| SetModify of string
| SetCreator of string
| SetProducer of string
| SetTrapped
| SetUntrapped
| SetVersion of int
| ListBookmarks
| SetPageLayout of string
| SetPageMode of string
| SetNonFullScreenPageMode of string
| HideToolbar of bool
| HideMenubar of bool
| HideWindowUI of bool
| FitWindow of bool
| CenterWindow of bool
| DisplayDocTitle of bool
| Presentation
| ChangeId
| RemoveId
| CopyId of string
| BlackText
| BlackLines
| BlackFills
| ExtractImages
| ListImages
| ImageResolution of float
| MissingFonts
| ExtractFontFile of string
| ExtractText
| OpenAtPage of string
| OpenAtPageFit of string
| OpenAtPageCustom of string
| AddPageLabels
| RemovePageLabels
| PrintPageLabels
| RemoveDictEntry of string
| ReplaceDictEntry of string
| PrintDictEntry of string
| ListSpotColours
| RemoveClipping
| SetMetadataDate of string
| CreateMetadata
| EmbedMissingFonts
| BookmarksOpenToLevel of int
| CreatePDF
| RemoveAllText
| ShowBoxes
| TrimMarks
| Prepend of string
| Postpend of string
| OutputJSON
| OCGCoalesce
| OCGList
| OCGRename
| OCGOrderAll
| StampAsXObject of string
| PrintFontEncoding of string
| TableOfContents
| Typeset of string
| TextWidth of string
| Draw
| Composition of bool
| Chop of int * int
| ChopHV of bool * float
| ProcessImages
| ExtractStream of string
| ReplaceStream of string
| PrintObj of string
| ReplaceObj of string * string
| Verify of string
| MarkAs of Cpdfua.subformat
| RemoveMark of Cpdfua.subformat
| PrintStructTree
| ExtractStructTree
| ReplaceStructTree of string
| SetLanguage of string
| Redact
| Rasterize
| OutputImage
let string_of_op = function
| PrintFontEncoding _ -> "PrintFontEncoding"
| PrintDictEntry _ -> "PrintDictEntry"
| Impose _ -> "Impose"
| CopyFont _ -> "CopyFont"
| CountPages -> "CountPages"
| Version -> "Version"
| Encrypt -> "Encrypt"
| Decrypt -> "Decrypt"
| StampOn _ -> "StampOn"
| StampUnder _ -> "StampUnder"
| CombinePages _ -> "CombinePages"
| TwoUp -> "TwoUp"
| TwoUpStack -> "TwoUpStack"
| RemoveBookmarks -> "RemoveBookmarks"
| AddBookmarks _ -> "AddBookmarks"
| AddText _ -> "AddText"
| AddRectangle -> "AddRectangle"
| RemoveText -> "RemoveText"
| Draft -> "Draft"
| PadBefore -> "PadBefore"
| PadAfter -> "PadAfter"
| PadEvery _ -> "PadEvery"
| PadMultiple _ -> "PadMultiple"
| PadMultipleBefore _ -> "PadMultipleBefore"
| Shift -> "Shift"
| ShiftBoxes -> "ShiftBoxes"
| Scale -> "Scale"
| ScaleToFit -> "ScaleToFit"
| Stretch -> "Stretch"
| CenterToFit -> "CenterToFit"
| ScaleContents _ -> "ScaleContents"
| AttachFile _ -> "AttachFile"
| RemoveAttachedFiles -> "RemoveAttachedFiles"
| ListAttachedFiles -> "ListAttachedFiles"
| DumpAttachedFiles -> "DumpAttachedFiles"
| RemoveAnnotations -> "RemoveAnnotations"
| ListAnnotations -> "ListAnnotations"
| CopyAnnotations _ -> "CopyAnnotations"
| SetAnnotations _ -> "SetAnnotations"
| Merge -> "Merge"
| Split -> "Split"
| SplitOnBookmarks _ -> "SplitOnBookmarks"
| SplitMax _ -> "SplitMax"
| Spray -> "Spray"
| Clean -> "Clean"
| Info -> "Info"
| PageInfo -> "PageInfo"
| Metadata -> "Metadata"
| SetMetadata _ -> "SetMetadata"
| RemoveMetadata -> "RemoveMetadata"
| Fonts -> "Fonts"
| RemoveFonts -> "RemoveFonts"
| Compress -> "Compress"
| Decompress -> "Decompress"
| Crop -> "Crop"
| RemoveCrop -> "RemoveCrop"
| CopyBox -> "CopyBox"
| MediaBox -> "MediaBox"
| HardBox _ -> "HardBox"
| Rotate _ -> "Rotate"
| Rotateby _ -> "Rotateby"
| RotateContents _ -> "RotateContents"
| Upright -> "Upright"
| VFlip -> "VFlip"
| HFlip -> "HFlip"
| ThinLines _ -> "ThinLines"
| SetAuthor _ -> "SetAuthor"
| SetTitle _ -> "SetTitle"
| SetSubject _ -> "SetSubject"
| SetKeywords _ -> "SetKeywords"
| SetCreate _ -> "SetCreate"
| SetModify _ -> "SetModify"
| SetCreator _ -> "SetCreator"
| SetProducer _ -> "SetProducer"
| SetTrapped -> "SetTrapped"
| SetUntrapped -> "SetUntrapped"
| SetVersion _ -> "SetVersion"
| ListBookmarks -> "ListBookmarks"
| SetPageLayout _ -> "SetPageLayout"
| SetPageMode _ -> "SetPageMode"
| SetNonFullScreenPageMode _ -> "SetNonFullScreenPageMode"
| HideToolbar _ -> "HideToolbar"
| HideMenubar _ -> "HideMenubar"
| HideWindowUI _ -> "HideWindowUI"
| FitWindow _ -> "FitWindow"
| CenterWindow _ -> "CenterWindow"
| DisplayDocTitle _ -> "DisplayDocTitle"
| Presentation -> "Presentation"
| ChangeId -> "ChangeId"
| RemoveId -> "RemoveId"
| CopyId _ -> "CopyId"
| BlackText -> "BlackText"
| BlackLines -> "BlackLines"
| BlackFills -> "BlackFills"
| ExtractImages -> "ExtractImages"
| ListImages -> "ListImages"
| ImageResolution _ -> "ImageResolution"
| MissingFonts -> "MissingFonts"
| ExtractFontFile _ -> "ExtractFontFile"
| ExtractText -> "ExtractText"
| OpenAtPage _ -> "OpenAtPage"
| OpenAtPageFit _ -> "OpenAtPageFit"
| OpenAtPageCustom _ -> "OpenAtPageCustom"
| AddPageLabels -> "AddPageLabels"
| RemovePageLabels -> "RemovePageLabels"
| PrintPageLabels -> "PrintPageLabels"
| RemoveDictEntry _ -> "RemoveDictEntry"
| ReplaceDictEntry _ -> "ReplaceDictEntry"
| ListSpotColours -> "ListSpotColours"
| RemoveClipping -> "RemoveClipping"
| Trim -> "Trim"
| Art -> "Art"
| Bleed -> "Bleed"
| RemoveArt -> "RemoveArt"
| RemoveTrim -> "RemoveTrim"
| RemoveBleed -> "RemoveBleed"
| SetMetadataDate _ -> "SetMetadataDate"
| CreateMetadata -> "CreateMetadata"
| EmbedMissingFonts -> "EmbedMissingFonts"
| BookmarksOpenToLevel _ -> "BookmarksOpenToLevel"
| CreatePDF -> "CreatePDF"
| RemoveAllText -> "RemoveAllText"
| ShowBoxes -> "ShowBoxes"
| TrimMarks -> "TrimMarks"
| Prepend _ -> "Prepend"
| Postpend _ -> "Postpend"
| OutputJSON -> "OutputJSON"
| OCGCoalesce -> "OCGCoalesce"
| OCGList -> "OCGList"
| OCGRename -> "OCGRename"
| OCGOrderAll -> "OCGOrderAll"
| StampAsXObject _ -> "StampAsXObject"
| TableOfContents -> "TableOfContents"
| Typeset _ -> "Typeset"
| TextWidth _ -> "TextWidth"
| Draw -> "Draw"
| Composition _ -> "Composition"
| Chop _ -> "Chop"
| ChopHV _ -> "ChopHV"
| ProcessImages -> "ProcessImages"
| ExtractStream _ -> "ExtractStream"
| ReplaceStream _ -> "ReplaceStream"
| PrintObj _ -> "PrintObj"
| ReplaceObj _ -> "ReplaceObj"
| Verify _ -> "Verify"
| MarkAs _ -> "MarkAs"
| RemoveMark _ -> "RemoveMark"
| PrintStructTree -> "PrintStructTree"
| ExtractStructTree -> "ExtractStructTree"
| ReplaceStructTree _ -> "ReplaceStructTree"
| SetLanguage _ -> "SetLanguage"
| Redact -> "Redact"
| Rasterize -> "Rasterize"
| OutputImage -> "OutputImage"
(* Inputs: filename, pagespec. *)
type input_kind =
| AlreadyInMemory of Pdf.t * string
| InFile of string
| StdIn
let string_of_input_kind = function
| AlreadyInMemory (_, s) -> s
| InFile s -> s
| StdIn -> "Stdin"
type input =
input_kind * string * string * string * bool ref * int option
(* input kind, range, user_pw, owner_pw, was_decrypted_with_owner, revision *)
type output_method =
| NoOutputSpecified
| Stdout
| File of string
(* Outputs are also added here, in case -spray is in use. *)
let spray_outputs = ref []
(* A list of PDFs to be output, if no output method was specified. *)
let output_pdfs : Pdf.t list ref = ref []
let standard_namespace = "http://iso.org/pdf/ssn"
let pdf2_namespace = "http://iso.org/pdf2/ssn"
type font =
| StandardFont of Pdftext.standard_font
| EmbeddedFont of string
| OtherFont of string
type args =
{mutable op : op option;
mutable preserve_objstm : bool;
mutable create_objstm : bool;
mutable out : output_method;
mutable inputs : input list;
mutable chunksize : int;
mutable linearize : bool;
mutable keeplinearize : bool;
mutable rectangle : string;
mutable coord : string;
mutable duration : float option;
mutable transition : string option;
mutable horizontal : bool;
mutable inward : bool;
mutable direction : int;
mutable effect_duration : float;
mutable font : font;
mutable fontname : string;
mutable fontencoding : Pdftext.encoding;
mutable fontsize : float;
mutable embedstd14 : string option;
mutable color : Cpdfaddtext.colour;
mutable opacity : float;
mutable position : Cpdfposition.position;
mutable underneath : bool;
mutable linespacing : float;
mutable midline : bool;
mutable topline : bool;
mutable justification : Cpdfaddtext.justification;
mutable bates : int;
mutable batespad : int option;
mutable prerotate : bool;
mutable relative_to_cropbox : bool;
mutable keepversion : bool;
mutable bycolumns : bool;
mutable pagerotation : int;
mutable crypt_method : string;
mutable owner : string;
mutable user : string;
mutable no_edit : bool;
mutable no_print : bool;
mutable no_copy : bool;
mutable no_annot : bool;
mutable no_forms : bool;
mutable no_extract : bool;
mutable no_assemble : bool;
mutable no_hq_print : bool;
mutable debug : bool;
mutable debugcrypt : bool;
mutable debugforce : bool;
mutable boxes : bool;
mutable encrypt_metadata : bool;
mutable retain_numbering : bool;
mutable process_struct_trees : bool;
mutable remove_duplicate_fonts : bool;
mutable remove_duplicate_streams : bool;
mutable encoding : Cpdfmetadata.encoding;
mutable scale : float;
mutable copyfontpage : int;
mutable copyfontname : string option;
mutable fast : bool;
mutable dashrange : string;
mutable outline : bool;
mutable linewidth : float;
mutable path_to_ghostscript : string;
mutable path_to_im : string;
mutable path_to_p2p : string;
mutable path_to_jbig2enc : string;
mutable frombox : string option;
mutable tobox : string option;
mutable mediabox_if_missing : bool;
mutable topage : string option;
mutable scale_stamp_to_fit : bool;
mutable labelstyle : Pdfpagelabels.labelstyle;
mutable labelprefix : string option;
mutable labelstartval : int;
mutable labelsprogress : bool;
mutable squeeze : bool;
mutable squeeze_recompress : bool;
mutable squeeze_pagedata: bool;
mutable original_filename : string;
mutable was_encrypted : bool;
mutable cpdflin : string option;
mutable recrypt : bool;
mutable was_decrypted_with_owner : bool;
mutable creator : string option;
mutable producer : string option;
mutable extract_text_font_size : float option;
mutable padwith : string option;
mutable alsosetxml : bool;
mutable justsetxml : bool;
mutable gs_malformed : bool;
mutable gs_quiet : bool;
mutable merge_add_bookmarks : bool;
mutable merge_add_bookmarks_use_titles : bool;
mutable createpdf_pages : int;
mutable createpdf_pagesize : Pdfpaper.t;
mutable removeonly : string option;
mutable jsonparsecontentstreams : bool;
mutable jsonnostreamdata : bool;
mutable jsondecompressstreams : bool;
mutable jsoncleanstrings : bool;
mutable ocgrenamefrom : string;
mutable ocgrenameto : string;
mutable dedup : bool;
mutable dedup_per_page : bool;
mutable collate : int;
mutable impose_columns : bool;
mutable impose_rtl : bool;
mutable impose_btt : bool;
mutable impose_center : bool;
mutable impose_margin : float;
mutable impose_spacing : float;
mutable impose_linewidth : float;
mutable format_json : bool;
mutable replace_dict_entry_value : Pdf.pdfobject;
mutable dict_entry_search : Pdf.pdfobject option;
mutable toc_title : string;
mutable toc_bookmark : bool;
mutable idir_only_pdfs : bool;
mutable no_warn_rotate : bool;
mutable jpegquality : float;
mutable jpegqualitylossless : float;
mutable jpegtojpegscale : float;
mutable jpegtojpegdpi : float;
mutable onebppmethod : string;
mutable pixel_threshold : int;
mutable length_threshold : int;
mutable percentage_threshold : float;
mutable dpi_threshold : float;
mutable resample_factor : float;
mutable resample_interpolate : bool;
mutable jbig2_lossy_threshold : float;
mutable extract_stream_decompress : bool;
mutable verify_single : string option;
mutable draw_struct_tree : bool;
mutable subformat : Cpdfua.subformat option;
mutable indent : float option;
mutable title : string option;
mutable rast_device : string;
mutable rast_res : float;
mutable rast_annots : bool;
mutable rast_antialias : bool;
mutable rast_jpeg_quality : int;
mutable rast_downsample : bool;
mutable replace_stream_with : string;
mutable output_unit : Pdfunits.t;
mutable dot_leader : bool}
let args =
{op = None;
preserve_objstm = true;
create_objstm = false;
out = NoOutputSpecified;
inputs = [];
chunksize = 1;
linearize = false;
keeplinearize = false;
rectangle = "0 0 0 0";
coord = "0 0";
duration = None;
transition = None;
horizontal = true;
inward = true;
direction = 0;
effect_duration = 1.;
font = StandardFont Pdftext.TimesRoman;
fontname = "Times-Roman";
fontsize = 12.;
fontencoding = Pdftext.WinAnsiEncoding;
color = Cpdfaddtext.RGB (0., 0., 0.);
opacity = 1.;
position = Cpdfposition.TopLeft (100., 100.);
underneath = false;
linespacing = 1.;
midline = false;
topline = false;
justification = Cpdfaddtext.LeftJustify;
bates = 0;
batespad = None;
prerotate = false;
relative_to_cropbox = false;
keepversion = false;
bycolumns = false;
pagerotation = 0;
crypt_method = "";
owner = "";
user = "";
no_edit = false;
no_print = false;
no_copy = false;
no_annot = false;
no_forms = false;
no_extract = false;
no_assemble = false;
no_hq_print = false;
debug = false;
debugcrypt = false;
debugforce = false;
boxes = false;
encrypt_metadata = true;
retain_numbering = false;
process_struct_trees = false;
remove_duplicate_fonts = false;
remove_duplicate_streams = false;
encoding = Cpdfmetadata.Stripped;
scale = 1.;
copyfontpage = 1;
copyfontname = None;
fast = false;
dashrange = "all";
outline = false;
linewidth = 1.0;
path_to_ghostscript = "";
path_to_im = "";
path_to_p2p = "";
path_to_jbig2enc = "";
frombox = None;
tobox = None;
mediabox_if_missing = false;
topage = None;
scale_stamp_to_fit = false;
labelstyle = Pdfpagelabels.DecimalArabic;
labelprefix = None;
labelstartval = 1;
labelsprogress = false;
squeeze = false;
squeeze_recompress = true;
squeeze_pagedata = true;
original_filename = "";
was_encrypted = false;
cpdflin = None;
recrypt = false;
was_decrypted_with_owner = false;
producer = None;
creator = None;
embedstd14 = None;
extract_text_font_size = None;
padwith = None;
alsosetxml = false;
justsetxml = false;
gs_malformed = false;
gs_quiet = false;
merge_add_bookmarks = false;
merge_add_bookmarks_use_titles = false;
createpdf_pages = 1;
createpdf_pagesize = Pdfpaper.a4;
removeonly = None;
jsonparsecontentstreams = false;
jsonnostreamdata = false;
jsondecompressstreams = false;
jsoncleanstrings = false;
ocgrenamefrom = "";
ocgrenameto = "";
dedup = false;
dedup_per_page = false;
collate = 0;
impose_columns = false;
impose_rtl = false;
impose_btt = false;
impose_center = false;
impose_margin = 0.;
impose_spacing = 0.;
impose_linewidth = 0.;
format_json = false;
replace_dict_entry_value = Pdf.Null;
dict_entry_search = None;
toc_title = "Table of Contents";
toc_bookmark = true;
idir_only_pdfs = false;
no_warn_rotate = false;
jpegquality = 100.;
jpegqualitylossless = 101.;
jpegtojpegscale = 100.;
jpegtojpegdpi = 0.;
onebppmethod = "";
pixel_threshold = 25;
length_threshold = 100;
percentage_threshold = 99.;
dpi_threshold = 0.;
resample_factor = 101.;
resample_interpolate = false;
jbig2_lossy_threshold = 0.85;
extract_stream_decompress = false;
verify_single = None;
draw_struct_tree = false;
subformat = None;
indent = None;
title = None;
rast_device = "png16m";
rast_res = 144.;
rast_annots = false;
rast_antialias = true;
rast_jpeg_quality = 75;
rast_downsample = false;
replace_stream_with = "";
output_unit = Pdfunits.PdfPoint;
dot_leader = false}
(* Do not reset original_filename or cpdflin or was_encrypted or
was_decrypted_with_owner or recrypt or producer or creator or path_to_* or
gs_malformed or gs_quiet or no-warn-rotate, since we want these to work
across ANDs. Or squeeze options: a little odd, but we want it to happen on
eventual output. Or -debug-force (from v2.6). *)
let reset_arguments () =
args.op <- None;
args.preserve_objstm <- true;
args.create_objstm <- false;
args.out <- NoOutputSpecified;
args.inputs <- [];
args.chunksize <- 1;
args.linearize <- false;
args.keeplinearize <- false;
args.rectangle <- "0 0 0 0";
args.coord <- "0 0";
args.duration <- None;
args.transition <- None;
args.horizontal <- true;
args.inward <- true;
args.direction <- 0;
args.effect_duration <- 1.;
args.font <- StandardFont Pdftext.TimesRoman;
args.fontname <- "Times-Roman";
args.fontsize <- 12.;
args.fontencoding <- Pdftext.WinAnsiEncoding;
args.color <- Cpdfaddtext.RGB (0., 0., 0.);
args.opacity <- 1.;
args.position <- Cpdfposition.TopLeft (100., 100.);
args.underneath <- false;
args.linespacing <- 1.;
args.midline <- false;
args.topline <- false;
args.justification <- Cpdfaddtext.LeftJustify;
args.bates <- 0;
args.batespad <- None;
args.prerotate <- false;
args.relative_to_cropbox <- false;
args.keepversion <- false;
args.bycolumns <- false;
args.pagerotation <- 0;
args.crypt_method <- "";
args.owner <- "";
args.user <- "";
args.no_edit <- false;
args.no_print <- false;
args.no_copy <- false;
args.no_annot <- false;
args.no_forms <- false;
args.no_extract <- false;
args.no_assemble <- false;
args.no_hq_print <- false;
args.debug <- false;
args.debugcrypt <- false;
args.boxes <- false;
args.encrypt_metadata <- true;
args.retain_numbering <- false;
args.process_struct_trees <- false;
args.remove_duplicate_fonts <- false;
args.remove_duplicate_streams <- false;
args.encoding <- Cpdfmetadata.Stripped;
args.scale <- 1.;
args.copyfontpage <- 1;
args.copyfontname <- None;
args.fast <- false;
args.dashrange <- "all";
args.outline <- false;
args.linewidth <- 1.0;
args.frombox <- None;
args.tobox <- None;
args.mediabox_if_missing <- false;
args.topage <- None;
args.scale_stamp_to_fit <- false;
args.labelstyle <- Pdfpagelabels.DecimalArabic;
args.labelprefix <- None;
args.labelstartval <- 1;
args.labelsprogress <- false;
args.embedstd14 <- None;
args.extract_text_font_size <- None;
args.padwith <- None;
args.alsosetxml <- false;
args.justsetxml <- false;
args.merge_add_bookmarks <- false;
args.merge_add_bookmarks_use_titles <- false;
args.createpdf_pages <- 1;
args.createpdf_pagesize <- Pdfpaper.a4;
args.removeonly <- None;
args.jsonparsecontentstreams <- false;
args.jsonnostreamdata <- false;
args.jsondecompressstreams <- false;
args.jsoncleanstrings <- false;
args.ocgrenamefrom <- "";
args.ocgrenameto <- "";
args.dedup <- false;
args.dedup_per_page <- false;
args.collate <- 0;
args.impose_columns <- false;
args.impose_rtl <- false;
args.impose_btt <- false;
args.impose_center <- false;
args.impose_margin <- 0.;
args.impose_spacing <- 0.;
args.impose_linewidth <- 0.;
args.format_json <- false;
args.replace_dict_entry_value <- Pdf.Null;
args.dict_entry_search <- None;
args.toc_title <- "Table of Contents";
args.toc_bookmark <- true;
args.idir_only_pdfs <- false;
args.jpegquality <- 100.;
args.jpegqualitylossless <- 101.;
args.onebppmethod <- "";
args.pixel_threshold <- 25;
args.length_threshold <- 100;
args.percentage_threshold <- 99.;
args.dpi_threshold <- 0.;
args.resample_factor <- 101.;
args.resample_interpolate <- false;
args.jbig2_lossy_threshold <- 0.85;
args.extract_stream_decompress <- false;
clear Cpdfdrawcontrol.fontpack_initialised;
args.verify_single <- None;
args.draw_struct_tree <- false;
args.subformat <- None;
args.indent <- None;
args.title <- None;
args.rast_device <- "png16m";
args.rast_res <- 144.;
args.rast_annots <- false;
args.rast_antialias <- true;
args.rast_jpeg_quality <- 75;
args.rast_downsample <- false;
args.replace_stream_with <- "";
args.output_unit <- Pdfunits.PdfPoint;
args.dot_leader <- false
(* Prefer a) the one given with -cpdflin b) a local cpdflin, c) otherwise assume
installed at a system place *)
let find_cpdflin provided =
match provided with
Some x -> x
| None ->
let dotslash = match Sys.os_type with "Win32" -> "" | _ -> "./" in
if Sys.file_exists "cpdflin" then (dotslash ^ "cpdflin") else
if Sys.file_exists "cpdflin.exe" then (dotslash ^ "cpdflin.exe") else
match Sys.os_type with
"Win32" -> "cpdflin.exe"
| _ -> "cpdflin"
(* Call cpdflin, given the (temp) input name, the output name, and the location
of the cpdflin binary. Returns the exit code. *)
let call_cpdflin cpdflin temp output best_password =
let command =
Filename.quote_command cpdflin
["--linearize"; ("--password=" ^ best_password); temp; output]
in
match Sys.os_type with
"Win32" ->
(* On windows, don't use LD_LIBRARY_PATH - it will happen automatically *)
if args.debug then Pdfe.log (command ^ "\n");
Sys.command command
| _ ->
(* On other platforms, if -cpdflin was provided, or cpdflin was in the
current folder, set up LD_LIBRARY_PATH: *)
match cpdflin with
"cpdflin" ->
if args.debug then Pdfe.log (command ^ "\n");
Sys.command command
| _ ->
let command =
"DYLD_FALLBACK_LIBRARY_PATH=" ^ Filename.quote (Filename.dirname cpdflin) ^ " " ^
"LD_LIBRARY_PATH=" ^ Filename.quote (Filename.dirname cpdflin) ^ " " ^
command
in
if args.debug then Pdfe.log (command ^ "\n");
Sys.command command
let get_pagespec () =
match args.inputs with
| (_, ps, _, _, _, _)::_ -> ps
| _ -> error "No range specified for input, or specified too late."
let string_of_permission = function
| Pdfcrypt.NoEdit -> "No edit"
| Pdfcrypt.NoPrint -> "No print"
| Pdfcrypt.NoCopy -> "No copy"
| Pdfcrypt.NoAnnot -> "No annotate"
| Pdfcrypt.NoForms -> "No edit forms"
| Pdfcrypt.NoExtract -> "No extract"
| Pdfcrypt.NoAssemble -> "No assemble"
| Pdfcrypt.NoHqPrint -> "No high-quality print"
let getpermissions pdf =
fold_left
(fun x y -> if x = "" then x ^ y else x ^ ", " ^ y)
""
(map string_of_permission (Pdfread.permissions pdf))
let banlist_of_args () =
let l = ref [] in
if args.no_edit then l =| Pdfcrypt.NoEdit;
if args.no_print then l =| Pdfcrypt.NoPrint;
if args.no_copy then l =| Pdfcrypt.NoCopy;
if args.no_annot then l =| Pdfcrypt.NoAnnot;
if args.no_forms then l =| Pdfcrypt.NoForms;
if args.no_extract then l =| Pdfcrypt.NoExtract;
if args.no_assemble then l =| Pdfcrypt.NoAssemble;
if args.no_hq_print then l =| Pdfcrypt.NoHqPrint;
!l
(* If a file is encrypted, decrypt it using the owner password or, if not
present, the user password. If the user password is used, the operation to be
performed is checked to see if it's allowable under the permissions regime. *)
(* The bans. Each function has a list of bans. If any of these is present in the
bans list in the input file, the operation cannot proceed. Other operations
cannot proceed at all without owner password. *)
let banned banlist = function
| Fonts | Info | Metadata | PageInfo | CountPages
| ListAttachedFiles | ListAnnotations
| ListBookmarks | ImageResolution _ | ListImages | MissingFonts
| PrintPageLabels | Clean | Compress | Decompress
| ChangeId | CopyId _ | ListSpotColours | Version
| DumpAttachedFiles | RemoveMetadata | EmbedMissingFonts | BookmarksOpenToLevel _ | CreatePDF
| SetPageMode _ | SetNonFullScreenPageMode _ | HideToolbar _ | HideMenubar _ | HideWindowUI _
| FitWindow _ | CenterWindow _ | DisplayDocTitle _
| RemoveId | OpenAtPageFit _ | OpenAtPage _ | OpenAtPageCustom _ | SetPageLayout _
| ShowBoxes | TrimMarks | CreateMetadata | SetMetadataDate _ | SetVersion _
| SetAuthor _|SetTitle _|SetSubject _|SetKeywords _|SetCreate _
| SetModify _|SetCreator _|SetProducer _|RemoveDictEntry _ | ReplaceDictEntry _ | PrintDictEntry _ | SetMetadata _
| ExtractText | ExtractImages | ExtractFontFile _
| AddPageLabels | RemovePageLabels | OutputJSON | OCGCoalesce
| OCGRename | OCGList | OCGOrderAll | PrintFontEncoding _ | TableOfContents | Typeset _ | Composition _
| TextWidth _ | SetAnnotations _ | CopyAnnotations _ | ExtractStream _ | ReplaceStream _ | PrintObj _ | ReplaceObj _
| Verify _ | MarkAs _ | RemoveMark _ | ExtractStructTree | ReplaceStructTree _ | SetLanguage _
| PrintStructTree | Rasterize | OutputImage
-> false (* Always allowed *)
(* Combine pages is not allowed because we would not know where to get the
-recrypt from -- the first or second file? *)
| Decrypt | Encrypt | CombinePages _ -> true (* Never allowed *)
| AddBookmarks _ | PadBefore | PadAfter | PadEvery _ | PadMultiple _ | PadMultipleBefore _
| Merge | Split | SplitOnBookmarks _ | SplitMax _ | Spray | RotateContents _ | Rotate _
| Rotateby _ | Upright | VFlip | HFlip | Impose _ | Chop _ | ChopHV _ | Redact ->
mem Pdfcrypt.NoAssemble banlist
| TwoUp | TwoUpStack | RemoveBookmarks | AddRectangle | RemoveText|
Draft | Shift | ShiftBoxes | Scale | ScaleToFit|Stretch|CenterToFit|RemoveAttachedFiles|
RemoveAnnotations|RemoveFonts|Crop|RemoveCrop|Trim|RemoveTrim|Bleed|RemoveBleed|Art|RemoveArt|
CopyBox|MediaBox|HardBox _|SetTrapped|SetUntrapped|Presentation|
BlackText|BlackLines|BlackFills|CopyFont _|StampOn _|StampUnder _|StampAsXObject _|
AddText _|ScaleContents _|AttachFile _| ThinLines _ | RemoveClipping | RemoveAllText
| Prepend _ | Postpend _ | Draw | ProcessImages ->
mem Pdfcrypt.NoEdit banlist
let operation_allowed pdf banlist op =
args.debugforce ||
match op with
| None ->
if args.debugcrypt then Printf.printf "operation is None, so allowed!\n";
true (* Merge *) (* changed to allow it *)
| Some op ->
if args.debugcrypt then Printf.printf "operation_allowed: op = %s\n" (string_of_op op);
if args.debugcrypt then Printf.printf "Permissions: %s\n" (getpermissions pdf);
not (banned banlist op)
let decrypt_if_necessary (_, _, user_pw, owner_pw, was_dec_with_owner, _) op pdf =
if args.debugcrypt then
begin match op with
None -> flprint "decrypt_if_necessary: op = None\n"
| Some x -> Printf.printf "decrypt_if_necessary: op = %s\n" (string_of_op x)
end;
if not (Pdfcrypt.is_encrypted pdf) then pdf else
match op with Some (CombinePages _) ->
(* This is a hack because we don't have support for recryption on combine
* pages. This is prevented by permissions above, but in the case that the