-
-
Notifications
You must be signed in to change notification settings - Fork 37
/
pdfScale.sh
executable file
·2740 lines (2443 loc) · 100 KB
/
pdfScale.sh
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
#!/usr/bin/env bash
################################################################
#
# pdfScale.sh
#
# Manipulate PDFs using Ghostscript.
# Scale, Resize and Split PDFs.
# Writen for Bash.
#
# Gustavo Arnosti Neves - 2016 / 07 / 10
# Latest Version - 2024 / 07 / 16
#
# This app: https://github.com/tavinus/pdfScale
#
# THIS SOFTWARE IS FREE - HAVE FUN WITH IT
# I hope this can be of help to people. Thanks to the people
# that helped and donated. It has been a long run with this
# script. I wish you all the best! -]
#
# Ver 2.5.9 Added MIT License
#
################################################################
VERSION="2.6.3"
###################### EXTERNAL PROGRAMS #######################
GSBIN="" # GhostScript Binary
BCBIN="" # BC Math Binary
IDBIN="" # Identify Binary
PDFINFOBIN="" # PDF Info Binary
MDLSBIN="" # MacOS mdls Binary
##################### ENVIRONMENT SET-UP #######################
LC_MEASUREMENT="C" # To make sure our numbers have .decimals
LC_ALL="C" # Some languages use , as decimal token
LC_CTYPE="C"
LC_NUMERIC="C"
TRUE=0 # Silly stuff
FALSE=1
########################### GLOBALS ############################
SCALE="0.95" # scaling factor (0.95 = 95%, e.g.)
VERBOSE=0 # verbosity Level
PDFSCALE_NAME="$(basename "$0")" # simplified name of this script
OSNAME="$(uname 2>/dev/null)" # Check where we are running
GS_RUN_STATUS="" # Holds GS error messages, signals errors
INFILEPDF="" # Input PDF file name
OUTFILEPDF="" # Output PDF file name
JUST_IDENTIFY=$FALSE # Flag to just show PDF info
ABORT_ON_OVERWRITE=$FALSE # Flag to abort if OUTFILEPDF already exists
EXPLODE_MODE=$FALSE # Turn explode mode (split) on or off
ADAPTIVE_MODE=$TRUE # Automatically try to guess best mode
AUTOMATIC_SCALING=$TRUE # Default scaling in $SCALE, disabled in resize mode
MODE="" # Which page size detection to use
RESIZE_PAPER_TYPE="" # Pre-defined paper to use
CUSTOM_RESIZE_PAPER=$FALSE # If we are using a custom-defined paper
CROPBOX_PAPER_TYPE="" # Pre-defined paper to use for cropboxes
CUSTOM_CROPBOX_PAPER=$FALSE # If we are using a custom-defined cropbox
FLIP_DETECTION=$TRUE # If we should run the Flip-detection
FLIP_FORCE=$FALSE # If we should force Flipping
AUTO_ROTATION='/PageByPage' # GS call auto-rotation setting
FIT_PAGE='-dPDFFitPage' # GS call resize fit page setting
DPRINTED="" # Print to screen or printer ? -dPrinted=false
PGWIDTH="" # Input PDF Page Width
PGHEIGHT="" # Input PDF Page Height
RESIZE_WIDTH="" # Resized PDF Page Width
RESIZE_HEIGHT="" # Resized PDF Page Height
PAGE_RANGE="" # Pages to be processed (feeds -sPageList)
PAGE_COUNT="" # To store the PDF page count
PAGE_SIZES=() # To list all page sizes
EXPLODE_SUFFIX='.Page%d' # Suffix for exploded pages
############################# Image resolution (dpi)
IMAGE_RESOLUTION=300 # 300 is /Printer default
############################# Image compression setting
# default screen ebook printer prepress
# ColorImageDownsampleType /Subsample /Average /Bicubic /Bicubic /Bicubic
IMAGE_DOWNSAMPLE_TYPE='/Bicubic'
############################# default PDF profile
# /screen /ebook /printer /prepress /default
# -dPDFSETTINGS=/screen (screen-view-only quality, 72 dpi images)
# -dPDFSETTINGS=/ebook (low quality, 150 dpi images)
# -dPDFSETTINGS=/printer (high quality, 300 dpi images)
# -dPDFSETTINGS=/prepress (high quality, color preserving, 300 dpi imgs)
# -dPDFSETTINGS=/default (almost identical to /screen)
PDF_SETTINGS='/printer'
############################# default Scaling alignment
VERT_ALIGN="CENTER"
HOR_ALIGN="CENTER"
############################# Translation Offset to apply
XTRANSOFFSET=0.0
YTRANSOFFSET=0.0
############################# Background/Bleed color creation
BACKGROUNDTYPE="NONE" # Should be NONE, CMYK or RGB only
BACKGROUNDCOLOR="" # Color parameters for CMYK(4) or RGB(3)
BACKGROUNDCALL="" # Actual PS call to be embedded
BACKGROUNDLOG="No background (default)"
############################# Execution Flags
SIMULATE=$FALSE # Avoid execution
PRINT_GS_CALL=$FALSE # Print GS Call to stdout
GS_CALL_STRING="" # Buffer
RESIZECOMMANDS="" # command to run on resize call
GSNEWPDF="" # for -dNEWDPF flag
############################# Project Info
PROJECT_NAME="pdfScale"
PROJECT_URL="https://github.com/tavinus/$PROJECT_NAME"
PROJECT_BRANCH='master'
HTTPS_INSECURE=$FALSE
ASSUME_YES=$FALSE
RUN_SELF_INSTALL=$FALSE
TARGET_LOC="/usr/local/bin/pdfscale"
########################## EXIT FLAGS ##########################
EXIT_SUCCESS=0
EXIT_ERROR=1
EXIT_INVALID_PAGE_SIZE_DETECTED=10
EXIT_FILE_NOT_FOUND=20
EXIT_INPUT_NOT_PDF=21
EXIT_INVALID_OPTION=22
EXIT_NO_INPUT_FILE=23
EXIT_INVALID_SCALE=24
EXIT_MISSING_DEPENDENCY=25
EXIT_IMAGEMAGIK_NOT_FOUND=26
EXIT_MAC_MDLS_NOT_FOUND=27
EXIT_PDFINFO_NOT_FOUND=28
EXIT_NOWRITE_PERMISSION=29
EXIT_NOREAD_PERMISSION=30
EXIT_TEMP_FILE_EXISTS=40
EXIT_INVALID_PAPER_SIZE=50
EXIT_INVALID_IMAGE_RESOLUTION=51
############################# MAIN #############################
# Main function called at the end
main() {
isJustIdentify && printPDFSizes # will exit here
local finalRet=$EXIT_ERROR
if isMixedMode; then
initMain " Mixed Tasks: Resize & Scale"
local tempFile=""
local tempSuffix="$RANDOM$RANDOM""_TEMP_$RANDOM$RANDOM.pdf"
outputFile="$OUTFILEPDF" # backup outFile name
tempFile="${OUTFILEPDF%.pdf}" # set temp file, remove .pdf extension
tempFile="${tempFile%$EXPLODE_SUFFIX}.$tempSuffix" # remove explode and add temp suffix
if isFile "$tempFile"; then
printError $'Error! Temporary file name already exists!\n'"File: $tempFile"$'\nAborting execution to avoid overwriting the file.\nPlease Try again...'
exit $EXIT_TEMP_FILE_EXISTS
fi
OUTFILEPDF="$tempFile" # set output to tmp file
pageResize # resize to tmp file
finalRet=$?
INFILEPDF="$tempFile" # get tmp file as input
OUTFILEPDF="$outputFile" # reset final target
PGWIDTH=$RESIZE_WIDTH # we already know the new page size
PGHEIGHT=$RESIZE_HEIGHT # from the last command (Resize)
vPrintPageSizes ' New'
vPrintScaleFactor
PAGE_RANGE="" # reset page range, we already got the pages
pageScale # scale the resized pdf
finalRet=$(($finalRet+$?))
# remove tmp file
if isFile "$tempFile"; then
rm "$tempFile" >/dev/null 2>&1 || printError "Error when removing temporary file: $tempFile"
fi
elif isResizeMode; then
initMain " Single Task: Resize PDF Paper"
vPrintScaleFactor "Disabled (resize only)"
pageResize
finalRet=$?
else
initMain " Single Task: Scale PDF Contents"
local scaleMode=""
isManualScaledMode && scaleMode='(manual)' || scaleMode='(auto)'
vPrintScaleFactor "$SCALE $scaleMode"
pageScale
finalRet=$?
fi
if [[ $finalRet -eq $EXIT_SUCCESS ]] && isEmpty "$GS_RUN_STATUS"; then
if isDryRun; then
vprint " Final Status: Simulation completed successfully"
else
vprint " Final Status: File created successfully"
fi
elif [[ $finalRet -eq $EXIT_SUCCESS ]] && isNotEmpty "$GS_RUN_STATUS"; then
vprint " Final Status: Succeeded with Warnings"
printError "-------------------------------------------------"$'\n'"Ghostscript Debug Info:"$'\n'"$GS_RUN_STATUS"
else
vprint " Final Status: Error detected. Exit status: $finalRet"
printError "-------------------------------------------------"$'\n'"Ghostscript Debug Info:"$'\n'"$GS_RUN_STATUS"
fi
if isNotEmpty "$GS_CALL_STRING" && shouldPrintGSCall; then
printf "%s" "$GS_CALL_STRING"
fi
return $finalRet
}
# Initializes PDF processing for all modes of operation
initMain() {
printVersion 1 'verbose'
isNotEmpty "$1" && vprint "$1"
local sim="FALSE"
isDryRun && sim="TRUE (Simulating)"
vprint " Dry-Run: $sim"
vPrintFileInfo
local exp="Disabled"
isExplodeMode && exp="Enabled"
vprint " Explode PDF: $exp"
getPageSize
vPrintRange
vPrintPageSizes ' Source'
vShowPrintMode
}
# Prints PDF Info and exits with $EXIT_SUCCESS, but only if $JUST_IDENTIFY is $TRUE
printPDFSizes() {
VERBOSE=0
printVersion 3 " - Paper Sizes"
getPageSize || initError "Could not get pagesize!"
local paperType="$(getGSPaperName $PGWIDTH $PGHEIGHT)"
isEmpty "$paperType" && paperType="Custom Paper Size"
getPageCountAndSizes
printf '%s\n' "-------------+-----------------------------"
printf " File | %s\n" "$(basename "$INFILEPDF")"
printf " Paper Type | %s\n" "$paperType"
printf " Pages | %s\n" "$PAGE_COUNT"
printf '%s\n' "-------------+-----------------------------"
printf '%s\n' " FIRST PAGE | WIDTH x HEIGHT"
printf " Points | %+8s x %-8s\n" "$PGWIDTH" "$PGHEIGHT"
printf " Millimeters | %+8s x %-8s\n" "$(pointsToMillimeters $PGWIDTH)" "$(pointsToMillimeters $PGHEIGHT)"
printf " Inches | %+8s x %-8s\n" "$(pointsToInches $PGWIDTH)" "$(pointsToInches $PGHEIGHT)"
printf '%s\n' "-------------+-----------------------------"
printf '%s\n' " ALL PAGES | WIDTH x HEIGHT (pts)"
local t=0
local wh=()
for l in "${PAGE_SIZES[@]}" ; do
wh=($l)
printf " %+11s | %+8s x %-8s\n" $((t+1)) ${wh[0]} ${wh[1]}
((t++))
done
printf '%s\n' "-------------+-----------------------------"
exit $EXIT_SUCCESS
}
###################### GHOSTSCRIPT CALLS #######################
# Runs the ghostscript scaling script
pageScale() {
# Compute translation factors to position pages
CENTERXTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGWIDTH" | "$BCBIN")
CENTERYTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGHEIGHT" | "$BCBIN")
BXTRANS=$CENTERXTRANS
BYTRANS=$CENTERYTRANS
if [[ "$VERT_ALIGN" = "TOP" ]]; then
BYTRANS=$(echo "scale=6; 2*$CENTERYTRANS" | "$BCBIN")
elif [[ "$VERT_ALIGN" = "BOTTOM" ]]; then
BYTRANS=0
fi
if [[ "$HOR_ALIGN" = "LEFT" ]]; then
BXTRANS=0
elif [[ "$HOR_ALIGN" = "RIGHT" ]]; then
BXTRANS=$(echo "scale=6; 2*$CENTERXTRANS" | "$BCBIN")
fi
XTRANS=$(echo "scale=6; $BXTRANS + $XTRANSOFFSET" | "$BCBIN")
YTRANS=$(echo "scale=6; $BYTRANS + $YTRANSOFFSET" | "$BCBIN")
local increase=$(echo "scale=0; (($SCALE - 1) * 100)/1" | "$BCBIN")
[[ $increase -gt 0 ]] && increase="+$increase"
vprint " Scale Percent: $increase%"
vprint " Vert-Align: $VERT_ALIGN"
vprint " Hor-Align: $HOR_ALIGN"
vprint "$(printf ' Translation X: %.2f = %.2f + %.2f (offset)' $XTRANS $BXTRANS $XTRANSOFFSET)"
vprint "$(printf ' Translation Y: %.2f = %.2f + %.2f (offset)' $YTRANS $BYTRANS $YTRANSOFFSET)"
vprint " Background: $BACKGROUNDLOG"
GS_RUN_STATUS="$GS_RUN_STATUS""$(gsPageScale 2>&1)"
GS_CALL_STRING="$GS_CALL_STRING"$'[GS SCALE CALL STARTS]\n'"$(gsPrintPageScale)"$'\n[GS SCALE CALL ENDS]\n'
return $? # Last command is always returned I think
}
# Runs GS call for scaling, nothing else should run here
gsPageScale() {
if isDryRun; then
return $TRUE
fi
# Scale page
"$GSBIN" \
-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \
-dCompatibilityLevel="1.5" -dPDFSETTINGS="$PDF_SETTINGS" \
-dColorImageResolution=$IMAGE_RESOLUTION -dGrayImageResolution=$IMAGE_RESOLUTION \
-dColorImageDownsampleType="$IMAGE_DOWNSAMPLE_TYPE" -dGrayImageDownsampleType="$IMAGE_DOWNSAMPLE_TYPE" \
-dColorConversionStrategy=/LeaveColorUnchanged \
-dSubsetFonts=true -dEmbedAllFonts=true \
-dDEVICEWIDTHPOINTS=$PGWIDTH -dDEVICEHEIGHTPOINTS=$PGHEIGHT \
$DPRINTED \
-sOutputFile="$OUTFILEPDF" $GSNEWPDF $PAGE_RANGE \
-c "<</BeginPage{$BACKGROUNDCALL$SCALE $SCALE scale $XTRANS $YTRANS translate}>> setpagedevice" \
-f "$INFILEPDF"
}
# Prints GS call for scaling
gsPrintPageScale() {
local _call_str=""
# Print Scale page command
read -d '' _call_str<< _EOF_
"$GSBIN" \
-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \
-dCompatibilityLevel="1.5" -dPDFSETTINGS="$PDF_SETTINGS" \
-dColorImageResolution=$IMAGE_RESOLUTION -dGrayImageResolution=$IMAGE_RESOLUTION \
-dColorImageDownsampleType="$IMAGE_DOWNSAMPLE_TYPE" -dGrayImageDownsampleType="$IMAGE_DOWNSAMPLE_TYPE" \
-dColorConversionStrategy=/LeaveColorUnchanged \
-dSubsetFonts=true -dEmbedAllFonts=true \
-dDEVICEWIDTHPOINTS=$PGWIDTH -dDEVICEHEIGHTPOINTS=$PGHEIGHT \
$DPRINTED \
-sOutputFile="$OUTFILEPDF" $GSNEWPDF $PAGE_RANGE \
-c "<</BeginPage{$BACKGROUNDCALL$SCALE $SCALE scale $XTRANS $YTRANS translate}>> setpagedevice" \
-f "$INFILEPDF"
_EOF_
echo -ne "$_call_str"
}
# Runs the ghostscript paper resize script
pageResize() {
# Get paper sizes from source if not resizing
isResizePaperSource && { RESIZE_WIDTH=$PGWIDTH; RESIZE_HEIGHT=$PGHEIGHT; }
# Get new paper sizes if not custom or source paper
isNotCustomPaper && ! isResizePaperSource && getGSPaperSize "$RESIZE_PAPER_TYPE"
local fpStatus="Enabled (default)"
isEmpty $FIT_PAGE && fpStatus="Disabled (manual)"
vprint " Fit To Page: $fpStatus"
vprint " Auto Rotate: $(basename $AUTO_ROTATION)"
runFlipDetect
vprint " Run Resizing: $(uppercase "$RESIZE_PAPER_TYPE") ( "$RESIZE_WIDTH" x "$RESIZE_HEIGHT" ) pts"
if shouldSetCropbox; then
if [[ $CROPBOX_PAPER_TYPE == 'fullsize' ]]; then
CROPBOX_WIDTH=$RESIZE_WIDTH
CROPBOX_HEIGHT=$RESIZE_HEIGHT
elif [[ $CROPBOX_PAPER_TYPE != 'custom' ]]; then
getCropboxPaperSize "$CROPBOX_PAPER_TYPE"
fi
RESIZECOMMANDS='<</EndPage {0 eq {[/CropBox [0 0 '"$CROPBOX_WIDTH $CROPBOX_HEIGHT"'] /PAGE pdfmark true}{false}ifelse}>> setpagedevice'
vprint " Cropbox Reset: $(uppercase "$CROPBOX_PAPER_TYPE") ( "$CROPBOX_WIDTH" x "$CROPBOX_HEIGHT" ) pts"
fi
GS_RUN_STATUS="$GS_RUN_STATUS""$(gsPageResize 2>&1)"
GS_CALL_STRING="$GS_CALL_STRING"$'[GS RESIZE CALL STARTS]\n'"$(gsPrintPageResize)"$'\n[GS RESIZE CALL ENDS]\n'
return $?
}
# Runs GS call for resizing, nothing else should run here
gsPageResize() {
if isDryRun; then
return $TRUE
fi
# Change page size
"$GSBIN" \
-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \
-dCompatibilityLevel="1.5" -dPDFSETTINGS="$PDF_SETTINGS" \
-dColorImageResolution=$IMAGE_RESOLUTION -dGrayImageResolution=$IMAGE_RESOLUTION \
-dColorImageDownsampleType="$IMAGE_DOWNSAMPLE_TYPE" -dGrayImageDownsampleType="$IMAGE_DOWNSAMPLE_TYPE" \
-dColorConversionStrategy=/LeaveColorUnchanged \
-dSubsetFonts=true -dEmbedAllFonts=true \
-dDEVICEWIDTHPOINTS=$RESIZE_WIDTH -dDEVICEHEIGHTPOINTS=$RESIZE_HEIGHT \
-dAutoRotatePages=$AUTO_ROTATION \
-dFIXEDMEDIA $FIT_PAGE $DPRINTED $GSNEWPDF $PAGE_RANGE \
-sOutputFile="$OUTFILEPDF" -c "$RESIZECOMMANDS" \
-f "$INFILEPDF"
return $?
}
# Prints GS call for resizing
gsPrintPageResize() {
# Print Resize page command
local _call_str=""
# Print Scale page command
read -d '' _call_str<< _EOF_
"$GSBIN" \
-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \
-dCompatibilityLevel="1.5" -dPDFSETTINGS="$PDF_SETTINGS" \
-dColorImageResolution=$IMAGE_RESOLUTION -dGrayImageResolution=$IMAGE_RESOLUTION \
-dColorImageDownsampleType="$IMAGE_DOWNSAMPLE_TYPE" -dGrayImageDownsampleType="$IMAGE_DOWNSAMPLE_TYPE" \
-dColorConversionStrategy=/LeaveColorUnchanged \
-dSubsetFonts=true -dEmbedAllFonts=true \
-dDEVICEWIDTHPOINTS=$RESIZE_WIDTH -dDEVICEHEIGHTPOINTS=$RESIZE_HEIGHT \
-dAutoRotatePages=$AUTO_ROTATION \
-dFIXEDMEDIA $FIT_PAGE $DPRINTED $GSNEWPDF $PAGE_RANGE \
-sOutputFile="$OUTFILEPDF" -c "$RESIZECOMMANDS" \
-f "$INFILEPDF"
_EOF_
echo -ne "$_call_str"
}
# Returns $TRUE if we should use the source paper size, $FALSE otherwise
isResizePaperSource() {
[[ "$RESIZE_PAPER_TYPE" = 'source' ]] && return $TRUE
return $FALSE
}
# Filp-Detect Logic
runFlipDetect() {
if isFlipForced; then
vprint " Flip Detect: Forced Mode!"
applyFlipRevert
elif isFlipDetectionEnabled && shouldFlip; then
vprint " Flip Detect: Wrong orientation detected!"
applyFlipRevert
elif ! isFlipDetectionEnabled; then
vprint " Flip Detect: Disabled"
else
vprint " Flip Detect: No change needed"
fi
}
# Inverts $RESIZE_HEIGHT with $RESIZE_WIDTH
applyFlipRevert() {
local tmpInverter=""
tmpInverter=$RESIZE_HEIGHT
RESIZE_HEIGHT=$RESIZE_WIDTH
RESIZE_WIDTH=$tmpInverter
vprint " Inverting Width <-> Height"
}
# Returns the $FLIP_DETECTION flag
isFlipDetectionEnabled() {
return $FLIP_DETECTION
}
# Returns the $FLIP_FORCE flag
isFlipForced() {
return $FLIP_FORCE
}
# Returns $TRUE if the the paper size will invert orientation from source, $FALSE otherwise
shouldFlip() {
[[ $PGWIDTH -gt $PGHEIGHT && $RESIZE_WIDTH -lt $RESIZE_HEIGHT ]] || [[ $PGWIDTH -lt $PGHEIGHT && $RESIZE_WIDTH -gt $RESIZE_HEIGHT ]] && return $TRUE
return $FALSE
}
########################## INITIALIZERS #########################
# Loads external dependencies and checks for errors
initDeps() {
GREPBIN="$(command -v grep 2>/dev/null)"
STRINGSBIN="$(command -v strings 2>/dev/null)"
GSBIN="$(command -v gs 2>/dev/null)"
BCBIN="$(command -v bc 2>/dev/null)"
IDBIN=$(command -v identify 2>/dev/null)
MDLSBIN="$(command -v mdls 2>/dev/null)"
PDFINFOBIN="$(command -v pdfinfo 2>/dev/null)"
vprint "Checking for basename, grep, ghostscript and bcmath"
basename "" >/dev/null 2>&1 || printDependency 'basename'
isNotAvailable "$GREPBIN" && printDependency 'grep'
isNotAvailable "$STRINGSBIN" && printDependency 'strings (binutils)'
isNotAvailable "$GSBIN" && printDependency 'ghostscript'
isNotAvailable "$BCBIN" && printDependency 'bc'
return $TRUE
}
# Checks for dependencies errors, run after getting options
checkDeps() {
if [[ $MODE = "IDENTIFY" ]]; then
vprint "Checking for imagemagick's identify"
if isNotAvailable "$IDBIN"; then printDependency 'imagemagick'; fi
fi
if [[ $MODE = "PDFINFO" ]]; then
vprint "Checking for pdfinfo"
if isNotAvailable "$PDFINFOBIN"; then printDependency 'pdfinfo'; fi
fi
if [[ $MODE = "MDLS" ]]; then
vprint "Checking for MacOS mdls"
if isNotAvailable "$MDLSBIN"; then
initError 'mdls executable was not found! Is this even MacOS?' $EXIT_MAC_MDLS_NOT_FOUND
fi
fi
return $TRUE
}
######################### CLI OPTIONS ##########################
# Parse options
getOptions() {
local _optArgs=() # things that do not start with a '-'
local _tgtFile="" # to set $OUTFILEPDF
local _currParam="" # to enable case-insensitiveness
while [ ${#} -gt 0 ]; do
if [[ "${1:0:2}" = '--' ]]; then
# Long Option, get lowercase version
_currParam="$(lowercase ${1})"
elif [[ "${1:0:1}" = '-' ]]; then
# short Option, just assign
_currParam="${1}"
else
# file name arguments, store as is and reset loop
_optArgs+=("$1")
shift
continue
fi
case "$_currParam" in
-v|--verbose)
((VERBOSE++))
shift
;;
-n|--no-overwrite|--nooverwrite)
ABORT_ON_OVERWRITE=$TRUE
shift
;;
-h|--help)
printHelp
exit $EXIT_SUCCESS
;;
-V|--version)
printVersion 3
exit $EXIT_SUCCESS
;;
-i|--identify|--info)
JUST_IDENTIFY=$TRUE
shift
;;
-e|--explode|--split)
EXPLODE_MODE=$TRUE
shift
;;
--range|--page-range|--pagerange|--page-list|--pagelist)
shift
isEmpty "$1" && initError "Invalid (empty) Page Range!" $EXIT_INVALID_OPTION
PAGE_RANGE="-sPageList=$1"
shift
;;
-s|--scale|--setscale|--set-scale)
shift
parseScale "$1"
shift
;;
-m|--mode|--paperdetect|--paper-detect|--pagesizemode|--page-size-mode)
shift
parseMode "$1"
shift
;;
--newpdf|--dnewpdf)
GSNEWPDF="-dNEWPDF=false"
shift
;;
-r|--resize)
shift
parsePaperResize "$1"
shift
;;
-c|--cropbox)
shift
parseCropbox "$1"
shift
;;
-p|--printpapers|--print-papers|--listpapers|--list-papers)
printPaperInfo
exit $EXIT_SUCCESS
;;
-f|--flipdetection|--flip-detection|--flip-mode|--flipmode|--flipdetect|--flip-detect)
shift
parseFlipDetectionMode "$1"
shift
;;
-a|--autorotation|--auto-rotation|--autorotate|--auto-rotate)
shift
parseAutoRotationMode "$1"
shift
;;
--printmode|--print-mode)
shift
parsePrintMode "$1"
shift
;;
--no-fit-page|--no-fit-to-page|--disable-fit-to-page|--disable-fit-page|--nofitpage|--nofittopage|--disablefittopage|--disablefitpage)
FIT_PAGE=''
shift
;;
--background-gray)
shift
parseGrayBackground $1
shift
;;
--background-rgb)
shift
parseRGBBackground $1
shift
;;
--background-cmyk)
shift
parseCMYKBackground $1
shift
;;
--pdf-settings)
shift
parsePDFSettings "$1"
shift
;;
--image-downsample)
shift
parseImageDownSample "$1"
shift
;;
--image-resolution)
shift
parseImageResolution "$1"
shift
;;
--horizontal-alignment|--hor-align|--xalign|--x-align)
shift
parseHorizontalAlignment "$1"
shift
;;
--vertical-alignment|--ver-align|--vert-align|--yalign|--y-align)
shift
parseVerticalAlignment "$1"
shift
;;
--xtrans|--xtrans-offset|--xoffset)
shift
parseXTransOffset "$1"
shift
;;
--ytrans|--ytrans-offset|--yoffset)
shift
parseYTransOffset "$1"
shift
;;
--simulate|--dry-run)
SIMULATE=$TRUE
shift
;;
--install|--self-install)
RUN_SELF_INSTALL=$TRUE
shift
if [[ ${1:0:1} != "-" ]]; then
TARGET_LOC="$1"
shift
fi
;;
--upgrade|--self-upgrade)
RUN_SELF_UPGRADE=$TRUE
shift
;;
--insecure|--no-check-certificate)
HTTPS_INSECURE=$TRUE
shift
;;
--yes|--assume-yes)
ASSUME_YES=$TRUE
shift
;;
--print-gs-call|--gs-call)
PRINT_GS_CALL=$TRUE
shift
;;
*)
initError "Invalid Parameter: \"$1\"" $EXIT_INVALID_OPTION
;;
esac
done
shouldInstall && selfInstall "$TARGET_LOC" # WILL EXIT HERE
shouldUpgrade && selfUpgrade # WILL EXIT HERE
isEmpty "${_optArgs[2]}" || initError "Seems like you passed an extra file name?"$'\n'"Invalid option: ${_optArgs[2]}" $EXIT_INVALID_OPTION
if isJustIdentify; then
isEmpty "${_optArgs[1]}" || initError "Seems like you passed an extra file name?"$'\n'"Invalid option: ${_optArgs[1]}" $EXIT_INVALID_OPTION
VERBOSE=0 # remove verboseness if present
fi
# Validate input PDF file
INFILEPDF="${_optArgs[0]}"
isEmpty "$INFILEPDF" && initError "Input file is empty!" $EXIT_NO_INPUT_FILE
isPDF "$INFILEPDF" || initError "Input file is not a PDF file: $INFILEPDF" $EXIT_INPUT_NOT_PDF
isFile "$INFILEPDF" || initError "Input file not found: $INFILEPDF" $EXIT_FILE_NOT_FOUND
isReadable "$INFILEPDF" || initError "No read access to input file: $INFILEPDF"$'\nPermission Denied' $EXIT_NOREAD_PERMISSION
checkDeps
if isJustIdentify; then
return $TRUE # no need to get output file, so return already
fi
_tgtFile="${_optArgs[1]}"
local _autoName="${INFILEPDF%.*}" # remove possible stupid extension, like .pDF
local _exSuffix=""
isExplodeMode && _exSuffix='.Page%d'
if isMixedMode; then
isEmpty "$_tgtFile" && OUTFILEPDF="${_autoName}.$(uppercase $RESIZE_PAPER_TYPE).SCALED$_exSuffix.pdf"
elif isResizeMode; then
isEmpty "$_tgtFile" && OUTFILEPDF="${_autoName}.$(uppercase $RESIZE_PAPER_TYPE)$_exSuffix.pdf"
else
isEmpty "$_tgtFile" && OUTFILEPDF="${_autoName}.SCALED$_exSuffix.pdf"
fi
isNotEmpty "$_tgtFile" && OUTFILEPDF="${_tgtFile%.pdf}$_exSuffix.pdf"
validateOutFile
}
# Returns $TRUE if the install flag is set
shouldInstall() {
return $RUN_SELF_INSTALL
}
# Returns $TRUE if the upgrade flag is set
shouldUpgrade() {
return $RUN_SELF_UPGRADE
}
# Install pdfScale
selfInstall() {
#CURRENT_LOC="$(readlink -f $0)"
CURRENT_LOC="$(readlinkf $0)"
TARGET_LOC="$1"
isEmpty "$TARGET_LOC" && TARGET_LOC="/usr/local/bin/pdfscale"
VERBOSE=0
NEED_SUDO=$FALSE
printVersion 3 " - Self Install"
echo ""
echo "Current location : $CURRENT_LOC"
echo "Target location : $TARGET_LOC"
if [[ "$CURRENT_LOC" = "$TARGET_LOC" ]]; then
echo $'\n'"Error! Source and Target locations are the same!"
echo "Cannot copy to itself..."
exit $EXIT_INVALID_OPTION
fi
TARGET_FOLDER="$(dirname $TARGET_LOC)"
local _answer="NO"
if isNotDir "$TARGET_FOLDER"; then
echo $'\nThe target folder does not exist\n > '"$TARGET_FOLDER"
if assumeYes; then
echo ''
_answer="y"
else
read -p $'\nCreate the target folder? Y/y to continue > ' _answer
_answer="$(lowercase $_answer)"
fi
if [[ "$_answer" = "y" || "$_answer" = "yes" ]]; then
_answer="no"
if mkdir -p "$TARGET_FOLDER" 2>/dev/null; then
echo " > Folder Created!"
else
echo $'\n'"There was an error when trying to create the folder."
if assumeYes; then
echo $'\nTrying again with sudo, enter password if needed > '
_answer="y"
else
read -p $'\nDo you want to try again with sudo (as root)? Y/y to continue > ' _answer
_answer="$(lowercase $_answer)"
fi
if [[ "$_answer" = "y" || "$_answer" = "yes" ]]; then
NEED_SUDO=$TRUE
if sudo mkdir -p "$TARGET_FOLDER" 2>/dev/null; then
echo "Folder Created!"
else
echo "There was an error when trying to create the folder."
exit $EXIT_ERROR
fi
else
echo "Exiting..."
exit $EXIT_ERROR
fi
fi
else
echo "Exiting... (cancelled by user)"
exit $EXIT_ERROR
fi
fi
_answer="no"
if isFile "$TARGET_LOC"; then
echo $'\n'"The target file already exists: $TARGET_LOC"
if assumeYes; then
_answer="y"
else
read -p "Y/y to overwrite, anything else to cancel > " _answer
_answer="$(lowercase $_answer)"
fi
if [[ "$_answer" = "y" || "$_answer" = "yes" ]]; then
echo "Target will be replaced!"
else
echo "Exiting... (cancelled by user)"
exit $EXIT_ERROR
fi
fi
if [[ $NEED_SUDO -eq $TRUE ]]; then
if sudo cp "$CURRENT_LOC" "$TARGET_LOC"; then
sudo chmod +x "$TARGET_LOC"
echo $'\nSuccess! Program installed!'
echo " > $TARGET_LOC"
exit $EXIT_SUCCESS
else
echo "There was an error when trying to install the program."
exit $EXIT_ERROR
fi
fi
if cp "$CURRENT_LOC" "$TARGET_LOC"; then
chmod +x "$TARGET_LOC"
echo $'\nSuccess! Program installed!'
echo " > $TARGET_LOC"
exit $EXIT_SUCCESS
else
_answer="no"
echo "There was an error when trying to install pdfScale."
if assumeYes; then
echo $'\nTrying again with sudo, enter password if needed > '
_answer="y"
else
read -p $'Do you want to try again with sudo (as root)? Y/y to continue > ' _answer
_answer="$(lowercase $_answer)"
fi
if [[ "$_answer" = "y" || "$_answer" = "yes" ]]; then
NEED_SUDO=$TRUE
if sudo cp "$CURRENT_LOC" "$TARGET_LOC"; then
sudo chmod +x "$TARGET_LOC"
echo $'\nSuccess! Program installed!'
echo " > $TARGET_LOC"
exit $EXIT_SUCCESS
else
echo "There was an error when trying to install the program."
exit $EXIT_ERROR
fi
else
echo "Exiting... (cancelled by user)"
exit $EXIT_ERROR
fi
fi
exit $EXIT_ERROR
}
# Tries to download with curl or wget
getUrl() {
useInsecure && echo $'\nHTTPS Insecure flag is enabled!\nCertificates will be ignored by curl/wget\n'
local url="$1"
local target="$2"
local _stat=""
if isEmpty "$url" || isEmpty "$target"; then
echo "Error! Invalid parameters for download."
echo "URL > $url"
echo "TARGET > $target"
exit $EXIT_INVALID_OPTION
fi
WGET_BIN="$(command -v wget 2>/dev/null)"
CURL_BIN="$(command -v curl 2>/dev/null)"
if isExecutable "$WGET_BIN"; then
useInsecure && WGET_BIN="$WGET_BIN --no-check-certificate"
echo "Downloading file with wget"
_stat="$($WGET_BIN -O "$target" "$url" 2>&1)"
if [[ $? -eq 0 ]]; then
return $TRUE
else
echo "Error when downloading file!"
echo " > $url"
echo "Status:"
echo "$_stat"
exit $EXIT_ERROR
fi
elif isExecutable "$CURL_BIN"; then
useInsecure && CURL_BIN="$CURL_BIN --insecure"
echo "Downloading file with curl"
_stat="$($CURL_BIN -o "$target" -L "$url" 2>&1)"
if [[ $? -eq 0 ]]; then
return $TRUE
else
echo "Error when downloading file!"
echo " > $url"
echo "Status:"
echo "$_stat"
exit $EXIT_ERROR
fi
else
echo "Error! Could not find Wget or Curl to perform download."
echo "Please install either curl or wget and try again."
exit $EXIT_FILE_NOT_FOUND
fi
}
# Tries to remove temporary files from upgrade
clearUpgrade() {
echo $'\nCleaning up downloaded files from /tmp'
if isFile "$TMP_TARGET"; then
echo -n " > $TMP_TARGET > "
rm "$TMP_TARGET" 2>/dev/null && echo "Ok" || echo "Fail"
else
echo " > no temporary tarball was found to remove"
fi
if isDir "$TMP_EXTRACTED"; then
echo -n " > $TMP_EXTRACTED > "
rm -rf "$TMP_EXTRACTED" 2>/dev/null && echo "Ok" || echo "Fail"
else
echo " > no temporary master folder was found to remove"
fi
}
# Exit upgrade with message and status code
# $1 Mensagem (printed if not empty)
# $2 Status (defaults to $EXIT_ERROR)
exitUpgrade() {
isDir "$_cwd" && cd "$_cwd"
isNotEmpty "$1" && echo "$1"
clearUpgrade
isNotEmpty "$2" && exit $2
exit $EXIT_ERROR
}
# Downloads current version from github's MASTER branch
selfUpgrade() {
#CURRENT_LOC="$(readlink -f $0)"
CURRENT_LOC="$(readlinkf $0)"
_cwd="$(pwd)"
local _cur_tstamp="$(date '+%Y%m%d-%H%M%S')"
TMP_DIR='/tmp'
TMP_TARGET="$TMP_DIR/pdfScale_$_cur_tstamp.tar.gz"
TMP_EXTRACTED="$TMP_DIR/$PROJECT_NAME-$PROJECT_BRANCH"
local _answer="no"
printVersion 3 " - Self Upgrade"
echo $'\n'"Preparing download to temp folder"
echo " > $TMP_TARGET"
getUrl "$PROJECT_URL/archive/$PROJECT_BRANCH.tar.gz" "$TMP_TARGET"
if isNotFile "$TMP_TARGET"; then
echo "Error! Could not find downloaded file!"
exit $EXIT_FILE_NOT_FOUND
fi
echo $'\n'"Extracting compressed file"
cd "$TMP_DIR"
if ! (tar xzf "$TMP_TARGET" 2>/dev/null || gtar xzf "$TMP_TARGET" 2>/dev/null); then
exitUpgrade "Extraction error."
fi
if ! cd "$TMP_EXTRACTED" 2>/dev/null; then
exitUpgrade $'Error when accessing temporary folder\n > '"$TMP_EXTRACTED"
fi
if ! chmod +x pdfScale.sh; then
exitUpgrade $'Error when setting new pdfScale to executable\n > '"$TMP_EXTRACTED/pdfScale.sh"
fi
local newver="$(./pdfScale.sh --version 2>/dev/null)"
local curver="$(printVersion 3 2>/dev/null)"
newver=($newver)
curver=($curver)
newver=${newver[1]#v}
curver=${curver[1]#v}
echo $'\n'" Current Version is: $curver"
echo "Downloaded Version is: $newver"$'\n'
if [[ "$newver" = "$curver" ]]; then
echo "Seems like we have downloaded the same version that is installed."
elif isBiggerVersion "$newver" "$curver"; then
echo "Seems like the downloaded version is newer that the one installed."
elif isBiggerVersion "$curver" "$newver"; then
echo "Seems like the downloaded version is older that the one installed."
echo "It is basically a miracle or you have came from the future with this version!"
echo "BE CAREFUL NOT TO DELETE THE BETA/ALPHA VERSION WITH THIS UPDATE!"
else
exitUpgrade "An unidentified error has ocurred. Exiting..."
fi
if assumeYes; then
echo $'\n'"Assume yes activated, current version will be replaced with master branch"
_answer="y"
else
echo $'\n'"Are you sure that you want to replace the current installation with the downloaded one?"
read -p "Y/y to continue, anything else to cancel > " _answer
_answer="$(lowercase $_answer)"
fi
echo
if [[ "$_answer" = "y" || "$_answer" = "yes" ]]; then
echo "Upgrading..."
if cp "./pdfScale.sh" "$CURRENT_LOC" 2>/dev/null; then
chmod +x "$CURRENT_LOC"
exitUpgrade $'\n'"Success! Upgrade finished!"$'\n'" > $CURRENT_LOC" $EXIT_SUCCESS
else
_answer="no"