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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
|
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <ctype.h>
#include <qpdf/QUtil.hh>
#include <qpdf/QTC.hh>
#include <qpdf/ClosedFileInputSource.hh>
#include <qpdf/FileInputSource.hh>
#include <qpdf/Pl_StdioFile.hh>
#include <qpdf/Pl_Discard.hh>
#include <qpdf/Pl_DCT.hh>
#include <qpdf/Pl_Count.hh>
#include <qpdf/PointerHolder.hh>
#include <qpdf/QPDF.hh>
#include <qpdf/QPDFPageDocumentHelper.hh>
#include <qpdf/QPDFPageObjectHelper.hh>
#include <qpdf/QPDFPageLabelDocumentHelper.hh>
#include <qpdf/QPDFOutlineDocumentHelper.hh>
#include <qpdf/QPDFAcroFormDocumentHelper.hh>
#include <qpdf/QPDFExc.hh>
#include <qpdf/QPDFWriter.hh>
static int const EXIT_ERROR = 2;
static int const EXIT_WARNING = 3;
static char const* whoami = 0;
static std::string expected_version = "8.4.2";
struct PageSpec
{
PageSpec(std::string const& filename,
char const* password,
char const* range) :
filename(filename),
password(password),
range(range)
{
}
std::string filename;
char const* password;
char const* range;
};
struct RotationSpec
{
RotationSpec(int angle = 0, bool relative = false) :
angle(angle),
relative(relative)
{
}
int angle;
bool relative;
};
enum password_mode_e { pm_bytes, pm_hex_bytes, pm_unicode, pm_auto };
struct UnderOverlay
{
UnderOverlay(char const* which) :
which(which),
filename(0),
password(0),
to_nr("1-z"),
from_nr("1-z"),
repeat_nr("")
{
}
std::string which;
char const* filename;
char const* password;
char const* to_nr;
char const* from_nr;
char const* repeat_nr;
PointerHolder<QPDF> pdf;
std::vector<int> to_pagenos;
std::vector<int> from_pagenos;
std::vector<int> repeat_pagenos;
};
struct Options
{
Options() :
password(0),
linearize(false),
decrypt(false),
split_pages(0),
verbose(false),
progress(false),
suppress_warnings(false),
copy_encryption(false),
encryption_file(0),
encryption_file_password(0),
encrypt(false),
password_is_hex_key(false),
suppress_password_recovery(false),
password_mode(pm_auto),
keylen(0),
r2_print(true),
r2_modify(true),
r2_extract(true),
r2_annotate(true),
r3_accessibility(true),
r3_extract(true),
r3_assemble(true),
r3_annotate_and_form(true),
r3_form_filling(true),
r3_modify_other(true),
r3_print(qpdf_r3p_full),
force_V4(false),
force_R5(false),
cleartext_metadata(false),
use_aes(false),
stream_data_set(false),
stream_data_mode(qpdf_s_compress),
compress_streams(true),
compress_streams_set(false),
decode_level(qpdf_dl_generalized),
decode_level_set(false),
normalize_set(false),
normalize(false),
suppress_recovery(false),
object_stream_set(false),
object_stream_mode(qpdf_o_preserve),
ignore_xref_streams(false),
qdf_mode(false),
preserve_unreferenced_objects(false),
preserve_unreferenced_page_resources(false),
keep_files_open(true),
keep_files_open_set(false),
keep_files_open_threshold(200), // default known in help and docs
newline_before_endstream(false),
coalesce_contents(false),
flatten_annotations(false),
flatten_annotations_required(0),
flatten_annotations_forbidden(an_invisible | an_hidden),
generate_appearances(false),
show_npages(false),
deterministic_id(false),
static_id(false),
static_aes_iv(false),
suppress_original_object_id(false),
show_encryption(false),
show_encryption_key(false),
check_linearization(false),
show_linearization(false),
show_xref(false),
show_trailer(false),
show_obj(0),
show_gen(0),
show_raw_stream_data(false),
show_filtered_stream_data(false),
show_pages(false),
show_page_images(false),
collate(false),
json(false),
check(false),
optimize_images(false),
externalize_inline_images(false),
keep_inline_images(false),
remove_page_labels(false),
oi_min_width(128), // Default values for these
oi_min_height(128), // oi flags are in --help
oi_min_area(16384), // and in the manual.
ii_min_bytes(1024), //
underlay("underlay"),
overlay("overlay"),
under_overlay(0),
require_outfile(true),
infilename(0),
outfilename(0)
{
}
char const* password;
bool linearize;
bool decrypt;
int split_pages;
bool verbose;
bool progress;
bool suppress_warnings;
bool copy_encryption;
char const* encryption_file;
char const* encryption_file_password;
bool encrypt;
bool password_is_hex_key;
bool suppress_password_recovery;
password_mode_e password_mode;
std::string user_password;
std::string owner_password;
int keylen;
bool r2_print;
bool r2_modify;
bool r2_extract;
bool r2_annotate;
bool r3_accessibility;
bool r3_extract;
bool r3_assemble;
bool r3_annotate_and_form;
bool r3_form_filling;
bool r3_modify_other;
qpdf_r3_print_e r3_print;
bool force_V4;
bool force_R5;
bool cleartext_metadata;
bool use_aes;
bool stream_data_set;
qpdf_stream_data_e stream_data_mode;
bool compress_streams;
bool compress_streams_set;
qpdf_stream_decode_level_e decode_level;
bool decode_level_set;
bool normalize_set;
bool normalize;
bool suppress_recovery;
bool object_stream_set;
qpdf_object_stream_e object_stream_mode;
bool ignore_xref_streams;
bool qdf_mode;
bool preserve_unreferenced_objects;
bool preserve_unreferenced_page_resources;
bool keep_files_open;
bool keep_files_open_set;
size_t keep_files_open_threshold;
bool newline_before_endstream;
std::string linearize_pass1;
bool coalesce_contents;
bool flatten_annotations;
int flatten_annotations_required;
int flatten_annotations_forbidden;
bool generate_appearances;
std::string min_version;
std::string force_version;
bool show_npages;
bool deterministic_id;
bool static_id;
bool static_aes_iv;
bool suppress_original_object_id;
bool show_encryption;
bool show_encryption_key;
bool check_linearization;
bool show_linearization;
bool show_xref;
bool show_trailer;
int show_obj;
int show_gen;
bool show_raw_stream_data;
bool show_filtered_stream_data;
bool show_pages;
bool show_page_images;
bool collate;
bool json;
std::set<std::string> json_keys;
std::set<std::string> json_objects;
bool check;
bool optimize_images;
bool externalize_inline_images;
bool keep_inline_images;
bool remove_page_labels;
size_t oi_min_width;
size_t oi_min_height;
size_t oi_min_area;
size_t ii_min_bytes;
UnderOverlay underlay;
UnderOverlay overlay;
UnderOverlay* under_overlay;
std::vector<PageSpec> page_specs;
std::map<std::string, RotationSpec> rotations;
bool require_outfile;
char const* infilename;
char const* outfilename;
};
struct QPDFPageData
{
QPDFPageData(std::string const& filename, QPDF* qpdf, char const* range);
QPDFPageData(QPDFPageData const& other, int page);
std::string filename;
QPDF* qpdf;
std::vector<QPDFObjectHandle> orig_pages;
std::vector<int> selected_pages;
};
class DiscardContents: public QPDFObjectHandle::ParserCallbacks
{
public:
virtual ~DiscardContents() {}
virtual void handleObject(QPDFObjectHandle) {}
virtual void handleEOF() {}
};
class ProgressReporter: public QPDFWriter::ProgressReporter
{
public:
ProgressReporter(char const* filename) :
filename(filename)
{
}
virtual ~ProgressReporter()
{
}
virtual void reportProgress(int);
private:
std::string filename;
};
void
ProgressReporter::reportProgress(int percentage)
{
std::cout << whoami << ": " << filename << ": write progress: "
<< percentage << "%" << std::endl;
}
static JSON json_schema(std::set<std::string>* keys = 0)
{
// Style: use all lower-case keys with no dashes or underscores.
// Choose array or dictionary based on indexing. For example, we
// use a dictionary for objects because we want to index by object
// ID and an array for pages because we want to index by position.
// The pages in the pages array contain references back to the
// original object, which can be resolved in the objects
// dictionary. When a PDF construct that maps back to an original
// object is represented separately, use "object" as the key that
// references the original object.
// This JSON object doubles as a schema and as documentation for
// our JSON output. Any schema mismatch is a bug in qpdf. This
// helps to enforce our policy of consistently providing a known
// structure where every documented key will always be present,
// which makes it easier to consume our JSON. This is discussed in
// more depth in the manual.
JSON schema = JSON::makeDictionary();
schema.addDictionaryMember(
"version", JSON::makeString(
"JSON format serial number; increased for non-compatible changes"));
JSON j_params = schema.addDictionaryMember(
"parameters", JSON::makeDictionary());
j_params.addDictionaryMember(
"decodelevel", JSON::makeString(
"decode level used to determine stream filterability"));
bool all_keys = ((keys == 0) || keys->empty());
// The list of selectable top-level keys id duplicated in three
// places: json_schema, do_json, and initOptionTable.
if (all_keys || keys->count("objects"))
{
schema.addDictionaryMember(
"objects", JSON::makeString(
"dictionary of original objects;"
" keys are 'trailer' or 'n n R'"));
}
if (all_keys || keys->count("pages"))
{
JSON page = schema.addDictionaryMember("pages", JSON::makeArray()).
addArrayElement(JSON::makeDictionary());
page.addDictionaryMember(
"object",
JSON::makeString("reference to original page object"));
JSON image = page.addDictionaryMember("images", JSON::makeArray()).
addArrayElement(JSON::makeDictionary());
image.addDictionaryMember(
"name",
JSON::makeString("name of image in XObject table"));
image.addDictionaryMember(
"object",
JSON::makeString("reference to image stream"));
image.addDictionaryMember(
"width",
JSON::makeString("image width"));
image.addDictionaryMember(
"height",
JSON::makeString("image height"));
image.addDictionaryMember(
"colorspace",
JSON::makeString("color space"));
image.addDictionaryMember(
"bitspercomponent",
JSON::makeString("bits per component"));
image.addDictionaryMember("filter", JSON::makeArray()).
addArrayElement(
JSON::makeString("filters applied to image data"));
image.addDictionaryMember("decodeparms", JSON::makeArray()).
addArrayElement(
JSON::makeString("decode parameters for image data"));
image.addDictionaryMember(
"filterable",
JSON::makeString("whether image data can be decoded"
" using the decode level qpdf was invoked with"));
page.addDictionaryMember("contents", JSON::makeArray()).
addArrayElement(
JSON::makeString("reference to each content stream"));
page.addDictionaryMember(
"label",
JSON::makeString("page label dictionary, or null if none"));
JSON outline = page.addDictionaryMember("outlines", JSON::makeArray()).
addArrayElement(JSON::makeDictionary());
outline.addDictionaryMember(
"object",
JSON::makeString("reference to outline that targets this page"));
outline.addDictionaryMember(
"title",
JSON::makeString("outline title"));
outline.addDictionaryMember(
"dest",
JSON::makeString("outline destination dictionary"));
page.addDictionaryMember(
"pageposfrom1",
JSON::makeString("position of page in document numbering from 1"));
}
if (all_keys || keys->count("pagelabels"))
{
JSON labels = schema.addDictionaryMember(
"pagelabels", JSON::makeArray()).
addArrayElement(JSON::makeDictionary());
labels.addDictionaryMember(
"index",
JSON::makeString("starting page position starting from zero"));
labels.addDictionaryMember(
"label",
JSON::makeString("page label dictionary"));
}
if (all_keys || keys->count("outlines"))
{
JSON outlines = schema.addDictionaryMember(
"outlines", JSON::makeArray()).
addArrayElement(JSON::makeDictionary());
outlines.addDictionaryMember(
"object",
JSON::makeString("reference to this outline"));
outlines.addDictionaryMember(
"title",
JSON::makeString("outline title"));
outlines.addDictionaryMember(
"dest",
JSON::makeString("outline destination dictionary"));
outlines.addDictionaryMember(
"kids",
JSON::makeString("array of descendent outlines"));
outlines.addDictionaryMember(
"open",
JSON::makeString("whether the outline is displayed expanded"));
outlines.addDictionaryMember(
"destpageposfrom1",
JSON::makeString("position of destination page in document"
" numbered from 1; null if not known"));
}
if (all_keys || keys->count("acroform"))
{
JSON acroform = schema.addDictionaryMember(
"acroform", JSON::makeDictionary());
acroform.addDictionaryMember(
"hasacroform",
JSON::makeString("whether the document has interactive forms"));
acroform.addDictionaryMember(
"needappearances",
JSON::makeString("whether the form fields' appearance"
" streams need to be regenerated"));
JSON fields = acroform.addDictionaryMember(
"fields", JSON::makeArray()).
addArrayElement(JSON::makeDictionary());
fields.addDictionaryMember(
"object",
JSON::makeString("reference to this form field"));
fields.addDictionaryMember(
"parent",
JSON::makeString("reference to this field's parent"));
fields.addDictionaryMember(
"pageposfrom1",
JSON::makeString("position of containing page numbered from 1"));
fields.addDictionaryMember(
"fieldtype",
JSON::makeString("field type"));
fields.addDictionaryMember(
"fieldflags",
JSON::makeString(
"form field flags from /Ff --"
" see pdf_form_field_flag_e in qpdf/Constants.h"));
fields.addDictionaryMember(
"fullname",
JSON::makeString("full name of field"));
fields.addDictionaryMember(
"partialname",
JSON::makeString("partial name of field"));
fields.addDictionaryMember(
"alternativename",
JSON::makeString(
"alternative name of field --"
" this is the one usually shown to users"));
fields.addDictionaryMember(
"mappingname",
JSON::makeString("mapping name of field"));
fields.addDictionaryMember(
"value",
JSON::makeString("value of field"));
fields.addDictionaryMember(
"defaultvalue",
JSON::makeString("default value of field"));
fields.addDictionaryMember(
"quadding",
JSON::makeString(
"field quadding --"
" number indicating left, center, or right"));
fields.addDictionaryMember(
"ischeckbox",
JSON::makeString("whether field is a checkbox"));
fields.addDictionaryMember(
"isradiobutton",
JSON::makeString("whether field is a radio button --"
" buttons in a single group share a parent"));
fields.addDictionaryMember(
"ischoice",
JSON::makeString("whether field is a list, combo, or dropdown"));
fields.addDictionaryMember(
"istext",
JSON::makeString("whether field is a text field"));
JSON j_choices = fields.addDictionaryMember(
"choices",
JSON::makeString("for choices fields, the list of"
" choices presented to the user"));
JSON annotation = fields.addDictionaryMember(
"annotation", JSON::makeDictionary());
annotation.addDictionaryMember(
"object",
JSON::makeString("reference to the annotation object"));
annotation.addDictionaryMember(
"appearancestate",
JSON::makeString("appearance state --"
" can be used to determine value for"
" checkboxes and radio buttons"));
annotation.addDictionaryMember(
"annotationflags",
JSON::makeString(
"annotation flags from /F --"
" see pdf_annotation_flag_e in qpdf/Constants.h"));
}
return schema;
}
static void parse_object_id(std::string const& objspec,
bool& trailer, int& obj, int& gen)
{
if (objspec == "trailer")
{
trailer = true;
}
else
{
trailer = false;
obj = QUtil::string_to_int(objspec.c_str());
size_t comma = objspec.find(',');
if ((comma != std::string::npos) && (comma + 1 < objspec.length()))
{
gen = QUtil::string_to_int(
objspec.substr(1 + comma, std::string::npos).c_str());
}
}
}
// This is not a general-purpose argument parser. It is tightly
// crafted to work with qpdf. qpdf's command-line syntax is very
// complex because of its long history, and it doesn't really follow
// any kind of normal standard for arguments, but I don't want to
// break compatibility by changing what constitutes a valid command.
// This class is intended to simplify the argument parsing code and
// also to make it possible to add bash completion support while
// guaranteeing consistency with the actual argument syntax.
class ArgParser
{
public:
ArgParser(int argc, char* argv[], Options& o);
void parseOptions();
private:
typedef void (ArgParser::*bare_arg_handler_t)();
typedef void (ArgParser::*param_arg_handler_t)(char* parameter);
struct OptionEntry
{
OptionEntry() :
parameter_needed(false),
bare_arg_handler(0),
param_arg_handler(0)
{
}
bool parameter_needed;
std::string parameter_name;
std::set<std::string> choices;
bare_arg_handler_t bare_arg_handler;
param_arg_handler_t param_arg_handler;
};
friend struct OptionEntry;
OptionEntry oe_positional(param_arg_handler_t);
OptionEntry oe_bare(bare_arg_handler_t);
OptionEntry oe_requiredParameter(param_arg_handler_t, char const* name);
OptionEntry oe_optionalParameter(param_arg_handler_t);
OptionEntry oe_requiredChoices(param_arg_handler_t, char const** choices);
void argHelp();
void argVersion();
void argCopyright();
void argCompletionBash();
void argCompletionZsh();
void argJsonHelp();
void argPositional(char* arg);
void argPassword(char* parameter);
void argEmpty();
void argLinearize();
void argEncrypt();
void argDecrypt();
void argPasswordIsHexKey();
void argPasswordMode(char* parameter);
void argSuppressPasswordRecovery();
void argCopyEncryption(char* parameter);
void argEncryptionFilePassword(char* parameter);
void argPages();
void argUnderlay();
void argOverlay();
void argRotate(char* parameter);
void argCollate();
void argStreamData(char* parameter);
void argCompressStreams(char* parameter);
void argDecodeLevel(char* parameter);
void argNormalizeContent(char* parameter);
void argSuppressRecovery();
void argObjectStreams(char* parameter);
void argIgnoreXrefStreams();
void argQdf();
void argPreserveUnreferenced();
void argPreserveUnreferencedResources();
void argKeepFilesOpen(char* parameter);
void argKeepFilesOpenThreshold(char* parameter);
void argNewlineBeforeEndstream();
void argLinearizePass1(char* parameter);
void argCoalesceContents();
void argFlattenAnnotations(char* parameter);
void argGenerateAppearances();
void argMinVersion(char* parameter);
void argForceVersion(char* parameter);
void argSplitPages(char* parameter);
void argVerbose();
void argProgress();
void argNoWarn();
void argDeterministicId();
void argStaticId();
void argStaticAesIv();
void argNoOriginalObjectIds();
void argShowEncryption();
void argShowEncryptionKey();
void argCheckLinearization();
void argShowLinearization();
void argShowXref();
void argShowObject(char* parameter);
void argRawStreamData();
void argFilteredStreamData();
void argShowNpages();
void argShowPages();
void argWithImages();
void argJson();
void argJsonKey(char* parameter);
void argJsonObject(char* parameter);
void argCheck();
void argOptimizeImages();
void argExternalizeInlineImages();
void argKeepInlineImages();
void argRemovePageLabels();
void argOiMinWidth(char* parameter);
void argOiMinHeight(char* parameter);
void argOiMinArea(char* parameter);
void argIiMinBytes(char* parameter);
void arg40Print(char* parameter);
void arg40Modify(char* parameter);
void arg40Extract(char* parameter);
void arg40Annotate(char* parameter);
void arg128Accessibility(char* parameter);
void arg128Extract(char* parameter);
void arg128Print(char* parameter);
void arg128Modify(char* parameter);
void arg128ClearTextMetadata();
void arg128Assemble(char* parameter);
void arg128Annotate(char* parameter);
void arg128Form(char* parameter);
void arg128ModOther(char* parameter);
void arg128UseAes(char* parameter);
void arg128ForceV4();
void arg256ForceR5();
void argEndEncrypt();
void argUOpositional(char* arg);
void argUOto(char* parameter);
void argUOfrom(char* parameter);
void argUOrepeat(char* parameter);
void argUOpassword(char* parameter);
void argEndUnderOverlay();
void usage(std::string const& message);
void checkCompletion();
void initOptionTable();
void handleHelpArgs();
void handleArgFileArguments();
void handleBashArguments();
void readArgsFromFile(char const* filename);
void doFinalChecks();
void addOptionsToCompletions();
void addChoicesToCompletions(std::string const&, std::string const&);
void handleCompletion();
std::vector<PageSpec> parsePagesOptions();
void parseUnderOverlayOptions(UnderOverlay*);
void parseRotationParameter(std::string const&);
std::vector<int> parseNumrange(char const* range, int max,
bool throw_error = false);
int argc;
char** argv;
Options& o;
int cur_arg;
bool bash_completion;
bool zsh_completion;
std::string bash_prev;
std::string bash_cur;
std::string bash_line;
std::set<std::string> completions;
std::map<std::string, OptionEntry>* option_table;
std::map<std::string, OptionEntry> help_option_table;
std::map<std::string, OptionEntry> main_option_table;
std::map<std::string, OptionEntry> encrypt40_option_table;
std::map<std::string, OptionEntry> encrypt128_option_table;
std::map<std::string, OptionEntry> encrypt256_option_table;
std::map<std::string, OptionEntry> under_overlay_option_table;
std::vector<PointerHolder<char> > new_argv;
std::vector<PointerHolder<char> > bash_argv;
PointerHolder<char*> argv_ph;
PointerHolder<char*> bash_argv_ph;
};
ArgParser::ArgParser(int argc, char* argv[], Options& o) :
argc(argc),
argv(argv),
o(o),
cur_arg(0),
bash_completion(false),
zsh_completion(false)
{
option_table = &main_option_table;
initOptionTable();
}
ArgParser::OptionEntry
ArgParser::oe_positional(param_arg_handler_t h)
{
OptionEntry oe;
oe.param_arg_handler = h;
return oe;
}
ArgParser::OptionEntry
ArgParser::oe_bare(bare_arg_handler_t h)
{
OptionEntry oe;
oe.parameter_needed = false;
oe.bare_arg_handler = h;
return oe;
}
ArgParser::OptionEntry
ArgParser::oe_requiredParameter(param_arg_handler_t h, char const* name)
{
OptionEntry oe;
oe.parameter_needed = true;
oe.parameter_name = name;
oe.param_arg_handler = h;
return oe;
}
ArgParser::OptionEntry
ArgParser::oe_optionalParameter(param_arg_handler_t h)
{
OptionEntry oe;
oe.parameter_needed = false;
oe.param_arg_handler = h;
return oe;
}
ArgParser::OptionEntry
ArgParser::oe_requiredChoices(param_arg_handler_t h, char const** choices)
{
OptionEntry oe;
oe.parameter_needed = true;
oe.param_arg_handler = h;
for (char const** i = choices; *i; ++i)
{
oe.choices.insert(*i);
}
return oe;
}
void
ArgParser::initOptionTable()
{
std::map<std::string, OptionEntry>* t = &this->help_option_table;
(*t)["help"] = oe_bare(&ArgParser::argHelp);
(*t)["version"] = oe_bare(&ArgParser::argVersion);
(*t)["copyright"] = oe_bare(&ArgParser::argCopyright);
(*t)["completion-bash"] = oe_bare(&ArgParser::argCompletionBash);
(*t)["completion-zsh"] = oe_bare(&ArgParser::argCompletionZsh);
(*t)["json-help"] = oe_bare(&ArgParser::argJsonHelp);
t = &this->main_option_table;
char const* yn[] = {"y", "n", 0};
(*t)[""] = oe_positional(&ArgParser::argPositional);
(*t)["password"] = oe_requiredParameter(
&ArgParser::argPassword, "password");
(*t)["empty"] = oe_bare(&ArgParser::argEmpty);
(*t)["linearize"] = oe_bare(&ArgParser::argLinearize);
(*t)["encrypt"] = oe_bare(&ArgParser::argEncrypt);
(*t)["decrypt"] = oe_bare(&ArgParser::argDecrypt);
(*t)["password-is-hex-key"] = oe_bare(&ArgParser::argPasswordIsHexKey);
(*t)["suppress-password-recovery"] =
oe_bare(&ArgParser::argSuppressPasswordRecovery);
char const* password_mode_choices[] =
{"bytes", "hex-bytes", "unicode", "auto", 0};
(*t)["password-mode"] = oe_requiredChoices(
&ArgParser::argPasswordMode, password_mode_choices);
(*t)["copy-encryption"] = oe_requiredParameter(
&ArgParser::argCopyEncryption, "file");
(*t)["encryption-file-password"] = oe_requiredParameter(
&ArgParser::argEncryptionFilePassword, "password");
(*t)["pages"] = oe_bare(&ArgParser::argPages);
(*t)["rotate"] = oe_requiredParameter(
&ArgParser::argRotate, "[+|-]angle:page-range");
char const* stream_data_choices[] =
{"compress", "preserve", "uncompress", 0};
(*t)["collate"] = oe_bare(&ArgParser::argCollate);
(*t)["stream-data"] = oe_requiredChoices(
&ArgParser::argStreamData, stream_data_choices);
(*t)["compress-streams"] = oe_requiredChoices(
&ArgParser::argCompressStreams, yn);
char const* decode_level_choices[] =
{"none", "generalized", "specialized", "all", 0};
(*t)["decode-level"] = oe_requiredChoices(
&ArgParser::argDecodeLevel, decode_level_choices);
(*t)["normalize-content"] = oe_requiredChoices(
&ArgParser::argNormalizeContent, yn);
(*t)["suppress-recovery"] = oe_bare(&ArgParser::argSuppressRecovery);
char const* object_streams_choices[] = {
"disable", "preserve", "generate", 0};
(*t)["object-streams"] = oe_requiredChoices(
&ArgParser::argObjectStreams, object_streams_choices);
(*t)["ignore-xref-streams"] = oe_bare(&ArgParser::argIgnoreXrefStreams);
(*t)["qdf"] = oe_bare(&ArgParser::argQdf);
(*t)["preserve-unreferenced"] = oe_bare(
&ArgParser::argPreserveUnreferenced);
(*t)["preserve-unreferenced-resources"] = oe_bare(
&ArgParser::argPreserveUnreferencedResources);
(*t)["keep-files-open"] = oe_requiredChoices(
&ArgParser::argKeepFilesOpen, yn);
(*t)["keep-files-open-threshold"] = oe_requiredParameter(
&ArgParser::argKeepFilesOpenThreshold, "count");
(*t)["newline-before-endstream"] = oe_bare(
&ArgParser::argNewlineBeforeEndstream);
(*t)["linearize-pass1"] = oe_requiredParameter(
&ArgParser::argLinearizePass1, "filename");
(*t)["coalesce-contents"] = oe_bare(&ArgParser::argCoalesceContents);
char const* flatten_choices[] = {"all", "print", "screen", 0};
(*t)["flatten-annotations"] = oe_requiredChoices(
&ArgParser::argFlattenAnnotations, flatten_choices);
(*t)["generate-appearances"] =
oe_bare(&ArgParser::argGenerateAppearances);
(*t)["min-version"] = oe_requiredParameter(
&ArgParser::argMinVersion, "version");
(*t)["force-version"] = oe_requiredParameter(
&ArgParser::argForceVersion, "version");
(*t)["split-pages"] = oe_optionalParameter(&ArgParser::argSplitPages);
(*t)["verbose"] = oe_bare(&ArgParser::argVerbose);
(*t)["progress"] = oe_bare(&ArgParser::argProgress);
(*t)["no-warn"] = oe_bare(&ArgParser::argNoWarn);
(*t)["deterministic-id"] = oe_bare(&ArgParser::argDeterministicId);
(*t)["static-id"] = oe_bare(&ArgParser::argStaticId);
(*t)["static-aes-iv"] = oe_bare(&ArgParser::argStaticAesIv);
(*t)["no-original-object-ids"] = oe_bare(
&ArgParser::argNoOriginalObjectIds);
(*t)["show-encryption"] = oe_bare(&ArgParser::argShowEncryption);
(*t)["show-encryption-key"] = oe_bare(&ArgParser::argShowEncryptionKey);
(*t)["check-linearization"] = oe_bare(&ArgParser::argCheckLinearization);
(*t)["show-linearization"] = oe_bare(&ArgParser::argShowLinearization);
(*t)["show-xref"] = oe_bare(&ArgParser::argShowXref);
(*t)["show-object"] = oe_requiredParameter(
&ArgParser::argShowObject, "trailer|obj[,gen]");
(*t)["raw-stream-data"] = oe_bare(&ArgParser::argRawStreamData);
(*t)["filtered-stream-data"] = oe_bare(&ArgParser::argFilteredStreamData);
(*t)["show-npages"] = oe_bare(&ArgParser::argShowNpages);
(*t)["show-pages"] = oe_bare(&ArgParser::argShowPages);
(*t)["with-images"] = oe_bare(&ArgParser::argWithImages);
(*t)["json"] = oe_bare(&ArgParser::argJson);
// The list of selectable top-level keys id duplicated in three
// places: json_schema, do_json, and initOptionTable.
char const* json_key_choices[] = {
"objects", "pages", "pagelabels", "outlines", "acroform", 0};
(*t)["json-key"] = oe_requiredChoices(
&ArgParser::argJsonKey, json_key_choices);
(*t)["json-object"] = oe_requiredParameter(
&ArgParser::argJsonObject, "trailer|obj[,gen]");
(*t)["check"] = oe_bare(&ArgParser::argCheck);
(*t)["optimize-images"] = oe_bare(&ArgParser::argOptimizeImages);
(*t)["externalize-inline-images"] =
oe_bare(&ArgParser::argExternalizeInlineImages);
(*t)["keep-inline-images"] = oe_bare(&ArgParser::argKeepInlineImages);
(*t)["remove-page-labels"] = oe_bare(&ArgParser::argRemovePageLabels);
(*t)["oi-min-width"] = oe_requiredParameter(
&ArgParser::argOiMinWidth, "minimum-width");
(*t)["oi-min-height"] = oe_requiredParameter(
&ArgParser::argOiMinHeight, "minimum-height");
(*t)["oi-min-area"] = oe_requiredParameter(
&ArgParser::argOiMinArea, "minimum-area");
(*t)["ii-min-bytes"] = oe_requiredParameter(
&ArgParser::argIiMinBytes, "minimum-bytes");
(*t)["overlay"] = oe_bare(&ArgParser::argOverlay);
(*t)["underlay"] = oe_bare(&ArgParser::argUnderlay);
t = &this->encrypt40_option_table;
(*t)["--"] = oe_bare(&ArgParser::argEndEncrypt);
(*t)["print"] = oe_requiredChoices(&ArgParser::arg40Print, yn);
(*t)["modify"] = oe_requiredChoices(&ArgParser::arg40Modify, yn);
(*t)["extract"] = oe_requiredChoices(&ArgParser::arg40Extract, yn);
(*t)["annotate"] = oe_requiredChoices(&ArgParser::arg40Annotate, yn);
t = &this->encrypt128_option_table;
(*t)["--"] = oe_bare(&ArgParser::argEndEncrypt);
(*t)["accessibility"] = oe_requiredChoices(
&ArgParser::arg128Accessibility, yn);
(*t)["extract"] = oe_requiredChoices(&ArgParser::arg128Extract, yn);
char const* print128_choices[] = {"full", "low", "none", 0};
(*t)["print"] = oe_requiredChoices(
&ArgParser::arg128Print, print128_choices);
(*t)["assemble"] = oe_requiredChoices(&ArgParser::arg128Assemble, yn);
(*t)["annotate"] = oe_requiredChoices(&ArgParser::arg128Annotate, yn);
(*t)["form"] = oe_requiredChoices(&ArgParser::arg128Form, yn);
(*t)["modify-other"] = oe_requiredChoices(&ArgParser::arg128ModOther, yn);
char const* modify128_choices[] =
{"all", "annotate", "form", "assembly", "none", 0};
(*t)["modify"] = oe_requiredChoices(
&ArgParser::arg128Modify, modify128_choices);
(*t)["cleartext-metadata"] = oe_bare(&ArgParser::arg128ClearTextMetadata);
// The above 128-bit options are also 256-bit options, so copy
// what we have so far. Then continue separately with 128 and 256.
this->encrypt256_option_table = this->encrypt128_option_table;
(*t)["use-aes"] = oe_requiredChoices(&ArgParser::arg128UseAes, yn);
(*t)["force-V4"] = oe_bare(&ArgParser::arg128ForceV4);
t = &this->encrypt256_option_table;
(*t)["force-R5"] = oe_bare(&ArgParser::arg256ForceR5);
t = &this->under_overlay_option_table;
(*t)[""] = oe_positional(&ArgParser::argUOpositional);
(*t)["to"] = oe_requiredParameter(
&ArgParser::argUOto, "page-range");
(*t)["from"] = oe_requiredParameter(
&ArgParser::argUOfrom, "page-range");
(*t)["repeat"] = oe_requiredParameter(
&ArgParser::argUOrepeat, "page-range");
(*t)["password"] = oe_requiredParameter(
&ArgParser::argUOpassword, "password");
(*t)["--"] = oe_bare(&ArgParser::argEndUnderOverlay);
}
void
ArgParser::argPositional(char* arg)
{
if (o.infilename == 0)
{
o.infilename = arg;
}
else if (o.outfilename == 0)
{
o.outfilename = arg;
}
else
{
usage(std::string("unknown argument ") + arg);
}
}
void
ArgParser::argVersion()
{
if (expected_version != QPDF::QPDFVersion())
{
std::cerr << "***\n"
<< "WARNING: qpdf CLI from version " << expected_version
<< " is using library version " << QPDF::QPDFVersion()
<< ".\n"
<< "This probably means you have multiple versions of qpdf installed\n"
<< "and don't have your library path configured correctly.\n"
<< "***"
<< std::endl;
}
std::cout
<< whoami << " version " << QPDF::QPDFVersion() << std::endl
<< "Run " << whoami << " --copyright to see copyright and license information."
<< std::endl;
}
void
ArgParser::argCopyright()
{
// Make sure the output looks right on an 80-column display.
// 1 2 3 4 5 6 7 8
// 12345678901234567890123456789012345678901234567890123456789012345678901234567890
std::cout
<< whoami << " version " << QPDF::QPDFVersion() << std::endl
<< std::endl
<< "Copyright (c) 2005-2019 Jay Berkenbilt"
<< std::endl
<< "QPDF is licensed under the Apache License, Version 2.0 (the \"License\");"
<< std::endl
<< "not use this file except in compliance with the License."
<< std::endl
<< "You may obtain a copy of the License at"
<< std::endl
<< std::endl
<< " http://www.apache.org/licenses/LICENSE-2.0"
<< std::endl
<< std::endl
<< "Unless required by applicable law or agreed to in writing, software"
<< std::endl
<< "distributed under the License is distributed on an \"AS IS\" BASIS,"
<< std::endl
<< "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied."
<< std::endl
<< "See the License for the specific language governing permissions and"
<< std::endl
<< "limitations under the License."
<< std::endl
<< std::endl
<< "Versions of qpdf prior to version 7 were released under the terms"
<< std::endl
<< "of version 2.0 of the Artistic License. At your option, you may"
<< std::endl
<< "continue to consider qpdf to be licensed under those terms. Please"
<< std::endl
<< "see the manual for additional information."
<< std::endl;
}
void
ArgParser::argHelp()
{
std::cout
// 12345678901234567890123456789012345678901234567890123456789012345678901234567890
<< "Usage: qpdf [ options ] { infilename | --empty } [ outfilename ]\n"
<< "\n"
<< "An option summary appears below. Please see the documentation for details.\n"
<< "\n"
<< "If @filename appears anywhere in the command-line, each line of filename\n"
<< "will be interpreted as an argument. No interpolation is done. Line\n"
<< "terminators are stripped. @- can be specified to read from standard input.\n"
<< "\n"
<< "Note that when contradictory options are provided, whichever options are\n"
<< "provided last take precedence.\n"
<< "\n"
<< "\n"
<< "Basic Options\n"
<< "-------------\n"
<< "\n"
<< "--version show version of qpdf\n"
<< "--copyright show qpdf's copyright and license information\n"
<< "--help show command-line argument help\n"
<< "--completion-bash output a bash complete command you can eval\n"
<< "--completion-zsh output a zsh complete command you can eval\n"
<< "--password=password specify a password for accessing encrypted files\n"
<< "--verbose provide additional informational output\n"
<< "--progress give progress indicators while writing output\n"
<< "--no-warn suppress warnings\n"
<< "--linearize generated a linearized (web optimized) file\n"
<< "--copy-encryption=file copy encryption parameters from specified file\n"
<< "--encryption-file-password=password\n"
<< " password used to open the file from which encryption\n"
<< " parameters are being copied\n"
<< "--encrypt options -- generate an encrypted file\n"
<< "--decrypt remove any encryption on the file\n"
<< "--password-is-hex-key treat primary password option as a hex-encoded key\n"
<< "--suppress-password-recovery\n"
<< " do not attempt recovering from password string\n"
<< " encoding errors\n"
<< "--password-mode=mode control qpdf's encoding of passwords\n"
<< "--pages options -- select specific pages from one or more files\n"
<< "--collate causes files specified in --pages to be collated\n"
<< " rather than concatenated\n"
<< "--rotate=[+|-]angle[:page-range]\n"
<< " rotate each specified page 90, 180, or 270 degrees;\n"
<< " rotate all pages if no page range is given\n"
<< "--split-pages=[n] write each output page to a separate file\n"
<< "--overlay options -- overlay pages from another file\n"
<< "--underlay options -- underlay pages from another file\n"
<< "\n"
<< "Note that you can use the @filename or @- syntax for any argument at any\n"
<< "point in the command. This provides a good way to specify a password without\n"
<< "having to explicitly put it on the command line.\n"
<< "\n"
<< "If none of --copy-encryption, --encrypt or --decrypt are given, qpdf will\n"
<< "preserve any encryption data associated with a file.\n"
<< "\n"
<< "Note that when copying encryption parameters from another file, all\n"
<< "parameters will be copied, including both user and owner passwords, even\n"
<< "if the user password is used to open the other file. This works even if\n"
<< "the owner password is not known.\n"
<< "\n"
<< "The --password-is-hex-key option overrides the normal computation of\n"
<< "encryption keys. It only applies to the password used to open the main\n"
<< "file. This option is not ordinarily useful but can be helpful for forensic\n"
<< "or investigatory purposes. See manual for further discussion.\n"
<< "\n"
<< "The --rotate flag can be used to specify pages to rotate pages either\n"
<< "90, 180, or 270 degrees. The page range is specified in the same\n"
<< "format as with the --pages option, described below. Repeat the option\n"
<< "to rotate multiple groups of pages. If the angle is preceded by + or -,\n"
<< "it is added to or subtracted from the original rotation. Otherwise, the\n"
<< "rotation angle is set explicitly to the given value.\n"
<< "\n"
<< "If --split-pages is specified, each page is written to a separate output\n"
<< "file. File names are generated as follows:\n"
<< "* If the string %d appears in the output file name, it is replaced with a\n"
<< " zero-padded page range starting from 1\n"
<< "* Otherwise, if the output file name ends in .pdf (case insensitive), a\n"
<< " zero-padded page range, preceded by a dash, is inserted before the file\n"
<< " extension\n"
<< "* Otherwise, the file name is appended with a zero-padded page range\n"
<< " preceded by a dash.\n"
<< "Page ranges are single page numbers for single-page groups or first-last\n"
<< "for multipage groups.\n"
<< "\n"
<< "\n"
<< "Encryption Options\n"
<< "------------------\n"
<< "\n"
<< " --encrypt user-password owner-password key-length flags --\n"
<< "\n"
<< "Note that -- terminates parsing of encryption flags.\n"
<< "\n"
<< "Either or both of the user password and the owner password may be\n"
<< "empty strings.\n"
<< "\n"
<< "key-length may be 40, 128, or 256\n"
<< "\n"
<< "Additional flags are dependent upon key length.\n"
<< "\n"
<< " If 40:\n"
<< "\n"
<< " --print=[yn] allow printing\n"
<< " --modify=[yn] allow document modification\n"
<< " --extract=[yn] allow text/graphic extraction\n"
<< " --annotate=[yn] allow comments and form fill-in and signing\n"
<< "\n"
<< " If 128:\n"
<< "\n"
<< " --accessibility=[yn] allow accessibility to visually impaired\n"
<< " --extract=[yn] allow other text/graphic extraction\n"
<< " --print=print-opt control printing access\n"
<< " --assemble=[yn] allow document assembly\n"
<< " --annotate=[yn] allow commenting/filling form fields\n"
<< " --form=[yn] allow filling form fields\n"
<< " --modify-other=[yn] allow other modifications\n"
<< " --modify=modify-opt control modify access (old way)\n"
<< " --cleartext-metadata prevents encryption of metadata\n"
<< " --use-aes=[yn] indicates whether to use AES encryption\n"
<< " --force-V4 forces use of V=4 encryption handler\n"
<< "\n"
<< " If 256, options are the same as 128 with these exceptions:\n"
<< " --force-V4 this option is not available with 256-bit keys\n"
<< " --use-aes this option is always on with 256-bit keys\n"
<< " --force-R5 forces use of deprecated R=5 encryption\n"
<< "\n"
<< " print-opt may be:\n"
<< "\n"
<< " full allow full printing\n"
<< " low allow only low-resolution printing\n"
<< " none disallow printing\n"
<< "\n"
<< " modify-opt may be:\n"
<< "\n"
<< " all allow full document modification\n"
<< " annotate allow comment authoring and form operations\n"
<< " form allow form field fill-in and signing\n"
<< " assembly allow document assembly only\n"
<< " none allow no modifications\n"
<< "\n"
<< "The default for each permission option is to be fully permissive. Please\n"
<< "refer to the manual for more details on the modify options.\n"
<< "\n"
<< "Specifying cleartext-metadata forces the PDF version to at least 1.5.\n"
<< "Specifying use of AES forces the PDF version to at least 1.6. These\n"
<< "options are both off by default.\n"
<< "\n"
<< "The --force-V4 flag forces the V=4 encryption handler introduced in PDF 1.5\n"
<< "to be used even if not otherwise needed. This option is primarily useful\n"
<< "for testing qpdf and has no other practical use.\n"
<< "\n"
<< "\n"
<< "Password Modes\n"
<< "----------------------\n"
<< "\n"
<< "The --password-mode controls how qpdf interprets passwords supplied\n"
<< "on the command-line. qpdf's default behavior is correct in almost all\n"
<< "cases, but you can fine-tune with this option.\n"
<< "\n"
<< " bytes: use the password literally as supplied\n"
<< " hex-bytes: interpret the password as a hex-encoded byte string\n"
<< " unicode: interpret the password as a UTF-8 encoded string\n"
<< " auto: attempt to infer the encoding and adjust as needed\n"
<< "\n"
<< "This is a complex topic. See the manual for a complete discussion.\n"
<< "\n"
<< "\n"
<< "Page Selection Options\n"
<< "----------------------\n"
<< "\n"
<< "These options allow pages to be selected from one or more PDF files.\n"
<< "Whatever file is given as the primary input file is used as the\n"
<< "starting point, but its pages are replaced with pages as specified.\n"
<< "\n"
<< "--keep-files-open=[yn]\n"
<< "--keep-files-open-threshold=count\n"
<< "--pages file [ --password=password ] [ page-range ] ... --\n"
<< "\n"
<< "For each file that pages should be taken from, specify the file, a\n"
<< "password needed to open the file (if any), and a page range. The\n"
<< "password needs to be given only once per file. If any of the input\n"
<< "files are the same as the primary input file or the file used to copy\n"
<< "encryption parameters (if specified), you do not need to repeat the\n"
<< "password here. The same file can be repeated multiple times. The\n"
<< "filename \".\" may be used to refer to the current input file. All\n"
<< "non-page data (info, outlines, page numbers, etc. are taken from the\n"
<< "primary input file. To discard this, use --empty as the primary\n"
<< "input.\n"
<< "\n"
<< "By default, when more than 200 distinct files are specified, qpdf will\n"
<< "close each file when not being referenced. With 200 files or fewer, all\n"
<< "files will be kept open at the same time. This behavior can be overridden\n"
<< "by specifying --keep-files-open=[yn]. Closing and opening files can have\n"
<< "very high overhead on certain file systems, especially networked file\n"
<< "systems. The threshold of 200 can be modified with\n"
<< "--keep-files-open-threshold\n"
<< "\n"
<< "The page range is a set of numbers separated by commas, ranges of\n"
<< "numbers separated dashes, or combinations of those. The character\n"
<< "\"z\" represents the last page. A number preceded by an \"r\" indicates\n"
<< "to count from the end, so \"r3-r1\" would be the last three pages of the\n"
<< "document. Pages can appear in any order. Ranges can appear with a\n"
<< "high number followed by a low number, which causes the pages to appear in\n"
<< "reverse. Repeating a number will cause an error, but the manual discusses\n"
<< "a workaround should you really want to include the same page twice.\n"
<< "\n"
<< "If the page range is omitted, the range of 1-z is assumed. qpdf decides\n"
<< "that the page range is omitted if the range argument is either -- or a\n"
<< "valid file name and not a valid range.\n"
<< "\n"
<< "The usual behavior of --pages is to add all pages from the first file,\n"
<< "then all pages from the second file, and so on. If the --collate option\n"
<< "is specified, then pages are collated instead. In other words, qpdf takes\n"
<< "the first page from the first file, the first page from the second file,\n"
<< "and so on until it runs out of files; then it takes the second page from\n"
<< "each file, etc. When a file runs out of pages, it is skipped until all\n"
<< "specified pages are taken from all files.\n"
<< "\n"
<< "See the manual for examples and a discussion of additional subtleties.\n"
<< "\n"
<< "\n"
<< "Overlay and Underlay Options\n"
<< "-------------------------------\n"
<< "\n"
<< "These options allow pages from another file to be overlaid or underlaid\n"
<< "on the primary output. Overlaid pages are drawn on top of the destination\n"
<< "page and may obscure the page. Underlaid pages are drawn below the\n"
<< "destination page.\n"
<< "\n"
<< "{--overlay | --underlay } file\n"
" [ --password=password ]\n"
" [ --to=page-range ]\n"
" [ --from=[page-range] ]\n"
" [ --repeat=page-range ]\n"
" --\n"
<< "\n"
<< "For overlay and underlay, a file and optional password are specified, along\n"
<< "with a series of optional page ranges. The default behavior is that each\n"
<< "page of the overlay or underlay file is imposed on the corresponding page\n"
<< "of the primary output until it runs out of pages, and any extra pages are\n"
<< "ignored. The page range options all take page ranges in the same form as\n"
<< "the --pages option. They have the following meanings:\n"
<< "\n"
<< " --to: the pages in the primary output to which overlay/underlay is\n"
<< " applied\n"
<< " --from: the pages from the overlay/underlay file that are used\n"
<< " --repeat: pages from the overlay/underlay that are repeated after\n"
<< " any \"from\" pages have been exhausted\n"
<< "\n"
<< "\n"
<< "Advanced Parsing Options\n"
<< "-------------------------------\n"
<< "\n"
<< "These options control aspects of how qpdf reads PDF files. Mostly these are\n"
<< "of use to people who are working with damaged files. There is little reason\n"
<< "to use these options unless you are trying to solve specific problems.\n"
<< "\n"
<< "--suppress-recovery prevents qpdf from attempting to recover damaged files\n"
<< "--ignore-xref-streams tells qpdf to ignore any cross-reference streams\n"
<< "\n"
<< "\n"
<< "Advanced Transformation Options\n"
<< "-------------------------------\n"
<< "\n"
<< "These transformation options control fine points of how qpdf creates\n"
<< "the output file. Mostly these are of use only to people who are very\n"
<< "familiar with the PDF file format or who are PDF developers.\n"
<< "\n"
<< "--stream-data=option controls transformation of stream data (below)\n"
<< "--compress-streams=[yn] controls whether to compress streams on output\n"
<< "--decode-level=option controls how to filter streams from the input\n"
<< "--normalize-content=[yn] enables or disables normalization of content streams\n"
<< "--object-streams=mode controls handing of object streams\n"
<< "--preserve-unreferenced preserve unreferenced objects\n"
<< "--preserve-unreferenced-resources\n"
<< " preserve unreferenced page resources\n"
<< "--newline-before-endstream always put a newline before endstream\n"
<< "--coalesce-contents force all pages' content to be a single stream\n"
<< "--flatten-annotations=option\n"
<< " incorporate rendering of annotations into page\n"
<< " contents including those for interactive form\n"
<< " fields; may also want --generate-appearances\n"
<< "--generate-appearances generate appearance streams for form fields\n"
<< "--optimize-images compress images with DCT (JPEG) when advantageous\n"
<< "--oi-min-width=w do not optimize images whose width is below w;\n"
<< " default is 128. Use 0 to mean no minimum\n"
<< "--oi-min-height=h do not optimize images whose height is below h\n"
<< " default is 128. Use 0 to mean no minimum\n"
<< "--oi-min-area=a do not optimize images whose pixel count is below a\n"
<< " default is 16,384. Use 0 to mean no minimum\n"
<< "--externalize-inline-images convert inline images to regular images; by\n"
<< " default, images of at least 1,024 bytes are\n"
<< " externalized\n"
<< "--ii-min-bytes=bytes specify minimum size of inline images to be\n"
<< " converted to regular images\n"
<< "--keep-inline-images exclude inline images from image optimization\n"
<< "--remove-page-labels remove any page labels present in the output file\n"
<< "--qdf turns on \"QDF mode\" (below)\n"
<< "--linearize-pass1=file write intermediate pass of linearized file\n"
<< " for debugging\n"
<< "--min-version=version sets the minimum PDF version of the output file\n"
<< "--force-version=version forces this to be the PDF version of the output file\n"
<< "\n"
<< "Options for --flatten-annotations are all, print, or screen. If the option\n"
<< "is print, only annotations marked as print are included. If the option is\n"
<< "screen, options marked as \"no view\" are excluded. Otherwise, annotations\n"
<< "are flattened regardless of the presence of print or NoView flags. It is\n"
<< "common for PDF files to have a flag set that appearance streams need to be\n"
<< "regenerated. This happens when someone changes a form value with software\n"
<< "that does not know how to render the new value. qpdf will not flatten form\n"
<< "fields in files like this. If you get this warning, you have two choices:\n"
<< "either use qpdf's --generate-appearances flag to tell qpdf to go ahead and\n"
<< "regenerate appearances, or use some other tool to generate the appearances.\n"
<< "qpdf does a pretty good job with most forms when only ASCII and \"Windows\n"
<< "ANSI\" characters are used in form field values, but if your form fields\n"
<< "contain other characters, rich text, or are other than left justified, you\n"
<< "will get better results first saving with other software.\n"
<< "\n"
<< "Version numbers may be expressed as major.minor.extension-level, so 1.7.3\n"
<< "means PDF version 1.7 at extension level 3.\n"
<< "\n"
<< "Values for stream data options:\n"
<< "\n"
<< " compress recompress stream data when possible (default)\n"
<< " preserve leave all stream data as is\n"
<< " uncompress uncompress stream data when possible\n"
<< "\n"
<< "Values for object stream mode:\n"
<< "\n"
<< " preserve preserve original object streams (default)\n"
<< " disable don't write any object streams\n"
<< " generate use object streams wherever possible\n"
<< "\n"
<< "When --compress-streams=n is specified, this overrides the default behavior\n"
<< "of qpdf, which is to attempt compress uncompressed streams. Setting\n"
<< "stream data mode to uncompress or preserve has the same effect.\n"
<< "\n"
<< "The --decode-level parameter may be set to one of the following values:\n"
<< " none do not decode streams\n"
<< " generalized decode streams compressed with generalized filters\n"
<< " including LZW, Flate, and the ASCII encoding filters.\n"
<< " specialized additionally decode streams with non-lossy specialized\n"
<< " filters including RunLength\n"
<< " all additionally decode streams with lossy filters\n"
<< " including DCT (JPEG)\n"
<< "\n"
<< "In qdf mode, by default, content normalization is turned on, and the\n"
<< "stream data mode is set to uncompress. QDF mode does not support\n"
<< "linearized files. The --linearize flag disables qdf mode.\n"
<< "\n"
<< "Setting the minimum PDF version of the output file may raise the version\n"
<< "but will never lower it. Forcing the PDF version of the output file may\n"
<< "set the PDF version to a lower value than actually allowed by the file's\n"
<< "contents. You should only do this if you have no other possible way to\n"
<< "open the file or if you know that the file definitely doesn't include\n"
<< "features not supported later versions.\n"
<< "\n"
<< "Testing, Inspection, and Debugging Options\n"
<< "------------------------------------------\n"
<< "\n"
<< "These options can be useful for digging into PDF files or for use in\n"
<< "automated test suites for software that uses the qpdf library.\n"
<< "\n"
<< "--deterministic-id generate deterministic /ID\n"
<< "--static-id generate static /ID: FOR TESTING ONLY!\n"
<< "--static-aes-iv use a static initialization vector for AES-CBC\n"
<< " This is option is not secure! FOR TESTING ONLY!\n"
<< "--no-original-object-ids suppress original object ID comments in qdf mode\n"
<< "--show-encryption quickly show encryption parameters\n"
<< "--show-encryption-key when showing encryption, reveal the actual key\n"
<< "--check-linearization check file integrity and linearization status\n"
<< "--show-linearization check and show all linearization data\n"
<< "--show-xref show the contents of the cross-reference table\n"
<< "--show-object=trailer|obj[,gen]\n"
<< " show the contents of the given object\n"
<< " --raw-stream-data show raw stream data instead of object contents\n"
<< " --filtered-stream-data show filtered stream data instead of object contents\n"
<< "--show-npages print the number of pages in the file\n"
<< "--show-pages shows the object/generation number for each page\n"
<< " --with-images also shows the object IDs for images on each page\n"
<< "--check check file structure + encryption, linearization\n"
<< "--json generate a json representation of the file\n"
<< "--json-help describe the format of the json representation\n"
<< "--json-key=key repeatable; prune json structure to include only\n"
<< " specified keys. If absent, all keys are shown\n"
<< "--json-object=trailer|[obj,gen]\n"
<< " repeatable; include only specified objects in the\n"
<< " \"objects\" section of the json. If absent, all\n"
<< " objects are shown\n"
<< "\n"
<< "The json representation generated by qpdf is designed to facilitate\n"
<< "processing of qpdf from other programming languages that have a hard\n"
<< "time calling C++ APIs. Run qpdf --json-help for details on the format.\n"
<< "The manual has more in-depth information about the json representation\n"
<< "and certain compatibility guarantees that qpdf provides.\n"
<< "\n"
<< "The --raw-stream-data and --filtered-stream-data options are ignored\n"
<< "unless --show-object is given. Either of these options will cause the\n"
<< "stream data to be written to standard output.\n"
<< "\n"
<< "If --filtered-stream-data is given and --normalize-content=y is also\n"
<< "given, qpdf will attempt to normalize the stream data as if it is a\n"
<< "page content stream. This attempt will be made even if it is not a\n"
<< "page content stream, in which case it will produce unusable results.\n"
<< "\n"
<< "Ordinarily, qpdf exits with a status of 0 on success or a status of 2\n"
<< "if any errors occurred. If there were warnings but not errors, qpdf\n"
<< "exits with a status of 3. If warnings would have been issued but --no-warn\n"
<< "was given, an exit status of 3 is still used.\n";
}
void
ArgParser::argCompletionBash()
{
std::cout << "complete -o bashdefault -o default -o nospace"
<< " -C " << argv[0] << " " << whoami << std::endl;
// Put output before error so calling from zsh works properly
std::string path = argv[0];
size_t slash = path.find('/');
if ((slash != 0) && (slash != std::string::npos))
{
std::cerr << "WARNING: qpdf completion enabled"
<< " using relative path to qpdf" << std::endl;
}
}
void
ArgParser::argCompletionZsh()
{
std::cout << "autoload -U +X bashcompinit && bashcompinit && ";
argCompletionBash();
}
void
ArgParser::argJsonHelp()
{
// Make sure the output looks right on an 80-column display.
// 1 2 3 4 5 6 7 8
// 12345678901234567890123456789012345678901234567890123456789012345678901234567890
std::cout
<< "The json block below contains the same structure with the same keys as the"
<< std::endl
<< "json generated by qpdf. In the block below, the values are descriptions of"
<< std::endl
<< "the meanings of those entries. The specific contract guaranteed by qpdf in"
<< std::endl
<< "its json representation is explained in more detail in the manual. You can"
<< std::endl
<< "specify a subset of top-level keys when you invoke qpdf, but the \"version\""
<< std::endl
<< "and \"parameters\" keys will always be present."
<< std::endl
<< std::endl
<< json_schema().unparse()
<< std::endl;
}
void
ArgParser::argPassword(char* parameter)
{
o.password = parameter;
}
void
ArgParser::argEmpty()
{
o.infilename = "";
}
void
ArgParser::argLinearize()
{
o.linearize = true;
}
void
ArgParser::argEncrypt()
{
++cur_arg;
if (cur_arg + 3 > argc)
{
if (this->bash_completion)
{
if (cur_arg == argc)
{
this->completions.insert("user-password");
}
else if (cur_arg + 1 == argc)
{
this->completions.insert("owner-password");
}
else if (cur_arg + 2 == argc)
{
this->completions.insert("40");
this->completions.insert("128");
this->completions.insert("256");
}
return;
}
else
{
usage("insufficient arguments to --encrypt");
}
}
o.user_password = argv[cur_arg++];
o.owner_password = argv[cur_arg++];
std::string len_str = argv[cur_arg];
if (len_str == "40")
{
o.keylen = 40;
this->option_table = &(this->encrypt40_option_table);
}
else if (len_str == "128")
{
o.keylen = 128;
this->option_table = &(this->encrypt128_option_table);
}
else if (len_str == "256")
{
o.keylen = 256;
o.use_aes = true;
this->option_table = &(this->encrypt256_option_table);
}
else
{
usage("encryption key length must be 40, 128, or 256");
}
}
void
ArgParser::argDecrypt()
{
o.decrypt = true;
o.encrypt = false;
o.copy_encryption = false;
}
void
ArgParser::argPasswordIsHexKey()
{
o.password_is_hex_key = true;
}
void
ArgParser::argSuppressPasswordRecovery()
{
o.suppress_password_recovery = true;
}
void
ArgParser::argPasswordMode(char* parameter)
{
if (strcmp(parameter, "bytes") == 0)
{
o.password_mode = pm_bytes;
}
else if (strcmp(parameter, "hex-bytes") == 0)
{
o.password_mode = pm_hex_bytes;
}
else if (strcmp(parameter, "unicode") == 0)
{
o.password_mode = pm_unicode;
}
else if (strcmp(parameter, "auto") == 0)
{
o.password_mode = pm_auto;
}
else
{
usage("invalid password-mode option");
}
}
void
ArgParser::argCopyEncryption(char* parameter)
{
o.encryption_file = parameter;
o.copy_encryption = true;
o.encrypt = false;
o.decrypt = false;
}
void
ArgParser::argEncryptionFilePassword(char* parameter)
{
o.encryption_file_password = parameter;
}
void
ArgParser::argCollate()
{
o.collate = true;
}
void
ArgParser::argPages()
{
++cur_arg;
o.page_specs = parsePagesOptions();
if (o.page_specs.empty())
{
usage("--pages: no page specifications given");
}
}
void
ArgParser::argUnderlay()
{
parseUnderOverlayOptions(&o.underlay);
}
void
ArgParser::argOverlay()
{
parseUnderOverlayOptions(&o.overlay);
}
void
ArgParser::argRotate(char* parameter)
{
parseRotationParameter(parameter);
}
void
ArgParser::argStreamData(char* parameter)
{
o.stream_data_set = true;
if (strcmp(parameter, "compress") == 0)
{
o.stream_data_mode = qpdf_s_compress;
}
else if (strcmp(parameter, "preserve") == 0)
{
o.stream_data_mode = qpdf_s_preserve;
}
else if (strcmp(parameter, "uncompress") == 0)
{
o.stream_data_mode = qpdf_s_uncompress;
}
else
{
// If this happens, it means streamDataChoices in
// ArgParser::initOptionTable is wrong.
usage("invalid stream-data option");
}
}
void
ArgParser::argCompressStreams(char* parameter)
{
o.compress_streams_set = true;
o.compress_streams = (strcmp(parameter, "y") == 0);
}
void
ArgParser::argDecodeLevel(char* parameter)
{
o.decode_level_set = true;
if (strcmp(parameter, "none") == 0)
{
o.decode_level = qpdf_dl_none;
}
else if (strcmp(parameter, "generalized") == 0)
{
o.decode_level = qpdf_dl_generalized;
}
else if (strcmp(parameter, "specialized") == 0)
{
o.decode_level = qpdf_dl_specialized;
}
else if (strcmp(parameter, "all") == 0)
{
o.decode_level = qpdf_dl_all;
}
else
{
// If this happens, it means decodeLevelChoices in
// ArgParser::initOptionTable is wrong.
usage("invalid option");
}
}
void
ArgParser::argNormalizeContent(char* parameter)
{
o.normalize_set = true;
o.normalize = (strcmp(parameter, "y") == 0);
}
void
ArgParser::argSuppressRecovery()
{
o.suppress_recovery = true;
}
void
ArgParser::argObjectStreams(char* parameter)
{
o.object_stream_set = true;
if (strcmp(parameter, "disable") == 0)
{
o.object_stream_mode = qpdf_o_disable;
}
else if (strcmp(parameter, "preserve") == 0)
{
o.object_stream_mode = qpdf_o_preserve;
}
else if (strcmp(parameter, "generate") == 0)
{
o.object_stream_mode = qpdf_o_generate;
}
else
{
// If this happens, it means objectStreamsChoices in
// ArgParser::initOptionTable is wrong.
usage("invalid object stream mode");
}
}
void
ArgParser::argIgnoreXrefStreams()
{
o.ignore_xref_streams = true;
}
void
ArgParser::argQdf()
{
o.qdf_mode = true;
}
void
ArgParser::argPreserveUnreferenced()
{
o.preserve_unreferenced_objects = true;
}
void
ArgParser::argPreserveUnreferencedResources()
{
o.preserve_unreferenced_page_resources = true;
}
void
ArgParser::argKeepFilesOpen(char* parameter)
{
o.keep_files_open_set = true;
o.keep_files_open = (strcmp(parameter, "y") == 0);
}
void
ArgParser::argKeepFilesOpenThreshold(char* parameter)
{
o.keep_files_open_threshold =
static_cast<size_t>(QUtil::string_to_int(parameter));
}
void
ArgParser::argNewlineBeforeEndstream()
{
o.newline_before_endstream = true;
}
void
ArgParser::argLinearizePass1(char* parameter)
{
o.linearize_pass1 = parameter;
}
void
ArgParser::argCoalesceContents()
{
o.coalesce_contents = true;
}
void
ArgParser::argFlattenAnnotations(char* parameter)
{
o.flatten_annotations = true;
if (strcmp(parameter, "screen") == 0)
{
o.flatten_annotations_forbidden |= an_no_view;
}
else if (strcmp(parameter, "print") == 0)
{
o.flatten_annotations_required |= an_print;
}
}
void
ArgParser::argGenerateAppearances()
{
o.generate_appearances = true;
}
void
ArgParser::argMinVersion(char* parameter)
{
o.min_version = parameter;
}
void
ArgParser::argForceVersion(char* parameter)
{
o.force_version = parameter;
}
void
ArgParser::argSplitPages(char* parameter)
{
int n = ((parameter == 0) ? 1 :
QUtil::string_to_int(parameter));
o.split_pages = n;
}
void
ArgParser::argVerbose()
{
o.verbose = true;
}
void
ArgParser::argProgress()
{
o.progress = true;
}
void
ArgParser::argNoWarn()
{
o.suppress_warnings = true;
}
void
ArgParser::argDeterministicId()
{
o.deterministic_id = true;
}
void
ArgParser::argStaticId()
{
o.static_id = true;
}
void
ArgParser::argStaticAesIv()
{
o.static_aes_iv = true;
}
void
ArgParser::argNoOriginalObjectIds()
{
o.suppress_original_object_id = true;
}
void
ArgParser::argShowEncryption()
{
o.show_encryption = true;
o.require_outfile = false;
}
void
ArgParser::argShowEncryptionKey()
{
o.show_encryption_key = true;
}
void
ArgParser::argCheckLinearization()
{
o.check_linearization = true;
o.require_outfile = false;
}
void
ArgParser::argShowLinearization()
{
o.show_linearization = true;
o.require_outfile = false;
}
void
ArgParser::argShowXref()
{
o.show_xref = true;
o.require_outfile = false;
}
void
ArgParser::argShowObject(char* parameter)
{
parse_object_id(parameter, o.show_trailer, o.show_obj, o.show_gen);
o.require_outfile = false;
}
void
ArgParser::argRawStreamData()
{
o.show_raw_stream_data = true;
}
void
ArgParser::argFilteredStreamData()
{
o.show_filtered_stream_data = true;
}
void
ArgParser::argShowNpages()
{
o.show_npages = true;
o.require_outfile = false;
}
void
ArgParser::argShowPages()
{
o.show_pages = true;
o.require_outfile = false;
}
void
ArgParser::argWithImages()
{
o.show_page_images = true;
}
void
ArgParser::argJson()
{
o.json = true;
o.require_outfile = false;
}
void
ArgParser::argJsonKey(char* parameter)
{
o.json_keys.insert(parameter);
}
void
ArgParser::argJsonObject(char* parameter)
{
o.json_objects.insert(parameter);
}
void
ArgParser::argCheck()
{
o.check = true;
o.require_outfile = false;
}
void
ArgParser::argOptimizeImages()
{
o.optimize_images = true;
}
void
ArgParser::argExternalizeInlineImages()
{
o.externalize_inline_images = true;
}
void
ArgParser::argKeepInlineImages()
{
o.keep_inline_images = true;
}
void
ArgParser::argRemovePageLabels()
{
o.remove_page_labels = true;
}
void
ArgParser::argOiMinWidth(char* parameter)
{
o.oi_min_width = QUtil::string_to_int(parameter);
}
void
ArgParser::argOiMinHeight(char* parameter)
{
o.oi_min_height = QUtil::string_to_int(parameter);
}
void
ArgParser::argOiMinArea(char* parameter)
{
o.oi_min_area = QUtil::string_to_int(parameter);
}
void
ArgParser::argIiMinBytes(char* parameter)
{
o.ii_min_bytes = QUtil::string_to_int(parameter);
}
void
ArgParser::arg40Print(char* parameter)
{
o.r2_print = (strcmp(parameter, "y") == 0);
}
void
ArgParser::arg40Modify(char* parameter)
{
o.r2_modify = (strcmp(parameter, "y") == 0);
}
void
ArgParser::arg40Extract(char* parameter)
{
o.r2_extract = (strcmp(parameter, "y") == 0);
}
void
ArgParser::arg40Annotate(char* parameter)
{
o.r2_annotate = (strcmp(parameter, "y") == 0);
}
void
ArgParser::arg128Accessibility(char* parameter)
{
o.r3_accessibility = (strcmp(parameter, "y") == 0);
}
void
ArgParser::arg128Extract(char* parameter)
{
o.r3_extract = (strcmp(parameter, "y") == 0);
}
void
ArgParser::arg128Print(char* parameter)
{
if (strcmp(parameter, "full") == 0)
{
o.r3_print = qpdf_r3p_full;
}
else if (strcmp(parameter, "low") == 0)
{
o.r3_print = qpdf_r3p_low;
}
else if (strcmp(parameter, "none") == 0)
{
o.r3_print = qpdf_r3p_none;
}
else
{
usage("invalid print option");
}
}
void
ArgParser::arg128Modify(char* parameter)
{
if (strcmp(parameter, "all") == 0)
{
o.r3_assemble = true;
o.r3_annotate_and_form = true;
o.r3_form_filling = true;
o.r3_modify_other = true;
}
else if (strcmp(parameter, "annotate") == 0)
{
o.r3_assemble = true;
o.r3_annotate_and_form = true;
o.r3_form_filling = true;
o.r3_modify_other = false;
}
else if (strcmp(parameter, "form") == 0)
{
o.r3_assemble = true;
o.r3_annotate_and_form = false;
o.r3_form_filling = true;
o.r3_modify_other = false;
}
else if (strcmp(parameter, "assembly") == 0)
{
o.r3_assemble = true;
o.r3_annotate_and_form = false;
o.r3_form_filling = false;
o.r3_modify_other = false;
}
else if (strcmp(parameter, "none") == 0)
{
o.r3_assemble = false;
o.r3_annotate_and_form = false;
o.r3_form_filling = false;
o.r3_modify_other = false;
}
else
{
usage("invalid modify option");
}
}
void
ArgParser::arg128ClearTextMetadata()
{
o.cleartext_metadata = true;
}
void
ArgParser::arg128Assemble(char* parameter)
{
o.r3_assemble = (strcmp(parameter, "y") == 0);
}
void
ArgParser::arg128Annotate(char* parameter)
{
o.r3_annotate_and_form = (strcmp(parameter, "y") == 0);
}
void
ArgParser::arg128Form(char* parameter)
{
o.r3_form_filling = (strcmp(parameter, "y") == 0);
}
void
ArgParser::arg128ModOther(char* parameter)
{
o.r3_modify_other = (strcmp(parameter, "y") == 0);
}
void
ArgParser::arg128UseAes(char* parameter)
{
o.use_aes = (strcmp(parameter, "y") == 0);
}
void
ArgParser::arg128ForceV4()
{
o.force_V4 = true;
}
void
ArgParser::arg256ForceR5()
{
o.force_R5 = true;
}
void
ArgParser::argEndEncrypt()
{
o.encrypt = true;
o.decrypt = false;
o.copy_encryption = false;
this->option_table = &(this->main_option_table);
}
void
ArgParser::argUOpositional(char* arg)
{
if (o.under_overlay->filename)
{
usage(o.under_overlay->which + " file already specified");
}
else
{
o.under_overlay->filename = arg;
}
}
void
ArgParser::argUOto(char* parameter)
{
parseNumrange(parameter, 0);
o.under_overlay->to_nr = parameter;
}
void
ArgParser::argUOfrom(char* parameter)
{
if (strlen(parameter))
{
parseNumrange(parameter, 0);
}
o.under_overlay->from_nr = parameter;
}
void
ArgParser::argUOrepeat(char* parameter)
{
if (strlen(parameter))
{
parseNumrange(parameter, 0);
}
o.under_overlay->repeat_nr = parameter;
}
void
ArgParser::argUOpassword(char* parameter)
{
o.under_overlay->password = parameter;
}
void
ArgParser::argEndUnderOverlay()
{
this->option_table = &(this->main_option_table);
if (0 == o.under_overlay->filename)
{
usage(o.under_overlay->which + " file not specified");
}
o.under_overlay = 0;
}
void
ArgParser::handleArgFileArguments()
{
// Support reading arguments from files. Create a new argv. Ensure
// that argv itself as well as all its contents are automatically
// deleted by using PointerHolder objects to back the pointers in
// argv.
new_argv.push_back(PointerHolder<char>(true, QUtil::copy_string(argv[0])));
for (int i = 1; i < argc; ++i)
{
char* argfile = 0;
if ((strlen(argv[i]) > 1) && (argv[i][0] == '@'))
{
try
{
argfile = 1 + argv[i];
if (strcmp(argfile, "-") != 0)
{
fclose(QUtil::safe_fopen(argfile, "rb"));
}
}
catch (std::runtime_error&)
{
// The file's not there; treating as regular option
argfile = 0;
}
}
if (argfile)
{
readArgsFromFile(1+argv[i]);
}
else
{
new_argv.push_back(
PointerHolder<char>(true, QUtil::copy_string(argv[i])));
}
}
argv_ph = PointerHolder<char*>(true, new char*[1+new_argv.size()]);
argv = argv_ph.getPointer();
for (size_t i = 0; i < new_argv.size(); ++i)
{
argv[i] = new_argv.at(i).getPointer();
}
argc = static_cast<int>(new_argv.size());
argv[argc] = 0;
}
void
ArgParser::handleBashArguments()
{
// Do a minimal job of parsing bash_line into arguments. This
// doesn't do everything the shell does (e.g. $(...), variable
// expansion, arithmetic, globs, etc.), but it should be good
// enough for purposes of handling completion. As we build up the
// new argv, we can't use this->new_argv because this code has to
// interoperate with @file arguments, so memory for both ways of
// fabricating argv has to be protected.
bool last_was_backslash = false;
enum { st_top, st_squote, st_dquote } state = st_top;
std::string arg;
for (std::string::iterator iter = bash_line.begin();
iter != bash_line.end(); ++iter)
{
char ch = (*iter);
if (last_was_backslash)
{
arg.append(1, ch);
last_was_backslash = false;
}
else if (ch == '\\')
{
last_was_backslash = true;
}
else
{
bool append = false;
switch (state)
{
case st_top:
if (QUtil::is_space(ch))
{
if (! arg.empty())
{
bash_argv.push_back(
PointerHolder<char>(
true, QUtil::copy_string(arg.c_str())));
arg.clear();
}
}
else if (ch == '"')
{
state = st_dquote;
}
else if (ch == '\'')
{
state = st_squote;
}
else
{
append = true;
}
break;
case st_squote:
if (ch == '\'')
{
state = st_top;
}
else
{
append = true;
}
break;
case st_dquote:
if (ch == '"')
{
state = st_top;
}
else
{
append = true;
}
break;
}
if (append)
{
arg.append(1, ch);
}
}
}
if (bash_argv.empty())
{
// This can't happen if properly invoked by bash, but ensure
// we have a valid argv[0] regardless.
bash_argv.push_back(
PointerHolder<char>(
true, QUtil::copy_string(argv[0])));
}
// Explicitly discard any non-space-terminated word. The "current
// word" is handled specially.
bash_argv_ph = PointerHolder<char*>(true, new char*[1+bash_argv.size()]);
argv = bash_argv_ph.getPointer();
for (size_t i = 0; i < bash_argv.size(); ++i)
{
argv[i] = bash_argv.at(i).getPointer();
}
argc = static_cast<int>(bash_argv.size());
argv[argc] = 0;
}
void usageExit(std::string const& msg)
{
std::cerr
<< std::endl
<< whoami << ": " << msg << std::endl
<< std::endl
<< "Usage: " << whoami << " [options] infile outfile" << std::endl
<< "For detailed help, run " << whoami << " --help" << std::endl
<< std::endl;
exit(EXIT_ERROR);
}
void
ArgParser::usage(std::string const& message)
{
if (this->bash_completion)
{
// This will cause bash to fall back to regular file completion.
exit(0);
}
else
{
usageExit(message);
}
}
static std::string show_bool(bool v)
{
return v ? "allowed" : "not allowed";
}
static std::string show_encryption_method(QPDF::encryption_method_e method)
{
std::string result = "unknown";
switch (method)
{
case QPDF::e_none:
result = "none";
break;
case QPDF::e_unknown:
result = "unknown";
break;
case QPDF::e_rc4:
result = "RC4";
break;
case QPDF::e_aes:
result = "AESv2";
break;
case QPDF::e_aesv3:
result = "AESv3";
break;
// no default so gcc will warn for missing case
}
return result;
}
static void show_encryption(QPDF& pdf, Options& o)
{
// Extract /P from /Encrypt
int R = 0;
int P = 0;
int V = 0;
QPDF::encryption_method_e stream_method = QPDF::e_unknown;
QPDF::encryption_method_e string_method = QPDF::e_unknown;
QPDF::encryption_method_e file_method = QPDF::e_unknown;
if (! pdf.isEncrypted(R, P, V,
stream_method, string_method, file_method))
{
std::cout << "File is not encrypted" << std::endl;
}
else
{
std::cout << "R = " << R << std::endl;
std::cout << "P = " << P << std::endl;
std::string user_password = pdf.getTrimmedUserPassword();
std::string encryption_key = pdf.getEncryptionKey();
std::cout << "User password = " << user_password << std::endl;
if (o.show_encryption_key)
{
std::cout << "Encryption key = "
<< QUtil::hex_encode(encryption_key) << std::endl;
}
std::cout << "extract for accessibility: "
<< show_bool(pdf.allowAccessibility()) << std::endl
<< "extract for any purpose: "
<< show_bool(pdf.allowExtractAll()) << std::endl
<< "print low resolution: "
<< show_bool(pdf.allowPrintLowRes()) << std::endl
<< "print high resolution: "
<< show_bool(pdf.allowPrintHighRes()) << std::endl
<< "modify document assembly: "
<< show_bool(pdf.allowModifyAssembly()) << std::endl
<< "modify forms: "
<< show_bool(pdf.allowModifyForm()) << std::endl
<< "modify annotations: "
<< show_bool(pdf.allowModifyAnnotation()) << std::endl
<< "modify other: "
<< show_bool(pdf.allowModifyOther()) << std::endl
<< "modify anything: "
<< show_bool(pdf.allowModifyAll()) << std::endl;
if (V >= 4)
{
std::cout << "stream encryption method: "
<< show_encryption_method(stream_method) << std::endl
<< "string encryption method: "
<< show_encryption_method(string_method) << std::endl
<< "file encryption method: "
<< show_encryption_method(file_method) << std::endl;
}
}
}
std::vector<int>
ArgParser::parseNumrange(char const* range, int max, bool throw_error)
{
try
{
return QUtil::parse_numrange(range, max);
}
catch (std::runtime_error& e)
{
if (throw_error)
{
throw(e);
}
else
{
usage(e.what());
}
}
return std::vector<int>();
}
std::vector<PageSpec>
ArgParser::parsePagesOptions()
{
std::vector<PageSpec> result;
while (1)
{
if ((cur_arg < argc) && (strcmp(argv[cur_arg], "--") == 0))
{
break;
}
if (cur_arg + 1 >= argc)
{
usage("insufficient arguments to --pages");
}
char const* file = argv[cur_arg++];
char const* password = 0;
char const* range = argv[cur_arg++];
if (strncmp(range, "--password=", 11) == 0)
{
// Oh, that's the password, not the range
if (cur_arg + 1 >= argc)
{
usage("insufficient arguments to --pages");
}
password = range + 11;
range = argv[cur_arg++];
}
// See if the user omitted the range entirely, in which case
// we assume "1-z".
bool range_omitted = false;
if (strcmp(range, "--") == 0)
{
// The filename or password was the last argument
QTC::TC("qpdf", "qpdf pages range omitted at end");
range_omitted = true;
}
else
{
try
{
parseNumrange(range, 0, true);
}
catch (std::runtime_error& e1)
{
// The range is invalid. Let's see if it's a file.
try
{
fclose(QUtil::safe_fopen(range, "rb"));
// Yup, it's a file.
QTC::TC("qpdf", "qpdf pages range omitted in middle");
range_omitted = true;
}
catch (std::runtime_error&)
{
// Give the range error
usage(e1.what());
}
}
}
if (range_omitted)
{
--cur_arg;
range = "1-z";
}
result.push_back(PageSpec(file, password, range));
}
return result;
}
void
ArgParser::parseUnderOverlayOptions(UnderOverlay* uo)
{
o.under_overlay = uo;
this->option_table = &(this->under_overlay_option_table);
}
QPDFPageData::QPDFPageData(std::string const& filename,
QPDF* qpdf,
char const* range) :
filename(filename),
qpdf(qpdf),
orig_pages(qpdf->getAllPages())
{
try
{
this->selected_pages =
QUtil::parse_numrange(range, this->orig_pages.size());
}
catch (std::runtime_error& e)
{
usageExit("parsing numeric range for " + filename + ": " + e.what());
}
}
QPDFPageData::QPDFPageData(QPDFPageData const& other, int page) :
filename(other.filename),
qpdf(other.qpdf),
orig_pages(other.orig_pages)
{
this->selected_pages.push_back(page);
}
static void parse_version(std::string const& full_version_string,
std::string& version, int& extension_level)
{
PointerHolder<char> vp(true, QUtil::copy_string(full_version_string));
char* v = vp.getPointer();
char* p1 = strchr(v, '.');
char* p2 = (p1 ? strchr(1 + p1, '.') : 0);
if (p2 && *(p2 + 1))
{
*p2++ = '\0';
extension_level = QUtil::string_to_int(p2);
}
version = v;
}
void
ArgParser::readArgsFromFile(char const* filename)
{
std::list<std::string> lines;
if (strcmp(filename, "-") == 0)
{
QTC::TC("qpdf", "qpdf read args from stdin");
lines = QUtil::read_lines_from_file(std::cin);
}
else
{
QTC::TC("qpdf", "qpdf read args from file");
lines = QUtil::read_lines_from_file(filename);
}
for (std::list<std::string>::iterator iter = lines.begin();
iter != lines.end(); ++iter)
{
new_argv.push_back(
PointerHolder<char>(true, QUtil::copy_string((*iter).c_str())));
}
}
void
ArgParser::handleHelpArgs()
{
// Handle special-case informational options that are only
// available as the sole option.
if (argc != 2)
{
return;
}
char* arg = argv[1];
if (*arg != '-')
{
return;
}
++arg;
if (*arg == '-')
{
++arg;
}
if (! *arg)
{
return;
}
if (this->help_option_table.count(arg))
{
(this->*(this->help_option_table[arg].bare_arg_handler))();
exit(0);
}
}
void
ArgParser::parseRotationParameter(std::string const& parameter)
{
std::string angle_str;
std::string range;
size_t colon = parameter.find(':');
int relative = 0;
if (colon != std::string::npos)
{
if (colon > 0)
{
angle_str = parameter.substr(0, colon);
}
if (colon + 1 < parameter.length())
{
range = parameter.substr(colon + 1);
}
}
else
{
angle_str = parameter;
}
if (angle_str.length() > 0)
{
char first = angle_str.at(0);
if ((first == '+') || (first == '-'))
{
relative = ((first == '+') ? 1 : -1);
angle_str = angle_str.substr(1);
}
else if (! QUtil::is_digit(angle_str.at(0)))
{
angle_str = "";
}
}
if (range.empty())
{
range = "1-z";
}
bool range_valid = false;
try
{
parseNumrange(range.c_str(), 0, true);
range_valid = true;
}
catch (std::runtime_error const&)
{
// ignore
}
if (range_valid &&
((angle_str == "90") || (angle_str == "180") || (angle_str == "270")))
{
int angle = QUtil::string_to_int(angle_str.c_str());
if (relative == -1)
{
angle = -angle;
}
o.rotations[range] = RotationSpec(angle, (relative != 0));
}
else
{
usage("invalid parameter to rotate: " + parameter);
}
}
void
ArgParser::checkCompletion()
{
// See if we're being invoked from bash completion.
std::string bash_point_env;
if (QUtil::get_env("COMP_LINE", &bash_line) &&
QUtil::get_env("COMP_POINT", &bash_point_env))
{
int p = QUtil::string_to_int(bash_point_env.c_str());
if ((p > 0) && (p <= static_cast<int>(bash_line.length())))
{
// Truncate the line. We ignore everything at or after the
// cursor for completion purposes.
bash_line = bash_line.substr(0, p);
}
// Set bash_cur and bash_prev based on bash_line rather than
// relying on argv. This enables us to use bashcompinit to get
// completion in zsh too since bashcompinit sets COMP_LINE and
// COMP_POINT but doesn't invoke the command with options like
// bash does.
// p is equal to length of the string. Walk backwards looking
// for the first separator. bash_cur is everything after the
// last separator, possibly empty.
char sep(0);
while (--p > 0)
{
char ch = bash_line.at(p);
if ((ch == ' ') || (ch == '=') || (ch == ':'))
{
sep = ch;
break;
}
}
bash_cur = bash_line.substr(1+p, std::string::npos);
if ((sep == ':') || (sep == '='))
{
// Bash sets prev to the non-space separator if any.
// Actually, if there are multiple separators in a row,
// they are all included in prev, but that detail is not
// important to us and not worth coding.
bash_prev = bash_line.substr(p, 1);
}
else
{
// Go back to the last separator and set prev based on
// that.
int p1 = p;
while (--p1 > 0)
{
char ch = bash_line.at(p1);
if ((ch == ' ') || (ch == ':') || (ch == '='))
{
bash_prev = bash_line.substr(p1 + 1, p - p1 - 1);
break;
}
}
}
if (bash_prev.empty())
{
bash_prev = bash_line.substr(0, p);
}
if (argc == 1)
{
// This is probably zsh using bashcompinit. There are a
// few differences in the expected output.
zsh_completion = true;
}
handleBashArguments();
bash_completion = true;
}
}
void
ArgParser::parseOptions()
{
checkCompletion();
if (! this->bash_completion)
{
handleHelpArgs();
}
handleArgFileArguments();
for (cur_arg = 1; cur_arg < argc; ++cur_arg)
{
char* arg = argv[cur_arg];
if (strcmp(arg, "--") == 0)
{
// Special case for -- option, which is used to break out
// of subparsers.
OptionEntry& oe = (*this->option_table)["--"];
if (oe.bare_arg_handler)
{
(this->*(oe.bare_arg_handler))();
}
}
else if ((arg[0] == '-') && (strcmp(arg, "-") != 0))
{
++arg;
if (arg[0] == '-')
{
// Be lax about -arg vs --arg
++arg;
}
char* parameter = 0;
if (strlen(arg) > 0)
{
// Prevent --=something from being treated as an empty
// arg since the empty string in the option table is
// for positional arguments.
parameter = const_cast<char*>(strchr(1 + arg, '='));
}
if (parameter)
{
*parameter++ = 0;
}
std::string arg_s(arg);
if (arg_s.empty() ||
(arg_s.at(0) == '-') ||
(0 == this->option_table->count(arg_s)))
{
usage(std::string("unknown option --") + arg);
}
OptionEntry& oe = (*this->option_table)[arg_s];
if ((oe.parameter_needed && (0 == parameter)) ||
((! oe.choices.empty() &&
((0 == parameter) ||
(0 == oe.choices.count(parameter))))))
{
std::string message =
"--" + arg_s + " must be given as --" + arg_s + "=";
if (! oe.choices.empty())
{
QTC::TC("qpdf", "qpdf required choices");
message += "{";
for (std::set<std::string>::iterator iter =
oe.choices.begin();
iter != oe.choices.end(); ++iter)
{
if (iter != oe.choices.begin())
{
message += ",";
}
message += *iter;
}
message += "}";
}
else if (! oe.parameter_name.empty())
{
QTC::TC("qpdf", "qpdf required parameter");
message += oe.parameter_name;
}
else
{
// should not be possible
message += "option";
}
usage(message);
}
if (oe.bare_arg_handler)
{
(this->*(oe.bare_arg_handler))();
}
else if (oe.param_arg_handler)
{
(this->*(oe.param_arg_handler))(parameter);
}
}
else if (0 != this->option_table->count(""))
{
// The empty string maps to the positional argument
// handler.
OptionEntry& oe = (*this->option_table)[""];
if (oe.param_arg_handler)
{
(this->*(oe.param_arg_handler))(arg);
}
}
else
{
usage(std::string("unknown argument ") + arg);
}
}
if (this->bash_completion)
{
handleCompletion();
}
else
{
doFinalChecks();
}
}
void
ArgParser::doFinalChecks()
{
if (this->option_table != &(this->main_option_table))
{
usage("missing -- at end of options");
}
if (o.infilename == 0)
{
usage("an input file name is required");
}
else if (o.require_outfile && (o.outfilename == 0))
{
usage("an output file name is required; use - for standard output");
}
else if ((! o.require_outfile) && (o.outfilename != 0))
{
usage("no output file may be given for this option");
}
if (o.optimize_images && (! o.keep_inline_images))
{
o.externalize_inline_images = true;
}
if (o.require_outfile && (strcmp(o.outfilename, "-") == 0))
{
if (o.split_pages)
{
usage("--split-pages may not be used when"
" writing to standard output");
}
if (o.verbose)
{
usage("--verbose may not be used when"
" writing to standard output");
}
if (o.progress)
{
usage("--progress may not be used when"
" writing to standard output");
}
}
if (QUtil::same_file(o.infilename, o.outfilename))
{
QTC::TC("qpdf", "qpdf same file error");
usage("input file and output file are the same;"
" this would cause input file to be lost");
}
}
void
ArgParser::addChoicesToCompletions(std::string const& option,
std::string const& extra_prefix)
{
if (this->option_table->count(option) != 0)
{
OptionEntry& oe = (*this->option_table)[option];
for (std::set<std::string>::iterator iter = oe.choices.begin();
iter != oe.choices.end(); ++iter)
{
completions.insert(extra_prefix + *iter);
}
}
}
void
ArgParser::addOptionsToCompletions()
{
for (std::map<std::string, OptionEntry>::iterator iter =
this->option_table->begin();
iter != this->option_table->end(); ++iter)
{
std::string const& arg = (*iter).first;
OptionEntry& oe = (*iter).second;
std::string base = "--" + arg;
if (oe.param_arg_handler)
{
completions.insert(base + "=");
}
if (! oe.parameter_needed)
{
completions.insert(base);
}
}
}
void
ArgParser::handleCompletion()
{
std::string extra_prefix;
if (this->completions.empty())
{
// Detect --option=... Bash treats the = as a word separator.
std::string choice_option;
if (bash_cur.empty() && (bash_prev.length() > 2) &&
(bash_prev.at(0) == '-') &&
(bash_prev.at(1) == '-') &&
(bash_line.at(bash_line.length() - 1) == '='))
{
choice_option = bash_prev.substr(2, std::string::npos);
}
else if ((bash_prev == "=") &&
(bash_line.length() > (bash_cur.length() + 1)))
{
// We're sitting at --option=x. Find previous option.
size_t end_mark = bash_line.length() - bash_cur.length() - 1;
char before_cur = bash_line.at(end_mark);
if (before_cur == '=')
{
size_t space = bash_line.find_last_of(' ', end_mark);
if (space != std::string::npos)
{
std::string candidate =
bash_line.substr(space + 1, end_mark - space - 1);
if ((candidate.length() > 2) &&
(candidate.at(0) == '-') &&
(candidate.at(1) == '-'))
{
choice_option =
candidate.substr(2, std::string::npos);
}
}
}
}
if (! choice_option.empty())
{
if (zsh_completion)
{
// zsh wants --option=choice rather than just choice
extra_prefix = "--" + choice_option + "=";
}
addChoicesToCompletions(choice_option, extra_prefix);
}
else if ((! bash_cur.empty()) && (bash_cur.at(0) == '-'))
{
addOptionsToCompletions();
if (this->argc == 1)
{
// Help options are valid only by themselves.
for (std::map<std::string, OptionEntry>::iterator iter =
this->help_option_table.begin();
iter != this->help_option_table.end(); ++iter)
{
this->completions.insert("--" + (*iter).first);
}
}
}
}
std::string prefix = extra_prefix + bash_cur;
for (std::set<std::string>::iterator iter = completions.begin();
iter != completions.end(); ++iter)
{
if (prefix.empty() ||
((*iter).substr(0, prefix.length()) == prefix))
{
std::cout << *iter << std::endl;
}
}
exit(0);
}
static void set_qpdf_options(QPDF& pdf, Options& o)
{
if (o.ignore_xref_streams)
{
pdf.setIgnoreXRefStreams(true);
}
if (o.suppress_recovery)
{
pdf.setAttemptRecovery(false);
}
if (o.password_is_hex_key)
{
pdf.setPasswordIsHexKey(true);
}
if (o.suppress_warnings)
{
pdf.setSuppressWarnings(true);
}
}
static void do_check(QPDF& pdf, Options& o, int& exit_code)
{
// Code below may set okay to false but not to true.
// We assume okay until we prove otherwise but may
// continue to perform additional checks after finding
// errors.
bool okay = true;
std::cout << "checking " << o.infilename << std::endl;
try
{
int extension_level = pdf.getExtensionLevel();
std::cout << "PDF Version: " << pdf.getPDFVersion();
if (extension_level > 0)
{
std::cout << " extension level "
<< pdf.getExtensionLevel();
}
std::cout << std::endl;
show_encryption(pdf, o);
if (pdf.isLinearized())
{
std::cout << "File is linearized\n";
if (! pdf.checkLinearization())
{
// any errors are reported by checkLinearization()
okay = false;
}
}
else
{
std::cout << "File is not linearized\n";
}
// Write the file no nowhere, uncompressing
// streams. This causes full file traversal and
// decoding of all streams we can decode.
QPDFWriter w(pdf);
Pl_Discard discard;
w.setOutputPipeline(&discard);
w.setDecodeLevel(qpdf_dl_all);
w.write();
// Parse all content streams
QPDFPageDocumentHelper dh(pdf);
std::vector<QPDFPageObjectHelper> pages = dh.getAllPages();
DiscardContents discard_contents;
int pageno = 0;
for (std::vector<QPDFPageObjectHelper>::iterator iter =
pages.begin();
iter != pages.end(); ++iter)
{
QPDFPageObjectHelper& page(*iter);
++pageno;
try
{
page.parsePageContents(&discard_contents);
}
catch (QPDFExc& e)
{
okay = false;
std::cout << "page " << pageno << ": "
<< e.what() << std::endl;
}
}
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
okay = false;
}
if (okay)
{
if (! pdf.getWarnings().empty())
{
exit_code = EXIT_WARNING;
}
else
{
std::cout << "No syntax or stream encoding errors"
<< " found; the file may still contain"
<< std::endl
<< "errors that qpdf cannot detect"
<< std::endl;
}
}
else
{
exit_code = EXIT_ERROR;
}
}
static void do_show_obj(QPDF& pdf, Options& o, int& exit_code)
{
QPDFObjectHandle obj;
if (o.show_trailer)
{
obj = pdf.getTrailer();
}
else
{
obj = pdf.getObjectByID(o.show_obj, o.show_gen);
}
if (obj.isStream())
{
if (o.show_raw_stream_data || o.show_filtered_stream_data)
{
bool filter = o.show_filtered_stream_data;
if (filter &&
(! obj.pipeStreamData(0, 0, qpdf_dl_all)))
{
QTC::TC("qpdf", "qpdf unable to filter");
std::cerr << "Unable to filter stream data."
<< std::endl;
exit_code = EXIT_ERROR;
}
else
{
QUtil::binary_stdout();
Pl_StdioFile out("stdout", stdout);
obj.pipeStreamData(
&out,
(filter && o.normalize) ? qpdf_ef_normalize : 0,
filter ? qpdf_dl_all : qpdf_dl_none);
}
}
else
{
std::cout
<< "Object is stream. Dictionary:" << std::endl
<< obj.getDict().unparseResolved() << std::endl;
}
}
else
{
std::cout << obj.unparseResolved() << std::endl;
}
}
static void do_show_pages(QPDF& pdf, Options& o)
{
QPDFPageDocumentHelper dh(pdf);
std::vector<QPDFPageObjectHelper> pages = dh.getAllPages();
int pageno = 0;
for (std::vector<QPDFPageObjectHelper>::iterator iter = pages.begin();
iter != pages.end(); ++iter)
{
QPDFPageObjectHelper& ph(*iter);
QPDFObjectHandle page = ph.getObjectHandle();
++pageno;
std::cout << "page " << pageno << ": "
<< page.getObjectID() << " "
<< page.getGeneration() << " R" << std::endl;
if (o.show_page_images)
{
std::map<std::string, QPDFObjectHandle> images =
ph.getPageImages();
if (! images.empty())
{
std::cout << " images:" << std::endl;
for (std::map<std::string,
QPDFObjectHandle>::iterator
iter = images.begin();
iter != images.end(); ++iter)
{
std::string const& name = (*iter).first;
QPDFObjectHandle image = (*iter).second;
QPDFObjectHandle dict = image.getDict();
int width =
dict.getKey("/Width").getIntValue();
int height =
dict.getKey("/Height").getIntValue();
std::cout << " " << name << ": "
<< image.unparse()
<< ", " << width << " x " << height
<< std::endl;
}
}
}
std::cout << " content:" << std::endl;
std::vector<QPDFObjectHandle> content =
ph.getPageContents();
for (std::vector<QPDFObjectHandle>::iterator iter =
content.begin();
iter != content.end(); ++iter)
{
std::cout << " " << (*iter).unparse() << std::endl;
}
}
}
static void do_json_objects(QPDF& pdf, Options& o, JSON& j)
{
// Add all objects. Do this first before other code below modifies
// things by doing stuff like calling
// pushInheritedAttributesToPage.
bool all_objects = o.json_objects.empty();
std::set<QPDFObjGen> wanted_og;
for (std::set<std::string>::iterator iter = o.json_objects.begin();
iter != o.json_objects.end(); ++iter)
{
bool trailer;
int obj = 0;
int gen = 0;
parse_object_id(*iter, trailer, obj, gen);
if (obj)
{
wanted_og.insert(QPDFObjGen(obj, gen));
}
}
JSON j_objects = j.addDictionaryMember("objects", JSON::makeDictionary());
if (all_objects || o.json_objects.count("trailer"))
{
j_objects.addDictionaryMember(
"trailer", pdf.getTrailer().getJSON(true));
}
std::vector<QPDFObjectHandle> objects = pdf.getAllObjects();
for (std::vector<QPDFObjectHandle>::iterator iter = objects.begin();
iter != objects.end(); ++iter)
{
if (all_objects || wanted_og.count((*iter).getObjGen()))
{
j_objects.addDictionaryMember(
(*iter).unparse(), (*iter).getJSON(true));
}
}
}
static void do_json_pages(QPDF& pdf, Options& o, JSON& j)
{
JSON j_pages = j.addDictionaryMember("pages", JSON::makeArray());
QPDFPageDocumentHelper pdh(pdf);
QPDFPageLabelDocumentHelper pldh(pdf);
QPDFOutlineDocumentHelper odh(pdf);
pdh.pushInheritedAttributesToPage();
std::vector<QPDFPageObjectHelper> pages = pdh.getAllPages();
size_t pageno = 0;
for (std::vector<QPDFPageObjectHelper>::iterator iter = pages.begin();
iter != pages.end(); ++iter, ++pageno)
{
JSON j_page = j_pages.addArrayElement(JSON::makeDictionary());
QPDFPageObjectHelper& ph(*iter);
QPDFObjectHandle page = ph.getObjectHandle();
j_page.addDictionaryMember("object", page.getJSON());
JSON j_images = j_page.addDictionaryMember(
"images", JSON::makeArray());
std::map<std::string, QPDFObjectHandle> images =
ph.getPageImages();
for (std::map<std::string, QPDFObjectHandle>::iterator iter =
images.begin();
iter != images.end(); ++iter)
{
JSON j_image = j_images.addArrayElement(JSON::makeDictionary());
j_image.addDictionaryMember(
"name", JSON::makeString((*iter).first));
QPDFObjectHandle image = (*iter).second;
QPDFObjectHandle dict = image.getDict();
j_image.addDictionaryMember("object", image.getJSON());
j_image.addDictionaryMember(
"width", dict.getKey("/Width").getJSON());
j_image.addDictionaryMember(
"height", dict.getKey("/Height").getJSON());
j_image.addDictionaryMember(
"colorspace", dict.getKey("/ColorSpace").getJSON());
j_image.addDictionaryMember(
"bitspercomponent", dict.getKey("/BitsPerComponent").getJSON());
QPDFObjectHandle filters = dict.getKey("/Filter").wrapInArray();
j_image.addDictionaryMember(
"filter", filters.getJSON());
QPDFObjectHandle decode_parms = dict.getKey("/DecodeParms");
QPDFObjectHandle dp_array;
if (decode_parms.isArray())
{
dp_array = decode_parms;
}
else
{
dp_array = QPDFObjectHandle::newArray();
for (int i = 0; i < filters.getArrayNItems(); ++i)
{
dp_array.appendItem(decode_parms);
}
}
j_image.addDictionaryMember("decodeparms", dp_array.getJSON());
j_image.addDictionaryMember(
"filterable",
JSON::makeBool(
image.pipeStreamData(0, 0, o.decode_level, true)));
}
j_page.addDictionaryMember("images", j_images);
JSON j_contents = j_page.addDictionaryMember(
"contents", JSON::makeArray());
std::vector<QPDFObjectHandle> content = ph.getPageContents();
for (std::vector<QPDFObjectHandle>::iterator iter = content.begin();
iter != content.end(); ++iter)
{
j_contents.addArrayElement((*iter).getJSON());
}
j_page.addDictionaryMember(
"label", pldh.getLabelForPage(pageno).getJSON());
JSON j_outlines = j_page.addDictionaryMember(
"outlines", JSON::makeArray());
std::list<QPDFOutlineObjectHelper> outlines =
odh.getOutlinesForPage(page.getObjGen());
for (std::list<QPDFOutlineObjectHelper>::iterator oiter =
outlines.begin();
oiter != outlines.end(); ++oiter)
{
JSON j_outline = j_outlines.addArrayElement(JSON::makeDictionary());
j_outline.addDictionaryMember(
"object", (*oiter).getObjectHandle().getJSON());
j_outline.addDictionaryMember(
"title", JSON::makeString((*oiter).getTitle()));
j_outline.addDictionaryMember(
"dest", (*oiter).getDest().getJSON(true));
}
j_page.addDictionaryMember("pageposfrom1", JSON::makeInt(1 + pageno));
}
}
static void do_json_page_labels(QPDF& pdf, Options& o, JSON& j)
{
JSON j_labels = j.addDictionaryMember("pagelabels", JSON::makeArray());
QPDFPageLabelDocumentHelper pldh(pdf);
QPDFPageDocumentHelper pdh(pdf);
std::vector<QPDFPageObjectHelper> pages = pdh.getAllPages();
if (pldh.hasPageLabels())
{
std::vector<QPDFObjectHandle> labels;
pldh.getLabelsForPageRange(0, pages.size() - 1, 0, labels);
for (std::vector<QPDFObjectHandle>::iterator iter = labels.begin();
iter != labels.end(); ++iter)
{
std::vector<QPDFObjectHandle>::iterator next = iter;
++next;
if (next == labels.end())
{
// This can't happen, so ignore it. This could only
// happen if getLabelsForPageRange somehow returned an
// odd number of items.
break;
}
JSON j_label = j_labels.addArrayElement(JSON::makeDictionary());
j_label.addDictionaryMember("index", (*iter).getJSON());
++iter;
j_label.addDictionaryMember("label", (*iter).getJSON());
}
}
}
static void add_outlines_to_json(
std::list<QPDFOutlineObjectHelper> outlines, JSON& j,
std::map<QPDFObjGen, int>& page_numbers)
{
for (std::list<QPDFOutlineObjectHelper>::iterator iter = outlines.begin();
iter != outlines.end(); ++iter)
{
QPDFOutlineObjectHelper& ol = *iter;
JSON jo = j.addArrayElement(JSON::makeDictionary());
jo.addDictionaryMember("object", ol.getObjectHandle().getJSON());
jo.addDictionaryMember("title", JSON::makeString(ol.getTitle()));
jo.addDictionaryMember("dest", ol.getDest().getJSON(true));
jo.addDictionaryMember("open", JSON::makeBool(ol.getCount() >= 0));
QPDFObjectHandle page = ol.getDestPage();
JSON j_destpage = JSON::makeNull();
if (page.isIndirect())
{
QPDFObjGen og = page.getObjGen();
if (page_numbers.count(og))
{
j_destpage = JSON::makeInt(page_numbers[og]);
}
}
jo.addDictionaryMember("destpageposfrom1", j_destpage);
JSON j_kids = jo.addDictionaryMember("kids", JSON::makeArray());
add_outlines_to_json(ol.getKids(), j_kids, page_numbers);
}
}
static void do_json_outlines(QPDF& pdf, Options& o, JSON& j)
{
std::map<QPDFObjGen, int> page_numbers;
QPDFPageDocumentHelper dh(pdf);
std::vector<QPDFPageObjectHelper> pages = dh.getAllPages();
int n = 0;
for (std::vector<QPDFPageObjectHelper>::iterator iter = pages.begin();
iter != pages.end(); ++iter)
{
QPDFObjectHandle oh = (*iter).getObjectHandle();
page_numbers[oh.getObjGen()] = ++n;
}
JSON j_outlines = j.addDictionaryMember(
"outlines", JSON::makeArray());
QPDFOutlineDocumentHelper odh(pdf);
add_outlines_to_json(odh.getTopLevelOutlines(), j_outlines, page_numbers);
}
static void do_json_acroform(QPDF& pdf, Options& o, JSON& j)
{
JSON j_acroform = j.addDictionaryMember(
"acroform", JSON::makeDictionary());
QPDFAcroFormDocumentHelper afdh(pdf);
j_acroform.addDictionaryMember(
"hasacroform",
JSON::makeBool(afdh.hasAcroForm()));
j_acroform.addDictionaryMember(
"needappearances",
JSON::makeBool(afdh.getNeedAppearances()));
JSON j_fields = j_acroform.addDictionaryMember(
"fields", JSON::makeArray());
QPDFPageDocumentHelper pdh(pdf);
std::vector<QPDFPageObjectHelper> pages = pdh.getAllPages();
int pagepos1 = 0;
for (std::vector<QPDFPageObjectHelper>::iterator page_iter =
pages.begin();
page_iter != pages.end(); ++page_iter)
{
++pagepos1;
std::vector<QPDFAnnotationObjectHelper> annotations =
afdh.getWidgetAnnotationsForPage(*page_iter);
for (std::vector<QPDFAnnotationObjectHelper>::iterator annot_iter =
annotations.begin();
annot_iter != annotations.end(); ++annot_iter)
{
QPDFAnnotationObjectHelper& aoh = *annot_iter;
QPDFFormFieldObjectHelper ffh =
afdh.getFieldForAnnotation(aoh);
JSON j_field = j_fields.addArrayElement(
JSON::makeDictionary());
j_field.addDictionaryMember(
"object",
ffh.getObjectHandle().getJSON());
j_field.addDictionaryMember(
"parent",
ffh.getObjectHandle().getKey("/Parent").getJSON());
j_field.addDictionaryMember(
"pageposfrom1",
JSON::makeInt(pagepos1));
j_field.addDictionaryMember(
"fieldtype",
JSON::makeString(ffh.getFieldType()));
j_field.addDictionaryMember(
"fieldflags",
JSON::makeInt(ffh.getFlags()));
j_field.addDictionaryMember(
"fullname",
JSON::makeString(ffh.getFullyQualifiedName()));
j_field.addDictionaryMember(
"partialname",
JSON::makeString(ffh.getPartialName()));
j_field.addDictionaryMember(
"alternativename",
JSON::makeString(ffh.getAlternativeName()));
j_field.addDictionaryMember(
"mappingname",
JSON::makeString(ffh.getMappingName()));
j_field.addDictionaryMember(
"value",
ffh.getValue().getJSON());
j_field.addDictionaryMember(
"defaultvalue",
ffh.getDefaultValue().getJSON());
j_field.addDictionaryMember(
"quadding",
JSON::makeInt(ffh.getQuadding()));
j_field.addDictionaryMember(
"ischeckbox",
JSON::makeBool(ffh.isCheckbox()));
j_field.addDictionaryMember(
"isradiobutton",
JSON::makeBool(ffh.isRadioButton()));
j_field.addDictionaryMember(
"ischoice",
JSON::makeBool(ffh.isChoice()));
j_field.addDictionaryMember(
"istext",
JSON::makeBool(ffh.isText()));
JSON j_choices = j_field.addDictionaryMember(
"choices", JSON::makeArray());
std::vector<std::string> choices = ffh.getChoices();
for (std::vector<std::string>::iterator iter = choices.begin();
iter != choices.end(); ++iter)
{
j_choices.addArrayElement(JSON::makeString(*iter));
}
JSON j_annot = j_field.addDictionaryMember(
"annotation", JSON::makeDictionary());
j_annot.addDictionaryMember(
"object",
aoh.getObjectHandle().getJSON());
j_annot.addDictionaryMember(
"appearancestate",
JSON::makeString(aoh.getAppearanceState()));
j_annot.addDictionaryMember(
"annotationflags",
JSON::makeInt(aoh.getFlags()));
}
}
}
static void do_json(QPDF& pdf, Options& o)
{
JSON j = JSON::makeDictionary();
// This version is updated every time a non-backward-compatible
// change is made to the JSON format. Clients of the JSON are to
// ignore unrecognized keys, so we only update the version of a
// key disappears or if its value changes meaning.
j.addDictionaryMember("version", JSON::makeInt(1));
JSON j_params = j.addDictionaryMember(
"parameters", JSON::makeDictionary());
std::string decode_level_str;
switch (o.decode_level)
{
case qpdf_dl_none:
decode_level_str = "none";
break;
case qpdf_dl_generalized:
decode_level_str = "generalized";
break;
case qpdf_dl_specialized:
decode_level_str = "specialized";
break;
case qpdf_dl_all:
decode_level_str = "all";
break;
}
j_params.addDictionaryMember(
"decodelevel", JSON::makeString(decode_level_str));
bool all_keys = o.json_keys.empty();
// The list of selectable top-level keys id duplicated in three
// places: json_schema, do_json, and initOptionTable.
if (all_keys || o.json_keys.count("objects"))
{
do_json_objects(pdf, o, j);
}
if (all_keys || o.json_keys.count("pages"))
{
do_json_pages(pdf, o, j);
}
if (all_keys || o.json_keys.count("pagelabels"))
{
do_json_page_labels(pdf, o, j);
}
if (all_keys || o.json_keys.count("outlines"))
{
do_json_outlines(pdf, o, j);
}
if (all_keys || o.json_keys.count("acroform"))
{
do_json_acroform(pdf, o, j);
}
// Check against schema
JSON schema = json_schema(&o.json_keys);
std::list<std::string> errors;
if (! j.checkSchema(schema, errors))
{
std::cerr
<< whoami << " didn't create JSON that complies with its own\n\
rules. Please report this as a bug at\n\
https://github.com/qpdf/qpdf/issues/new\n\
ideally with the file that caused the error and the output below. Thanks!\n\
\n";
for (std::list<std::string>::iterator iter = errors.begin();
iter != errors.end(); ++iter)
{
std::cerr << (*iter) << std::endl;
}
}
std::cout << j.unparse() << std::endl;
}
static void do_inspection(QPDF& pdf, Options& o)
{
int exit_code = 0;
if (o.check)
{
do_check(pdf, o, exit_code);
}
if (o.json)
{
do_json(pdf, o);
}
if (o.show_npages)
{
QTC::TC("qpdf", "qpdf npages");
std::cout << pdf.getRoot().getKey("/Pages").
getKey("/Count").getIntValue() << std::endl;
}
if (o.show_encryption)
{
show_encryption(pdf, o);
}
if (o.check_linearization)
{
if (pdf.checkLinearization())
{
std::cout << o.infilename << ": no linearization errors"
<< std::endl;
}
else
{
exit_code = EXIT_ERROR;
}
}
if (o.show_linearization)
{
if (pdf.isLinearized())
{
pdf.showLinearizationData();
}
else
{
std::cout << o.infilename << " is not linearized"
<< std::endl;
}
}
if (o.show_xref)
{
pdf.showXRefTable();
}
if ((o.show_obj > 0) || o.show_trailer)
{
do_show_obj(pdf, o, exit_code);
}
if (o.show_pages)
{
do_show_pages(pdf, o);
}
if (exit_code)
{
exit(exit_code);
}
}
class ImageOptimizer: public QPDFObjectHandle::StreamDataProvider
{
public:
ImageOptimizer(Options& o, QPDFObjectHandle& image);
virtual ~ImageOptimizer()
{
}
virtual void provideStreamData(int objid, int generation,
Pipeline* pipeline);
PointerHolder<Pipeline> makePipeline(
std::string const& description, Pipeline* next);
bool evaluate(std::string const& description);
private:
Options& o;
QPDFObjectHandle image;
};
ImageOptimizer::ImageOptimizer(Options& o, QPDFObjectHandle& image) :
o(o),
image(image)
{
}
PointerHolder<Pipeline>
ImageOptimizer::makePipeline(std::string const& description, Pipeline* next)
{
PointerHolder<Pipeline> result;
QPDFObjectHandle dict = image.getDict();
QPDFObjectHandle w_obj = dict.getKey("/Width");
QPDFObjectHandle h_obj = dict.getKey("/Height");
QPDFObjectHandle colorspace_obj = dict.getKey("/ColorSpace");
if (! (w_obj.isNumber() && h_obj.isNumber()))
{
if (o.verbose && (! description.empty()))
{
std::cout << whoami << ": " << description
<< ": not optimizing because image dictionary"
<< " is missing required keys" << std::endl;
}
return result;
}
QPDFObjectHandle components_obj = dict.getKey("/BitsPerComponent");
if (! (components_obj.isInteger() && (components_obj.getIntValue() == 8)))
{
QTC::TC("qpdf", "qpdf image optimize bits per component");
if (o.verbose && (! description.empty()))
{
std::cout << whoami << ": " << description
<< ": not optimizing because image has other than"
<< " 8 bits per component" << std::endl;
}
return result;
}
// Files have been seen in the wild whose width and height are
// floating point, which is goofy, but we can deal with it.
JDIMENSION w = static_cast<JDIMENSION>(
w_obj.isInteger() ? w_obj.getIntValue() : w_obj.getNumericValue());
JDIMENSION h = static_cast<JDIMENSION>(
h_obj.isInteger() ? h_obj.getIntValue() : h_obj.getNumericValue());
std::string colorspace = (colorspace_obj.isName() ?
colorspace_obj.getName() :
std::string());
int components = 0;
J_COLOR_SPACE cs = JCS_UNKNOWN;
if (colorspace == "/DeviceRGB")
{
components = 3;
cs = JCS_RGB;
}
else if (colorspace == "/DeviceGray")
{
components = 1;
cs = JCS_GRAYSCALE;
}
else if (colorspace == "/DeviceCMYK")
{
components = 4;
cs = JCS_CMYK;
}
else
{
QTC::TC("qpdf", "qpdf image optimize colorspace");
if (o.verbose && (! description.empty()))
{
std::cout << whoami << ": " << description
<< ": not optimizing because qpdf can't optimize"
<< " images with this colorspace" << std::endl;
}
return result;
}
if (((o.oi_min_width > 0) && (w <= o.oi_min_width)) ||
((o.oi_min_height > 0) && (h <= o.oi_min_height)) ||
((o.oi_min_area > 0) && ((w * h) <= o.oi_min_area)))
{
QTC::TC("qpdf", "qpdf image optimize too small");
if (o.verbose && (! description.empty()))
{
std::cout << whoami << ": " << description
<< ": not optimizing because image"
<< " is smaller than requested minimum dimensions"
<< std::endl;
}
return result;
}
result = new Pl_DCT("jpg", next, w, h, components, cs);
return result;
}
bool
ImageOptimizer::evaluate(std::string const& description)
{
if (! image.pipeStreamData(0, 0, qpdf_dl_specialized, true))
{
QTC::TC("qpdf", "qpdf image optimize no pipeline");
if (o.verbose)
{
std::cout << whoami << ": " << description
<< ": not optimizing because unable to decode data"
<< " or data already uses DCT"
<< std::endl;
}
return false;
}
Pl_Discard d;
Pl_Count c("count", &d);
PointerHolder<Pipeline> p = makePipeline(description, &c);
if (p.getPointer() == 0)
{
// message issued by makePipeline
return false;
}
if (! image.pipeStreamData(p.getPointer(), 0, qpdf_dl_specialized))
{
return false;
}
long long orig_length = image.getDict().getKey("/Length").getIntValue();
if (c.getCount() >= orig_length)
{
QTC::TC("qpdf", "qpdf image optimize no shrink");
if (o.verbose)
{
std::cout << whoami << ": " << description
<< ": not optimizing because DCT compression does not"
<< " reduce image size" << std::endl;
}
return false;
}
if (o.verbose)
{
std::cout << whoami << ": " << description
<< ": optimizing image reduces size from "
<< orig_length << " to " << c.getCount()
<< std::endl;
}
return true;
}
void
ImageOptimizer::provideStreamData(int, int, Pipeline* pipeline)
{
PointerHolder<Pipeline> p = makePipeline("", pipeline);
if (p.getPointer() == 0)
{
// Should not be possible
image.warnIfPossible("unable to create pipeline after previous"
" success; image data will be lost");
pipeline->finish();
return;
}
image.pipeStreamData(p.getPointer(), 0, qpdf_dl_specialized,
false, false);
}
template <typename T>
static PointerHolder<QPDF> do_process_once(
void (QPDF::*fn)(T, char const*),
T item, char const* password,
Options& o, bool empty)
{
PointerHolder<QPDF> pdf = new QPDF;
set_qpdf_options(*pdf, o);
if (empty)
{
pdf->emptyPDF();
}
else
{
((*pdf).*fn)(item, password);
}
return pdf;
}
template <typename T>
static PointerHolder<QPDF> do_process(
void (QPDF::*fn)(T, char const*),
T item, char const* password,
Options& o, bool empty)
{
// If a password has been specified but doesn't work, try other
// passwords that are equivalent in different character encodings.
// This makes it possible to open PDF files that were encrypted
// using incorrect string encodings. For example, if someone used
// a password encoded in PDF Doc encoding or Windows code page
// 1252 for an AES-encrypted file or a UTF-8-encoded password on
// an RC4-encrypted file, or if the password was properly encoded
// by the password given here was incorrectly encoded, there's a
// good chance we'd succeed here.
std::string ptemp;
if (password && (! o.password_is_hex_key))
{
if (o.password_mode == pm_hex_bytes)
{
// Special case: handle --password-mode=hex-bytes for input
// password as well as output password
QTC::TC("qpdf", "qpdf input password hex-bytes");
ptemp = QUtil::hex_decode(password);
password = ptemp.c_str();
}
}
if ((password == 0) || empty || o.password_is_hex_key ||
o.suppress_password_recovery)
{
// There is no password, or we're not doing recovery, so just
// do the normal processing with the supplied password.
return do_process_once(fn, item, password, o, empty);
}
// Get a list of otherwise encoded strings. Keep in scope for this
// method.
std::vector<std::string> passwords_str =
QUtil::possible_repaired_encodings(password);
// Represent to char const*, as required by the QPDF class.
std::vector<char const*> passwords;
for (std::vector<std::string>::iterator iter = passwords_str.begin();
iter != passwords_str.end(); ++iter)
{
passwords.push_back((*iter).c_str());
}
// We always try the supplied password first because it is the
// first string returned by possible_repaired_encodings. If there
// is more than one option, go ahead and put the supplied password
// at the end so that it's that decoding attempt whose exception
// is thrown.
if (passwords.size() > 1)
{
passwords.push_back(password);
}
// Try each password. If one works, return the resulting object.
// If they all fail, throw the exception thrown by the final
// attempt, which, like the first attempt, will be with the
// supplied password.
bool warned = false;
for (std::vector<char const*>::iterator iter = passwords.begin();
iter != passwords.end(); ++iter)
{
try
{
return do_process_once(fn, item, *iter, o, empty);
}
catch (QPDFExc& e)
{
std::vector<char const*>::iterator next = iter;
++next;
if (next == passwords.end())
{
throw e;
}
}
if ((! warned) && o.verbose)
{
warned = true;
std::cout << whoami << ": supplied password didn't work;"
<< " trying other passwords based on interpreting"
<< " password with different string encodings"
<< std::endl;
}
}
// Should not be reachable
throw std::logic_error("do_process returned");
}
static PointerHolder<QPDF> process_file(char const* filename,
char const* password,
Options& o)
{
return do_process(&QPDF::processFile, filename, password, o,
strcmp(filename, "") == 0);
}
static PointerHolder<QPDF> process_input_source(
PointerHolder<InputSource> is, char const* password, Options& o)
{
return do_process(&QPDF::processInputSource, is, password, o, false);
}
static void validate_under_overlay(QPDF& pdf, UnderOverlay* uo, Options& o)
{
if (0 == uo->filename)
{
return;
}
QPDFPageDocumentHelper main_pdh(pdf);
int main_npages = static_cast<int>(main_pdh.getAllPages().size());
uo->pdf = process_file(uo->filename, uo->password, o);
QPDFPageDocumentHelper uo_pdh(*(uo->pdf));
int uo_npages = static_cast<int>(uo_pdh.getAllPages().size());
try
{
uo->to_pagenos = QUtil::parse_numrange(uo->to_nr, main_npages);
}
catch (std::runtime_error& e)
{
usageExit("parsing numeric range for " + uo->which +
" \"to\" pages: " + e.what());
}
try
{
if (0 == strlen(uo->from_nr))
{
QTC::TC("qpdf", "qpdf from_nr from repeat_nr");
uo->from_nr = uo->repeat_nr;
}
uo->from_pagenos = QUtil::parse_numrange(uo->from_nr, uo_npages);
if (strlen(uo->repeat_nr))
{
uo->repeat_pagenos =
QUtil::parse_numrange(uo->repeat_nr, uo_npages);
}
}
catch (std::runtime_error& e)
{
usageExit("parsing numeric range for " + uo->which + " file " +
uo->filename + ": " + e.what());
}
}
static void get_uo_pagenos(UnderOverlay& uo,
std::map<int, std::vector<int> >& pagenos)
{
size_t idx = 0;
size_t from_size = uo.from_pagenos.size();
size_t repeat_size = uo.repeat_pagenos.size();
for (std::vector<int>::iterator iter = uo.to_pagenos.begin();
iter != uo.to_pagenos.end(); ++iter, ++idx)
{
if (idx < from_size)
{
pagenos[*iter].push_back(uo.from_pagenos.at(idx));
}
else if (repeat_size)
{
pagenos[*iter].push_back(
uo.repeat_pagenos.at((idx - from_size) % repeat_size));
}
}
}
static void do_under_overlay_for_page(
QPDF& pdf,
Options& o,
UnderOverlay& uo,
std::map<int, std::vector<int> >& pagenos,
size_t page_idx,
std::map<int, QPDFObjectHandle>& fo,
std::vector<QPDFPageObjectHelper>& pages,
QPDFPageObjectHelper& dest_page,
bool before)
{
int pageno = 1 + page_idx;
if (! pagenos.count(pageno))
{
return;
}
std::string content;
int min_suffix = 1;
QPDFObjectHandle resources = dest_page.getAttribute("/Resources", true);
for (std::vector<int>::iterator iter = pagenos[pageno].begin();
iter != pagenos[pageno].end(); ++iter)
{
int from_pageno = *iter;
if (o.verbose)
{
std::cout << " " << uo.which << " " << from_pageno << std::endl;
}
if (0 == fo.count(from_pageno))
{
fo[from_pageno] =
pdf.copyForeignObject(
pages.at(from_pageno - 1).getFormXObjectForPage());
}
// If the same page is overlaid or underlaid multiple times,
// we'll generate multiple names for it, but that's harmless
// and also a pretty goofy case that's not worth coding
// around.
std::string name = resources.getUniqueResourceName("/Fx", min_suffix);
std::string new_content = dest_page.placeFormXObject(
fo[from_pageno], name,
dest_page.getTrimBox().getArrayAsRectangle());
if (! new_content.empty())
{
resources.mergeResources(
QPDFObjectHandle::parse("<< /XObject << >> >>"));
resources.getKey("/XObject").replaceKey(name, fo[from_pageno]);
++min_suffix;
content += new_content;
}
}
if (! content.empty())
{
if (before)
{
dest_page.addPageContents(
QPDFObjectHandle::newStream(&pdf, content), true);
}
else
{
dest_page.addPageContents(
QPDFObjectHandle::newStream(&pdf, "q\n"), true);
dest_page.addPageContents(
QPDFObjectHandle::newStream(&pdf, "\nQ\n" + content), false);
}
}
}
static void handle_under_overlay(QPDF& pdf, Options& o)
{
validate_under_overlay(pdf, &o.underlay, o);
validate_under_overlay(pdf, &o.overlay, o);
if ((0 == o.underlay.pdf.getPointer()) &&
(0 == o.overlay.pdf.getPointer()))
{
return;
}
std::map<int, std::vector<int> > underlay_pagenos;
get_uo_pagenos(o.underlay, underlay_pagenos);
std::map<int, std::vector<int> > overlay_pagenos;
get_uo_pagenos(o.overlay, overlay_pagenos);
std::map<int, QPDFObjectHandle> underlay_fo;
std::map<int, QPDFObjectHandle> overlay_fo;
std::vector<QPDFPageObjectHelper> upages;
if (o.underlay.pdf.getPointer())
{
upages = QPDFPageDocumentHelper(*(o.underlay.pdf)).getAllPages();
}
std::vector<QPDFPageObjectHelper> opages;
if (o.overlay.pdf.getPointer())
{
opages = QPDFPageDocumentHelper(*(o.overlay.pdf)).getAllPages();
}
QPDFPageDocumentHelper main_pdh(pdf);
std::vector<QPDFPageObjectHelper> main_pages = main_pdh.getAllPages();
size_t main_npages = main_pages.size();
if (o.verbose)
{
std::cout << whoami << ": processing underlay/overlay" << std::endl;
}
for (size_t i = 0; i < main_npages; ++i)
{
if (o.verbose)
{
std::cout << " page " << 1+i << std::endl;
}
do_under_overlay_for_page(pdf, o, o.underlay, underlay_pagenos, i,
underlay_fo, upages, main_pages.at(i),
true);
do_under_overlay_for_page(pdf, o, o.overlay, overlay_pagenos, i,
overlay_fo, opages, main_pages.at(i),
false);
}
}
static void handle_transformations(QPDF& pdf, Options& o)
{
QPDFPageDocumentHelper dh(pdf);
if (o.externalize_inline_images)
{
std::vector<QPDFPageObjectHelper> pages = dh.getAllPages();
for (std::vector<QPDFPageObjectHelper>::iterator iter = pages.begin();
iter != pages.end(); ++iter)
{
QPDFPageObjectHelper& ph(*iter);
ph.externalizeInlineImages(o.ii_min_bytes);
}
}
if (o.optimize_images)
{
int pageno = 0;
std::vector<QPDFPageObjectHelper> pages = dh.getAllPages();
for (std::vector<QPDFPageObjectHelper>::iterator iter = pages.begin();
iter != pages.end(); ++iter)
{
++pageno;
QPDFPageObjectHelper& ph(*iter);
QPDFObjectHandle page = ph.getObjectHandle();
std::map<std::string, QPDFObjectHandle> images =
ph.getPageImages();
for (std::map<std::string, QPDFObjectHandle>::iterator iter =
images.begin();
iter != images.end(); ++iter)
{
std::string name = (*iter).first;
QPDFObjectHandle& image = (*iter).second;
ImageOptimizer* io = new ImageOptimizer(o, image);
PointerHolder<QPDFObjectHandle::StreamDataProvider> sdp(io);
if (io->evaluate("image " + name + " on page " +
QUtil::int_to_string(pageno)))
{
QPDFObjectHandle new_image =
QPDFObjectHandle::newStream(&pdf);
new_image.replaceDict(image.getDict().shallowCopy());
new_image.replaceStreamData(
sdp,
QPDFObjectHandle::newName("/DCTDecode"),
QPDFObjectHandle::newNull());
ph.getAttribute("/Resources", true).
getKey("/XObject").replaceKey(
name, new_image);
}
}
}
}
if (o.generate_appearances)
{
QPDFAcroFormDocumentHelper afdh(pdf);
afdh.generateAppearancesIfNeeded();
}
if (o.flatten_annotations)
{
dh.flattenAnnotations(o.flatten_annotations_required,
o.flatten_annotations_forbidden);
}
if (o.coalesce_contents)
{
std::vector<QPDFPageObjectHelper> pages = dh.getAllPages();
for (std::vector<QPDFPageObjectHelper>::iterator iter = pages.begin();
iter != pages.end(); ++iter)
{
(*iter).coalesceContentStreams();
}
}
if (o.remove_page_labels)
{
pdf.getRoot().removeKey("/PageLabels");
}
}
static void handle_page_specs(QPDF& pdf, Options& o)
{
// Parse all page specifications and translate them into lists of
// actual pages.
// Handle "." as a shortcut for the input file
for (std::vector<PageSpec>::iterator iter = o.page_specs.begin();
iter != o.page_specs.end(); ++iter)
{
PageSpec& page_spec = *iter;
if (page_spec.filename == ".")
{
page_spec.filename = o.infilename;
}
}
if (! o.keep_files_open_set)
{
// Count the number of distinct files to determine whether we
// should keep files open or not. Rather than trying to code
// some portable heuristic based on OS limits, just hard-code
// this at a given number and allow users to override.
std::set<std::string> filenames;
for (std::vector<PageSpec>::iterator iter = o.page_specs.begin();
iter != o.page_specs.end(); ++iter)
{
PageSpec& page_spec = *iter;
filenames.insert(page_spec.filename);
}
if (filenames.size() > o.keep_files_open_threshold)
{
QTC::TC("qpdf", "qpdf disable keep files open");
if (o.verbose)
{
std::cout << whoami << ": selecting --keep-open-files=n"
<< std::endl;
}
o.keep_files_open = false;
}
else
{
if (o.verbose)
{
std::cout << whoami << ": selecting --keep-open-files=y"
<< std::endl;
}
o.keep_files_open = true;
QTC::TC("qpdf", "qpdf don't disable keep files open");
}
}
// Create a QPDF object for each file that we may take pages from.
std::vector<PointerHolder<QPDF> > page_heap;
std::map<std::string, QPDF*> page_spec_qpdfs;
std::map<std::string, ClosedFileInputSource*> page_spec_cfis;
page_spec_qpdfs[o.infilename] = &pdf;
std::vector<QPDFPageData> parsed_specs;
std::map<unsigned long long, std::set<QPDFObjGen> > copied_pages;
for (std::vector<PageSpec>::iterator iter = o.page_specs.begin();
iter != o.page_specs.end(); ++iter)
{
PageSpec& page_spec = *iter;
if (page_spec_qpdfs.count(page_spec.filename) == 0)
{
// Open the PDF file and store the QPDF object. Throw a
// PointerHolder to the qpdf into a heap so that it
// survives through copying to the output but gets cleaned up
// automatically at the end. Do not canonicalize the file
// name. Using two different paths to refer to the same
// file is a document workaround for duplicating a page.
// If you are using this an example of how to do this with
// the API, you can just create two different QPDF objects
// to the same underlying file with the same path to
// achieve the same affect.
char const* password = page_spec.password;
if (o.encryption_file && (password == 0) &&
(page_spec.filename == o.encryption_file))
{
QTC::TC("qpdf", "qpdf pages encryption password");
password = o.encryption_file_password;
}
if (o.verbose)
{
std::cout << whoami << ": processing "
<< page_spec.filename << std::endl;
}
PointerHolder<InputSource> is;
ClosedFileInputSource* cis = 0;
if (! o.keep_files_open)
{
QTC::TC("qpdf", "qpdf keep files open n");
cis = new ClosedFileInputSource(page_spec.filename.c_str());
is = cis;
cis->stayOpen(true);
}
else
{
QTC::TC("qpdf", "qpdf keep files open y");
FileInputSource* fis = new FileInputSource();
is = fis;
fis->setFilename(page_spec.filename.c_str());
}
PointerHolder<QPDF> qpdf_ph = process_input_source(is, password, o);
page_heap.push_back(qpdf_ph);
page_spec_qpdfs[page_spec.filename] = qpdf_ph.getPointer();
if (cis)
{
cis->stayOpen(false);
page_spec_cfis[page_spec.filename] = cis;
}
}
// Read original pages from the PDF, and parse the page range
// associated with this occurrence of the file.
parsed_specs.push_back(
QPDFPageData(page_spec.filename,
page_spec_qpdfs[page_spec.filename],
page_spec.range));
}
if (! o.preserve_unreferenced_page_resources)
{
for (std::map<std::string, QPDF*>::iterator iter =
page_spec_qpdfs.begin();
iter != page_spec_qpdfs.end(); ++iter)
{
std::string const& filename = (*iter).first;
ClosedFileInputSource* cis = 0;
if (page_spec_cfis.count(filename))
{
cis = page_spec_cfis[filename];
cis->stayOpen(true);
}
QPDFPageDocumentHelper dh(*((*iter).second));
dh.removeUnreferencedResources();
if (cis)
{
cis->stayOpen(false);
}
}
}
// Clear all pages out of the primary QPDF's pages tree but leave
// the objects in place in the file so they can be re-added
// without changing their object numbers. This enables other
// things in the original file, such as outlines, to continue to
// work.
if (o.verbose)
{
std::cout << whoami
<< ": removing unreferenced pages from primary input"
<< std::endl;
}
QPDFPageDocumentHelper dh(pdf);
std::vector<QPDFPageObjectHelper> orig_pages = dh.getAllPages();
for (std::vector<QPDFPageObjectHelper>::iterator iter =
orig_pages.begin();
iter != orig_pages.end(); ++iter)
{
dh.removePage(*iter);
}
if (o.collate && (parsed_specs.size() > 1))
{
// Collate the pages by selecting one page from each spec in
// order. When a spec runs out of pages, stop selecting from
// it.
std::vector<QPDFPageData> new_parsed_specs;
size_t nspecs = parsed_specs.size();
size_t cur_page = 0;
bool got_pages = true;
while (got_pages)
{
got_pages = false;
for (size_t i = 0; i < nspecs; ++i)
{
QPDFPageData& page_data = parsed_specs.at(i);
if (cur_page < page_data.selected_pages.size())
{
got_pages = true;
new_parsed_specs.push_back(
QPDFPageData(
page_data,
page_data.selected_pages.at(cur_page)));
}
}
++cur_page;
}
parsed_specs = new_parsed_specs;
}
// Add all the pages from all the files in the order specified.
// Keep track of any pages from the original file that we are
// selecting.
std::set<int> selected_from_orig;
std::vector<QPDFObjectHandle> new_labels;
bool any_page_labels = false;
int out_pageno = 0;
for (std::vector<QPDFPageData>::iterator iter =
parsed_specs.begin();
iter != parsed_specs.end(); ++iter)
{
QPDFPageData& page_data = *iter;
ClosedFileInputSource* cis = 0;
if (page_spec_cfis.count(page_data.filename))
{
cis = page_spec_cfis[page_data.filename];
cis->stayOpen(true);
}
QPDFPageLabelDocumentHelper pldh(*page_data.qpdf);
if (pldh.hasPageLabels())
{
any_page_labels = true;
}
if (o.verbose)
{
std::cout << whoami << ": adding pages from "
<< page_data.filename << std::endl;
}
for (std::vector<int>::iterator pageno_iter =
page_data.selected_pages.begin();
pageno_iter != page_data.selected_pages.end();
++pageno_iter, ++out_pageno)
{
// Pages are specified from 1 but numbered from 0 in the
// vector
int pageno = *pageno_iter - 1;
pldh.getLabelsForPageRange(pageno, pageno, out_pageno,
new_labels);
QPDFPageObjectHelper to_copy = page_data.orig_pages.at(pageno);
QPDFObjGen to_copy_og = to_copy.getObjectHandle().getObjGen();
unsigned long long from_uuid = page_data.qpdf->getUniqueId();
if (copied_pages[from_uuid].count(to_copy_og))
{
QTC::TC("qpdf", "qpdf copy same page more than once",
(page_data.qpdf == &pdf) ? 0 : 1);
to_copy = to_copy.shallowCopyPage();
}
else
{
copied_pages[from_uuid].insert(to_copy_og);
}
dh.addPage(to_copy, false);
if (page_data.qpdf == &pdf)
{
// This is a page from the original file. Keep track
// of the fact that we are using it.
selected_from_orig.insert(pageno);
}
}
if (cis)
{
cis->stayOpen(false);
}
}
if (any_page_labels)
{
QPDFObjectHandle page_labels =
QPDFObjectHandle::newDictionary();
page_labels.replaceKey(
"/Nums", QPDFObjectHandle::newArray(new_labels));
pdf.getRoot().replaceKey("/PageLabels", page_labels);
}
// Delete page objects for unused page in primary. This prevents
// those objects from being preserved by being referred to from
// other places, such as the outlines dictionary.
for (size_t pageno = 0; pageno < orig_pages.size(); ++pageno)
{
if (selected_from_orig.count(pageno) == 0)
{
pdf.replaceObject(
orig_pages.at(pageno).getObjectHandle().getObjGen(),
QPDFObjectHandle::newNull());
}
}
}
static void handle_rotations(QPDF& pdf, Options& o)
{
QPDFPageDocumentHelper dh(pdf);
std::vector<QPDFPageObjectHelper> pages = dh.getAllPages();
int npages = static_cast<int>(pages.size());
for (std::map<std::string, RotationSpec>::iterator iter =
o.rotations.begin();
iter != o.rotations.end(); ++iter)
{
std::string const& range = (*iter).first;
RotationSpec const& rspec = (*iter).second;
// range has been previously validated
std::vector<int> to_rotate =
QUtil::parse_numrange(range.c_str(), npages);
for (std::vector<int>::iterator i2 = to_rotate.begin();
i2 != to_rotate.end(); ++i2)
{
int pageno = *i2 - 1;
if ((pageno >= 0) && (pageno < npages))
{
pages.at(pageno).rotatePage(rspec.angle, rspec.relative);
}
}
}
}
static void maybe_fix_write_password(int R, Options& o, std::string& password)
{
switch (o.password_mode)
{
case pm_bytes:
QTC::TC("qpdf", "qpdf password mode bytes");
break;
case pm_hex_bytes:
QTC::TC("qpdf", "qpdf password mode hex-bytes");
password = QUtil::hex_decode(password);
break;
case pm_unicode:
case pm_auto:
{
bool has_8bit_chars;
bool is_valid_utf8;
bool is_utf16;
QUtil::analyze_encoding(password,
has_8bit_chars,
is_valid_utf8,
is_utf16);
if (! has_8bit_chars)
{
return;
}
if (o.password_mode == pm_unicode)
{
if (! is_valid_utf8)
{
QTC::TC("qpdf", "qpdf password not unicode");
throw std::runtime_error(
"supplied password is not valid UTF-8");
}
if (R < 5)
{
std::string encoded;
if (! QUtil::utf8_to_pdf_doc(password, encoded))
{
QTC::TC("qpdf", "qpdf password not encodable");
throw std::runtime_error(
"supplied password cannot be encoded for"
" 40-bit or 128-bit encryption formats");
}
password = encoded;
}
}
else
{
if ((R < 5) && is_valid_utf8)
{
std::string encoded;
if (QUtil::utf8_to_pdf_doc(password, encoded))
{
QTC::TC("qpdf", "qpdf auto-encode password");
if (o.verbose)
{
std::cout
<< whoami
<< ": automatically converting Unicode"
<< " password to single-byte encoding as"
<< " required for 40-bit or 128-bit"
<< " encryption" << std::endl;
}
password = encoded;
}
else
{
QTC::TC("qpdf", "qpdf bytes fallback warning");
std::cerr
<< whoami << ": WARNING: "
<< "supplied password looks like a Unicode"
<< " password with characters not allowed in"
<< " passwords for 40-bit and 128-bit encryption;"
<< " most readers will not be able to open this"
<< " file with the supplied password."
<< " (Use --password-mode=bytes to suppress this"
<< " warning and use the password anyway.)"
<< std::endl;
}
}
else if ((R >= 5) && (! is_valid_utf8))
{
QTC::TC("qpdf", "qpdf invalid utf-8 in auto");
throw std::runtime_error(
"supplied password is not a valid Unicode password,"
" which is required for 256-bit encryption; to"
" really use this password, rerun with the"
" --password-mode=bytes option");
}
}
}
break;
}
}
static void set_encryption_options(QPDF& pdf, Options& o, QPDFWriter& w)
{
int R = 0;
if (o.keylen == 40)
{
R = 2;
}
else if (o.keylen == 128)
{
if (o.force_V4 || o.cleartext_metadata || o.use_aes)
{
R = 4;
}
else
{
R = 3;
}
}
else if (o.keylen == 256)
{
if (o.force_R5)
{
R = 5;
}
else
{
R = 6;
}
}
else
{
throw std::logic_error("bad encryption keylen");
}
if ((R > 3) && (o.r3_accessibility == false))
{
std::cerr << whoami
<< ": -accessibility=n is ignored for modern"
<< " encryption formats" << std::endl;
}
maybe_fix_write_password(R, o, o.user_password);
maybe_fix_write_password(R, o, o.owner_password);
switch (R)
{
case 2:
w.setR2EncryptionParameters(
o.user_password.c_str(), o.owner_password.c_str(),
o.r2_print, o.r2_modify, o.r2_extract, o.r2_annotate);
break;
case 3:
w.setR3EncryptionParameters(
o.user_password.c_str(), o.owner_password.c_str(),
o.r3_accessibility, o.r3_extract,
o.r3_assemble, o.r3_annotate_and_form,
o.r3_form_filling, o.r3_modify_other,
o.r3_print);
break;
case 4:
w.setR4EncryptionParameters(
o.user_password.c_str(), o.owner_password.c_str(),
o.r3_accessibility, o.r3_extract,
o.r3_assemble, o.r3_annotate_and_form,
o.r3_form_filling, o.r3_modify_other,
o.r3_print, !o.cleartext_metadata, o.use_aes);
break;
case 5:
w.setR5EncryptionParameters(
o.user_password.c_str(), o.owner_password.c_str(),
o.r3_accessibility, o.r3_extract,
o.r3_assemble, o.r3_annotate_and_form,
o.r3_form_filling, o.r3_modify_other,
o.r3_print, !o.cleartext_metadata);
break;
case 6:
w.setR6EncryptionParameters(
o.user_password.c_str(), o.owner_password.c_str(),
o.r3_accessibility, o.r3_extract,
o.r3_assemble, o.r3_annotate_and_form,
o.r3_form_filling, o.r3_modify_other,
o.r3_print, !o.cleartext_metadata);
break;
default:
throw std::logic_error("bad encryption R value");
break;
}
}
static void set_writer_options(QPDF& pdf, Options& o, QPDFWriter& w)
{
if (o.qdf_mode)
{
w.setQDFMode(true);
}
if (o.preserve_unreferenced_objects)
{
w.setPreserveUnreferencedObjects(true);
}
if (o.newline_before_endstream)
{
w.setNewlineBeforeEndstream(true);
}
if (o.normalize_set)
{
w.setContentNormalization(o.normalize);
}
if (o.stream_data_set)
{
w.setStreamDataMode(o.stream_data_mode);
}
if (o.compress_streams_set)
{
w.setCompressStreams(o.compress_streams);
}
if (o.decode_level_set)
{
w.setDecodeLevel(o.decode_level);
}
if (o.decrypt)
{
w.setPreserveEncryption(false);
}
if (o.deterministic_id)
{
w.setDeterministicID(true);
}
if (o.static_id)
{
w.setStaticID(true);
}
if (o.static_aes_iv)
{
w.setStaticAesIV(true);
}
if (o.suppress_original_object_id)
{
w.setSuppressOriginalObjectIDs(true);
}
if (o.copy_encryption)
{
PointerHolder<QPDF> encryption_pdf =
process_file(
o.encryption_file, o.encryption_file_password, o);
w.copyEncryptionParameters(*encryption_pdf);
}
if (o.encrypt)
{
set_encryption_options(pdf, o, w);
}
if (o.linearize)
{
w.setLinearization(true);
}
if (! o.linearize_pass1.empty())
{
w.setLinearizationPass1Filename(o.linearize_pass1);
}
if (o.object_stream_set)
{
w.setObjectStreamMode(o.object_stream_mode);
}
if (! o.min_version.empty())
{
std::string version;
int extension_level = 0;
parse_version(o.min_version, version, extension_level);
w.setMinimumPDFVersion(version, extension_level);
}
if (! o.force_version.empty())
{
std::string version;
int extension_level = 0;
parse_version(o.force_version, version, extension_level);
w.forcePDFVersion(version, extension_level);
}
if (o.progress && o.outfilename)
{
w.registerProgressReporter(new ProgressReporter(o.outfilename));
}
}
static void write_outfile(QPDF& pdf, Options& o)
{
if (o.split_pages)
{
// Generate output file pattern
std::string before;
std::string after;
size_t len = strlen(o.outfilename);
char* num_spot = strstr(const_cast<char*>(o.outfilename), "%d");
if (num_spot != 0)
{
QTC::TC("qpdf", "qpdf split-pages %d");
before = std::string(o.outfilename, (num_spot - o.outfilename));
after = num_spot + 2;
}
else if ((len >= 4) &&
(QUtil::strcasecmp(o.outfilename + len - 4, ".pdf") == 0))
{
QTC::TC("qpdf", "qpdf split-pages .pdf");
before = std::string(o.outfilename, len - 4) + "-";
after = o.outfilename + len - 4;
}
else
{
QTC::TC("qpdf", "qpdf split-pages other");
before = std::string(o.outfilename) + "-";
}
if (! o.preserve_unreferenced_page_resources)
{
QPDFPageDocumentHelper dh(pdf);
dh.removeUnreferencedResources();
}
QPDFPageLabelDocumentHelper pldh(pdf);
std::vector<QPDFObjectHandle> const& pages = pdf.getAllPages();
int pageno_len = QUtil::int_to_string(pages.size()).length();
unsigned int num_pages = pages.size();
for (unsigned int i = 0; i < num_pages; i += o.split_pages)
{
unsigned int first = i + 1;
unsigned int last = i + o.split_pages;
if (last > num_pages)
{
last = num_pages;
}
QPDF outpdf;
outpdf.emptyPDF();
for (unsigned int pageno = first; pageno <= last; ++pageno)
{
QPDFObjectHandle page = pages.at(pageno - 1);
outpdf.addPage(page, false);
}
if (pldh.hasPageLabels())
{
std::vector<QPDFObjectHandle> labels;
pldh.getLabelsForPageRange(first - 1, last - 1, 0, labels);
QPDFObjectHandle page_labels =
QPDFObjectHandle::newDictionary();
page_labels.replaceKey(
"/Nums", QPDFObjectHandle::newArray(labels));
outpdf.getRoot().replaceKey("/PageLabels", page_labels);
}
std::string page_range = QUtil::int_to_string(first, pageno_len);
if (o.split_pages > 1)
{
page_range += "-" + QUtil::int_to_string(last, pageno_len);
}
std::string outfile = before + page_range + after;
QPDFWriter w(outpdf, outfile.c_str());
set_writer_options(outpdf, o, w);
w.write();
if (o.verbose)
{
std::cout << whoami << ": wrote file " << outfile << std::endl;
}
}
}
else
{
if (strcmp(o.outfilename, "-") == 0)
{
o.outfilename = 0;
}
QPDFWriter w(pdf, o.outfilename);
set_writer_options(pdf, o, w);
w.write();
if (o.verbose)
{
std::cout << whoami << ": wrote file "
<< o.outfilename << std::endl;
}
}
}
int realmain(int argc, char* argv[])
{
whoami = QUtil::getWhoami(argv[0]);
QUtil::setLineBuf(stdout);
// Remove prefix added by libtool for consistency during testing.
if (strncmp(whoami, "lt-", 3) == 0)
{
whoami += 3;
}
// ArgParser must stay in scope for the duration of qpdf's run as
// it holds dynamic memory used for argv.
Options o;
ArgParser ap(argc, argv, o);
ap.parseOptions();
try
{
PointerHolder<QPDF> pdf_ph =
process_file(o.infilename, o.password, o);
QPDF& pdf = *pdf_ph;
if (! o.page_specs.empty())
{
handle_page_specs(pdf, o);
}
if (! o.rotations.empty())
{
handle_rotations(pdf, o);
}
handle_under_overlay(pdf, o);
handle_transformations(pdf, o);
if (o.outfilename == 0)
{
do_inspection(pdf, o);
}
else
{
write_outfile(pdf, o);
}
if (! pdf.getWarnings().empty())
{
if (! o.suppress_warnings)
{
std::cerr << whoami << ": operation succeeded with warnings;"
<< " resulting file may have some problems"
<< std::endl;
}
// Still exit with warning code even if warnings were suppressed.
exit(EXIT_WARNING);
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
exit(EXIT_ERROR);
}
return 0;
}
#ifdef WINDOWS_WMAIN
extern "C"
int wmain(int argc, wchar_t* argv[])
{
// If wmain is supported, argv contains UTF-16-encoded strings
// with a 16-bit wchar_t. Convert this to UTF-8-encoded strings
// for compatibility with other systems. That way the rest of
// qpdf.cc can just act like arguments are UTF-8.
std::vector<PointerHolder<char> > utf8_argv;
for (int i = 0; i < argc; ++i)
{
std::string utf16;
for (size_t j = 0; j < wcslen(argv[i]); ++j)
{
unsigned short codepoint = static_cast<unsigned short>(argv[i][j]);
utf16.append(1, static_cast<unsigned char>(codepoint >> 8));
utf16.append(1, static_cast<unsigned char>(codepoint & 0xff));
}
std::string utf8 = QUtil::utf16_to_utf8(utf16);
utf8_argv.push_back(
PointerHolder<char>(true, QUtil::copy_string(utf8.c_str())));
}
PointerHolder<char*> utf8_argv_ph =
PointerHolder<char*>(true, new char*[1+utf8_argv.size()]);
char** new_argv = utf8_argv_ph.getPointer();
for (size_t i = 0; i < utf8_argv.size(); ++i)
{
new_argv[i] = utf8_argv.at(i).getPointer();
}
argc = static_cast<int>(utf8_argv.size());
new_argv[argc] = 0;
return realmain(argc, new_argv);
}
#else
int main(int argc, char* argv[])
{
return realmain(argc, argv);
}
#endif
|