Bash Script to scale and/or resize PDFs from the command line.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

2257 rader
82 KiB

  1. #!/usr/bin/env bash
  2. # pdfScale.sh
  3. #
  4. # Scale PDF to specified percentage of original size.
  5. #
  6. # Gustavo Arnosti Neves - 2016 / 07 / 10
  7. # Latest Version - 2018 / 08 / 09
  8. #
  9. # This script: https://github.com/tavinus/pdfScale
  10. #
  11. # Related: http://ma.juii.net/blog/scale-page-content-of-pdf-files
  12. # And: https://gist.github.com/MichaelJCole/86e4968dbfc13256228a
  13. VERSION="2.4.0"
  14. ###################### EXTERNAL PROGRAMS #######################
  15. GSBIN="" # GhostScript Binary
  16. BCBIN="" # BC Math Binary
  17. IDBIN="" # Identify Binary
  18. PDFINFOBIN="" # PDF Info Binary
  19. MDLSBIN="" # MacOS mdls Binary
  20. ##################### ENVIRONMENT SET-UP #######################
  21. LC_MEASUREMENT="C" # To make sure our numbers have .decimals
  22. LC_ALL="C" # Some languages use , as decimal token
  23. LC_CTYPE="C"
  24. LC_NUMERIC="C"
  25. TRUE=0 # Silly stuff
  26. FALSE=1
  27. ########################### GLOBALS ############################
  28. SCALE="0.95" # scaling factor (0.95 = 95%, e.g.)
  29. VERBOSE=0 # verbosity Level
  30. PDFSCALE_NAME="$(basename $0)" # simplified name of this script
  31. OSNAME="$(uname 2>/dev/null)" # Check where we are running
  32. GS_RUN_STATUS="" # Holds GS error messages, signals errors
  33. INFILEPDF="" # Input PDF file name
  34. OUTFILEPDF="" # Output PDF file name
  35. JUST_IDENTIFY=$FALSE # Flag to just show PDF info
  36. ABORT_ON_OVERWRITE=$FALSE # Flag to abort if OUTFILEPDF already exists
  37. ADAPTIVEMODE=$TRUE # Automatically try to guess best mode
  38. AUTOMATIC_SCALING=$TRUE # Default scaling in $SCALE, disabled in resize mode
  39. MODE="" # Which page size detection to use
  40. RESIZE_PAPER_TYPE="" # Pre-defined paper to use
  41. CUSTOM_RESIZE_PAPER=$FALSE # If we are using a custom-defined paper
  42. FLIP_DETECTION=$TRUE # If we should run the Flip-detection
  43. FLIP_FORCE=$FALSE # If we should force Flipping
  44. AUTO_ROTATION='/PageByPage' # GS call auto-rotation setting
  45. PGWIDTH="" # Input PDF Page Width
  46. PGHEIGHT="" # Input PDF Page Height
  47. RESIZE_WIDTH="" # Resized PDF Page Width
  48. RESIZE_HEIGHT="" # Resized PDF Page Height
  49. ############################# Image resolution (dpi)
  50. IMAGE_RESOLUTION=300 # 300 is /Printer default
  51. ############################# Image compression setting
  52. # default screen ebook printer prepress
  53. # ColorImageDownsampleType /Subsample /Average /Bicubic /Bicubic /Bicubic
  54. IMAGE_DOWNSAMPLE_TYPE='/Bicubic'
  55. ############################# default PDF profile
  56. # /screen /ebook /printer /prepress /default
  57. # -dPDFSETTINGS=/screen (screen-view-only quality, 72 dpi images)
  58. # -dPDFSETTINGS=/ebook (low quality, 150 dpi images)
  59. # -dPDFSETTINGS=/printer (high quality, 300 dpi images)
  60. # -dPDFSETTINGS=/prepress (high quality, color preserving, 300 dpi imgs)
  61. # -dPDFSETTINGS=/default (almost identical to /screen)
  62. PDF_SETTINGS='/printer'
  63. ############################# default Scaling alignment
  64. VERT_ALIGN="CENTER"
  65. HOR_ALIGN="CENTER"
  66. ############################# Translation Offset to apply
  67. XTRANSOFFSET=0.0
  68. YTRANSOFFSET=0.0
  69. ############################# Background/Bleed color creation
  70. BACKGROUNDTYPE="NONE" # Should be NONE, CMYK or RGB only
  71. BACKGROUNDCOLOR="" # Color parameters for CMYK(4) or RGB(3)
  72. BACKGROUNDCALL="" # Actual PS call to be embedded
  73. BACKGROUNDLOG="No background (default)"
  74. ############################# Execution Flags
  75. SIMULATE=$FALSE # Avoid execution
  76. PRINT_GS_CALL=$FALSE # Print GS Call to stdout
  77. GS_CALL_STRING="" # Buffer
  78. ############################# Project Info
  79. PROJECT_NAME="pdfScale"
  80. PROJECT_URL="https://github.com/tavinus/$PROJECT_NAME"
  81. PROJECT_BRANCH='master'
  82. HTTPS_INSECURE=$FALSE
  83. ASSUME_YES=$FALSE
  84. RUN_SELF_INSTALL=$FALSE
  85. TARGET_LOC="/usr/local/bin/pdfscale"
  86. ########################## EXIT FLAGS ##########################
  87. EXIT_SUCCESS=0
  88. EXIT_ERROR=1
  89. EXIT_INVALID_PAGE_SIZE_DETECTED=10
  90. EXIT_FILE_NOT_FOUND=20
  91. EXIT_INPUT_NOT_PDF=21
  92. EXIT_INVALID_OPTION=22
  93. EXIT_NO_INPUT_FILE=23
  94. EXIT_INVALID_SCALE=24
  95. EXIT_MISSING_DEPENDENCY=25
  96. EXIT_IMAGEMAGIK_NOT_FOUND=26
  97. EXIT_MAC_MDLS_NOT_FOUND=27
  98. EXIT_PDFINFO_NOT_FOUND=28
  99. EXIT_NOWRITE_PERMISSION=29
  100. EXIT_NOREAD_PERMISSION=30
  101. EXIT_TEMP_FILE_EXISTS=40
  102. EXIT_INVALID_PAPER_SIZE=50
  103. EXIT_INVALID_IMAGE_RESOLUTION=51
  104. ############################# MAIN #############################
  105. # Main function called at the end
  106. main() {
  107. printPDFSizes # may exit here
  108. local finalRet=$EXIT_ERROR
  109. if isMixedMode; then
  110. initMain " Mixed Tasks: Resize & Scale"
  111. local tempFile=""
  112. local tempSuffix="$RANDOM$RANDOM""_TEMP_$RANDOM$RANDOM.pdf"
  113. outputFile="$OUTFILEPDF" # backup outFile name
  114. tempFile="${OUTFILEPDF%.pdf}.$tempSuffix" # set a temp file name
  115. if isFile "$tempFile"; then
  116. printError $'Error! Temporary file name already exists!\n'"File: $tempFile"$'\nAborting execution to avoid overwriting the file.\nPlease Try again...'
  117. exit $EXIT_TEMP_FILE_EXISTS
  118. fi
  119. OUTFILEPDF="$tempFile" # set output to tmp file
  120. pageResize # resize to tmp file
  121. finalRet=$?
  122. INFILEPDF="$tempFile" # get tmp file as input
  123. OUTFILEPDF="$outputFile" # reset final target
  124. PGWIDTH=$RESIZE_WIDTH # we already know the new page size
  125. PGHEIGHT=$RESIZE_HEIGHT # from the last command (Resize)
  126. vPrintPageSizes ' New'
  127. vPrintScaleFactor
  128. pageScale # scale the resized pdf
  129. finalRet=$(($finalRet+$?))
  130. # remove tmp file
  131. if isFile "$tempFile"; then
  132. rm "$tempFile" >/dev/null 2>&1 || printError "Error when removing temporary file: $tempFile"
  133. fi
  134. elif isResizeMode; then
  135. initMain " Single Task: Resize PDF Paper"
  136. vPrintScaleFactor "Disabled (resize only)"
  137. pageResize
  138. finalRet=$?
  139. else
  140. initMain " Single Task: Scale PDF Contents"
  141. local scaleMode=""
  142. isManualScaledMode && scaleMode='(manual)' || scaleMode='(auto)'
  143. vPrintScaleFactor "$SCALE $scaleMode"
  144. pageScale
  145. finalRet=$?
  146. fi
  147. if [[ $finalRet -eq $EXIT_SUCCESS ]] && isEmpty "$GS_RUN_STATUS"; then
  148. if isDryRun; then
  149. vprint " Final Status: Simulation completed successfully"
  150. else
  151. vprint " Final Status: File created successfully"
  152. fi
  153. else
  154. vprint " Final Status: Error detected. Exit status: $finalRet"
  155. printError "PdfScale: ERROR!"$'\n'"Ghostscript Debug Info:"$'\n'"$GS_RUN_STATUS"
  156. fi
  157. if isNotEmpty "$GS_CALL_STRING" && shouldPrintGSCall; then
  158. printf "%s" "$GS_CALL_STRING"
  159. fi
  160. return $finalRet
  161. }
  162. # Initializes PDF processing for all modes of operation
  163. initMain() {
  164. printVersion 1 'verbose'
  165. isNotEmpty "$1" && vprint "$1"
  166. local sim="FALSE"
  167. isDryRun && sim="TRUE (Simulating)"
  168. vprint " Dry-Run: $sim"
  169. vPrintFileInfo
  170. getPageSize
  171. vPrintPageSizes ' Source'
  172. }
  173. # Prints PDF Info and exits with $EXIT_SUCCESS, but only if $JUST_IDENTIFY is $TRUE
  174. printPDFSizes() {
  175. if [[ $JUST_IDENTIFY -eq $TRUE ]]; then
  176. VERBOSE=0
  177. printVersion 3 " - Paper Sizes"
  178. getPageSize || initError "Could not get pagesize!"
  179. local paperType="$(getGSPaperName $PGWIDTH $PGHEIGHT)"
  180. isEmpty "$paperType" && paperType="Custom Paper Size"
  181. printf '%s\n' "------------+-----------------------------"
  182. printf " File | %s\n" "$(basename "$INFILEPDF")"
  183. printf " Paper Type | %s\n" "$paperType"
  184. printf '%s\n' "------------+-----------------------------"
  185. printf '%s\n' " | WIDTH x HEIGHT"
  186. printf " Points | %+8s x %-8s\n" "$PGWIDTH" "$PGHEIGHT"
  187. printf " Milimeters | %+8s x %-8s\n" "$(pointsToMilimeters $PGWIDTH)" "$(pointsToMilimeters $PGHEIGHT)"
  188. printf " Inches | %+8s x %-8s\n" "$(pointsToInches $PGWIDTH)" "$(pointsToInches $PGHEIGHT)"
  189. exit $EXIT_SUCCESS
  190. fi
  191. return $EXIT_SUCCESS
  192. }
  193. ###################### GHOSTSCRIPT CALLS #######################
  194. # Runs the ghostscript scaling script
  195. pageScale() {
  196. # Compute translation factors to position pages
  197. CENTERXTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGWIDTH" | "$BCBIN")
  198. CENTERYTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGHEIGHT" | "$BCBIN")
  199. BXTRANS=$CENTERXTRANS
  200. BYTRANS=$CENTERYTRANS
  201. if [[ "$VERT_ALIGN" = "TOP" ]]; then
  202. BYTRANS=$(echo "scale=6; 2*$CENTERYTRANS" | "$BCBIN")
  203. elif [[ "$VERT_ALIGN" = "BOTTOM" ]]; then
  204. BYTRANS=0
  205. fi
  206. if [[ "$HOR_ALIGN" = "LEFT" ]]; then
  207. BXTRANS=0
  208. elif [[ "$HOR_ALIGN" = "RIGHT" ]]; then
  209. BXTRANS=$(echo "scale=6; 2*$CENTERXTRANS" | "$BCBIN")
  210. fi
  211. vprint " Vert-Align: $VERT_ALIGN"
  212. vprint " Hor-Align: $HOR_ALIGN"
  213. XTRANS=$(echo "scale=6; $BXTRANS + $XTRANSOFFSET" | "$BCBIN")
  214. YTRANS=$(echo "scale=6; $BYTRANS + $YTRANSOFFSET" | "$BCBIN")
  215. vprint "$(printf ' Translation X: %.2f = %.2f + %.2f (offset)' $XTRANS $BXTRANS $XTRANSOFFSET)"
  216. vprint "$(printf ' Translation Y: %.2f = %.2f + %.2f (offset)' $YTRANS $BYTRANS $YTRANSOFFSET)"
  217. local increase=$(echo "scale=0; (($SCALE - 1) * 100)/1" | "$BCBIN")
  218. vprint " Run Scaling: $increase %"
  219. vprint " Background: $BACKGROUNDLOG"
  220. GS_RUN_STATUS="$GS_RUN_STATUS""$(gsPageScale 2>&1)"
  221. GS_CALL_STRING="$GS_CALL_STRING"$'[GS SCALE CALL STARTS]\n'"$(gsPrintPageScale)"$'\n[GS SCALE CALL ENDS]\n'
  222. return $? # Last command is always returned I think
  223. }
  224. # Runs GS call for scaling, nothing else should run here
  225. gsPageScale() {
  226. if isDryRun; then
  227. return $TRUE
  228. fi
  229. # Scale page
  230. "$GSBIN" \
  231. -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \
  232. -dCompatibilityLevel="1.5" -dPDFSETTINGS="$PDF_SETTINGS" \
  233. -dColorImageResolution=$IMAGE_RESOLUTION -dGrayImageResolution=$IMAGE_RESOLUTION \
  234. -dColorImageDownsampleType="$IMAGE_DOWNSAMPLE_TYPE" -dGrayImageDownsampleType="$IMAGE_DOWNSAMPLE_TYPE" \
  235. -dColorConversionStrategy=/LeaveColorUnchanged \
  236. -dSubsetFonts=true -dEmbedAllFonts=true \
  237. -dDEVICEWIDTHPOINTS=$PGWIDTH -dDEVICEHEIGHTPOINTS=$PGHEIGHT \
  238. -sOutputFile="$OUTFILEPDF" \
  239. -c "<</BeginPage{$BACKGROUNDCALL$SCALE $SCALE scale $XTRANS $YTRANS translate}>> setpagedevice" \
  240. -f "$INFILEPDF"
  241. }
  242. # Prints GS call for scaling
  243. gsPrintPageScale() {
  244. local _call_str=""
  245. # Print Scale page command
  246. read -d '' _call_str<< _EOF_
  247. "$GSBIN" \
  248. -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \
  249. -dCompatibilityLevel="1.5" -dPDFSETTINGS="$PDF_SETTINGS" \
  250. -dColorImageResolution=$IMAGE_RESOLUTION -dGrayImageResolution=$IMAGE_RESOLUTION \
  251. -dColorImageDownsampleType="$IMAGE_DOWNSAMPLE_TYPE" -dGrayImageDownsampleType="$IMAGE_DOWNSAMPLE_TYPE" \
  252. -dColorConversionStrategy=/LeaveColorUnchanged \
  253. -dSubsetFonts=true -dEmbedAllFonts=true \
  254. -dDEVICEWIDTHPOINTS=$PGWIDTH -dDEVICEHEIGHTPOINTS=$PGHEIGHT \
  255. -sOutputFile="$OUTFILEPDF" \
  256. -c "<</BeginPage{$BACKGROUNDCALL$SCALE $SCALE scale $XTRANS $YTRANS translate}>> setpagedevice" \
  257. -f "$INFILEPDF"
  258. _EOF_
  259. echo -ne "$_call_str"
  260. }
  261. # Runs the ghostscript paper resize script
  262. pageResize() {
  263. # Get paper sizes from source if not resizing
  264. isResizePaperSource && { RESIZE_WIDTH=$PGWIDTH; RESIZE_HEIGHT=$PGHEIGHT; }
  265. # Get new paper sizes if not custom or source paper
  266. isNotCustomPaper && ! isResizePaperSource && getGSPaperSize "$RESIZE_PAPER_TYPE"
  267. vprint " Auto Rotate: $(basename $AUTO_ROTATION)"
  268. runFlipDetect
  269. vprint " Run Resizing: $(uppercase "$RESIZE_PAPER_TYPE") ( "$RESIZE_WIDTH" x "$RESIZE_HEIGHT" ) pts"
  270. GS_RUN_STATUS="$GS_RUN_STATUS""$(gsPageResize 2>&1)"
  271. GS_CALL_STRING="$GS_CALL_STRING"$'[GS RESIZE CALL STARTS]\n'"$(gsPrintPageResize)"$'\n[GS RESIZE CALL ENDS]\n'
  272. return $?
  273. }
  274. # Runs GS call for resizing, nothing else should run here
  275. gsPageResize() {
  276. if isDryRun; then
  277. return $TRUE
  278. fi
  279. # Change page size
  280. "$GSBIN" \
  281. -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \
  282. -dCompatibilityLevel="1.5" -dPDFSETTINGS="$PDF_SETTINGS" \
  283. -dColorImageResolution=$IMAGE_RESOLUTION -dGrayImageResolution=$IMAGE_RESOLUTION \
  284. -dColorImageDownsampleType="$IMAGE_DOWNSAMPLE_TYPE" -dGrayImageDownsampleType="$IMAGE_DOWNSAMPLE_TYPE" \
  285. -dColorConversionStrategy=/LeaveColorUnchanged \
  286. -dSubsetFonts=true -dEmbedAllFonts=true \
  287. -dDEVICEWIDTHPOINTS=$RESIZE_WIDTH -dDEVICEHEIGHTPOINTS=$RESIZE_HEIGHT \
  288. -dAutoRotatePages=$AUTO_ROTATION \
  289. -dFIXEDMEDIA -dPDFFitPage \
  290. -sOutputFile="$OUTFILEPDF" \
  291. -f "$INFILEPDF"
  292. return $?
  293. }
  294. # Prints GS call for resizing
  295. gsPrintPageResize() {
  296. # Print Resize page command
  297. local _call_str=""
  298. # Print Scale page command
  299. read -d '' _call_str<< _EOF_
  300. "$GSBIN" \
  301. -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \
  302. -dCompatibilityLevel="1.5" -dPDFSETTINGS="$PDF_SETTINGS" \
  303. -dColorImageResolution=$IMAGE_RESOLUTION -dGrayImageResolution=$IMAGE_RESOLUTION \
  304. -dColorImageDownsampleType="$IMAGE_DOWNSAMPLE_TYPE" -dGrayImageDownsampleType="$IMAGE_DOWNSAMPLE_TYPE" \
  305. -dColorConversionStrategy=/LeaveColorUnchanged \
  306. -dSubsetFonts=true -dEmbedAllFonts=true \
  307. -dDEVICEWIDTHPOINTS=$RESIZE_WIDTH -dDEVICEHEIGHTPOINTS=$RESIZE_HEIGHT \
  308. -dAutoRotatePages=$AUTO_ROTATION \
  309. -dFIXEDMEDIA -dPDFFitPage \
  310. -sOutputFile="$OUTFILEPDF" \
  311. -f "$INFILEPDF"
  312. _EOF_
  313. echo -ne "$_call_str"
  314. }
  315. # Returns $TRUE if we should use the source paper size, $FALSE otherwise
  316. isResizePaperSource() {
  317. [[ "$RESIZE_PAPER_TYPE" = 'source' ]] && return $TRUE
  318. return $FALSE
  319. }
  320. # Filp-Detect Logic
  321. runFlipDetect() {
  322. if isFlipForced; then
  323. vprint " Flip Detect: Forced Mode!"
  324. applyFlipRevert
  325. elif isFlipDetectionEnabled && shouldFlip; then
  326. vprint " Flip Detect: Wrong orientation detected!"
  327. applyFlipRevert
  328. elif ! isFlipDetectionEnabled; then
  329. vprint " Flip Detect: Disabled"
  330. else
  331. vprint " Flip Detect: No change needed"
  332. fi
  333. }
  334. # Inverts $RESIZE_HEIGHT with $RESIZE_WIDTH
  335. applyFlipRevert() {
  336. local tmpInverter=""
  337. tmpInverter=$RESIZE_HEIGHT
  338. RESIZE_HEIGHT=$RESIZE_WIDTH
  339. RESIZE_WIDTH=$tmpInverter
  340. vprint " Inverting Width <-> Height"
  341. }
  342. # Returns the $FLIP_DETECTION flag
  343. isFlipDetectionEnabled() {
  344. return $FLIP_DETECTION
  345. }
  346. # Returns the $FLIP_FORCE flag
  347. isFlipForced() {
  348. return $FLIP_FORCE
  349. }
  350. # Returns $TRUE if the the paper size will invert orientation from source, $FALSE otherwise
  351. shouldFlip() {
  352. [[ $PGWIDTH -gt $PGHEIGHT && $RESIZE_WIDTH -lt $RESIZE_HEIGHT ]] || [[ $PGWIDTH -lt $PGHEIGHT && $RESIZE_WIDTH -gt $RESIZE_HEIGHT ]] && return $TRUE
  353. return $FALSE
  354. }
  355. ########################## INITIALIZERS #########################
  356. # Loads external dependencies and checks for errors
  357. initDeps() {
  358. GREPBIN="$(which grep 2>/dev/null)"
  359. GSBIN="$(which gs 2>/dev/null)"
  360. BCBIN="$(which bc 2>/dev/null)"
  361. IDBIN=$(which identify 2>/dev/null)
  362. MDLSBIN="$(which mdls 2>/dev/null)"
  363. PDFINFOBIN="$(which pdfinfo 2>/dev/null)"
  364. vprint "Checking for basename, grep, ghostscript and bcmath"
  365. basename "" >/dev/null 2>&1 || printDependency 'basename'
  366. isNotAvailable "$GREPBIN" && printDependency 'grep'
  367. isNotAvailable "$GSBIN" && printDependency 'ghostscript'
  368. isNotAvailable "$BCBIN" && printDependency 'bc'
  369. return $TRUE
  370. }
  371. # Checks for dependencies errors, run after getting options
  372. checkDeps() {
  373. if [[ $MODE = "IDENTIFY" ]]; then
  374. vprint "Checking for imagemagick's identify"
  375. if isNotAvailable "$IDBIN"; then printDependency 'imagemagick'; fi
  376. fi
  377. if [[ $MODE = "PDFINFO" ]]; then
  378. vprint "Checking for pdfinfo"
  379. if isNotAvailable "$PDFINFOBIN"; then printDependency 'pdfinfo'; fi
  380. fi
  381. if [[ $MODE = "MDLS" ]]; then
  382. vprint "Checking for MacOS mdls"
  383. if isNotAvailable "$MDLSBIN"; then
  384. initError 'mdls executable was not found! Is this even MacOS?' $EXIT_MAC_MDLS_NOT_FOUND
  385. fi
  386. fi
  387. return $TRUE
  388. }
  389. ######################### CLI OPTIONS ##########################
  390. # Parse options
  391. getOptions() {
  392. local _optArgs=() # things that do not start with a '-'
  393. local _tgtFile="" # to set $OUTFILEPDF
  394. local _currParam="" # to enable case-insensitiveness
  395. while [ ${#} -gt 0 ]; do
  396. if [[ "${1:0:2}" = '--' ]]; then
  397. # Long Option, get lowercase version
  398. _currParam="$(lowercase ${1})"
  399. elif [[ "${1:0:1}" = '-' ]]; then
  400. # short Option, just assign
  401. _currParam="${1}"
  402. else
  403. # file name arguments, store as is and reset loop
  404. _optArgs+=("$1")
  405. shift
  406. continue
  407. fi
  408. case "$_currParam" in
  409. -v|--verbose)
  410. ((VERBOSE++))
  411. shift
  412. ;;
  413. -n|--no-overwrite|--nooverwrite)
  414. ABORT_ON_OVERWRITE=$TRUE
  415. shift
  416. ;;
  417. -h|--help)
  418. printHelp
  419. exit $EXIT_SUCCESS
  420. ;;
  421. -V|--version)
  422. printVersion 3
  423. exit $EXIT_SUCCESS
  424. ;;
  425. -i|--identify|--info)
  426. JUST_IDENTIFY=$TRUE
  427. shift
  428. ;;
  429. -s|--scale|--setscale|--set-scale)
  430. shift
  431. parseScale "$1"
  432. shift
  433. ;;
  434. -m|--mode|--paperdetect|--paper-detect|--pagesizemode|--page-size-mode)
  435. shift
  436. parseMode "$1"
  437. shift
  438. ;;
  439. -r|--resize)
  440. shift
  441. parsePaperResize "$1"
  442. shift
  443. ;;
  444. -p|--printpapers|--print-papers|--listpapers|--list-papers)
  445. printPaperInfo
  446. exit $EXIT_SUCCESS
  447. ;;
  448. -f|--flipdetection|--flip-detection|--flip-mode|--flipmode|--flipdetect|--flip-detect)
  449. shift
  450. parseFlipDetectionMode "$1"
  451. shift
  452. ;;
  453. -a|--autorotation|--auto-rotation|--autorotate|--auto-rotate)
  454. shift
  455. parseAutoRotationMode "$1"
  456. shift
  457. ;;
  458. --background-gray)
  459. shift
  460. parseGrayBackground $1
  461. shift
  462. ;;
  463. --background-rgb)
  464. shift
  465. parseRGBBackground $1
  466. shift
  467. ;;
  468. --background-cmyk)
  469. shift
  470. parseCMYKBackground $1
  471. shift
  472. ;;
  473. --pdf-settings)
  474. shift
  475. parsePDFSettings "$1"
  476. shift
  477. ;;
  478. --image-downsample)
  479. shift
  480. parseImageDownSample "$1"
  481. shift
  482. ;;
  483. --image-resolution)
  484. shift
  485. parseImageResolution "$1"
  486. shift
  487. ;;
  488. --horizontal-alignment|--hor-align|--xalign|--x-align)
  489. shift
  490. parseHorizontalAlignment "$1"
  491. shift
  492. ;;
  493. --vertical-alignment|--ver-align|--vert-align|--yalign|--y-align)
  494. shift
  495. parseVerticalAlignment "$1"
  496. shift
  497. ;;
  498. --xtrans|--xtrans-offset|--xoffset)
  499. shift
  500. parseXTransOffset "$1"
  501. shift
  502. ;;
  503. --ytrans|--ytrans-offset|--yoffset)
  504. shift
  505. parseYTransOffset "$1"
  506. shift
  507. ;;
  508. --simulate|--dry-run)
  509. SIMULATE=$TRUE
  510. shift
  511. ;;
  512. --install|--self-install)
  513. RUN_SELF_INSTALL=$TRUE
  514. shift
  515. if [[ ${1:0:1} != "-" ]]; then
  516. TARGET_LOC="$1"
  517. shift
  518. fi
  519. ;;
  520. --upgrade|--self-upgrade)
  521. RUN_SELF_UPGRADE=$TRUE
  522. shift
  523. ;;
  524. --insecure|--no-check-certificate)
  525. HTTPS_INSECURE=$TRUE
  526. shift
  527. ;;
  528. --yes|--assume-yes)
  529. ASSUME_YES=$TRUE
  530. shift
  531. ;;
  532. --print-gs-call|--gs-call)
  533. PRINT_GS_CALL=$TRUE
  534. shift
  535. ;;
  536. *)
  537. initError "Invalid Parameter: \"$1\"" $EXIT_INVALID_OPTION
  538. ;;
  539. esac
  540. done
  541. shouldInstall && selfInstall "$TARGET_LOC" # WILL EXIT HERE
  542. shouldUpgrade && selfUpgrade # WILL EXIT HERE
  543. isEmpty "${_optArgs[2]}" || initError "Seems like you passed an extra file name?"$'\n'"Invalid option: ${_optArgs[2]}" $EXIT_INVALID_OPTION
  544. if [[ $JUST_IDENTIFY -eq $TRUE ]]; then
  545. isEmpty "${_optArgs[1]}" || initError "Seems like you passed an extra file name?"$'\n'"Invalid option: ${_optArgs[1]}" $EXIT_INVALID_OPTION
  546. VERBOSE=0 # remove verboseness if present
  547. fi
  548. # Validate input PDF file
  549. INFILEPDF="${_optArgs[0]}"
  550. isEmpty "$INFILEPDF" && initError "Input file is empty!" $EXIT_NO_INPUT_FILE
  551. isPDF "$INFILEPDF" || initError "Input file is not a PDF file: $INFILEPDF" $EXIT_INPUT_NOT_PDF
  552. isFile "$INFILEPDF" || initError "Input file not found: $INFILEPDF" $EXIT_FILE_NOT_FOUND
  553. isReadable "$INFILEPDF" || initError "No read access to input file: $INFILEPDF"$'\nPermission Denied' $EXIT_NOREAD_PERMISSION
  554. checkDeps
  555. if [[ $JUST_IDENTIFY -eq $TRUE ]]; then
  556. return $TRUE # no need to get output file, so return already
  557. fi
  558. _tgtFile="${_optArgs[1]}"
  559. local _autoName="${INFILEPDF%.*}" # remove possible stupid extension, like .pDF
  560. if isMixedMode; then
  561. isEmpty "$_tgtFile" && OUTFILEPDF="${_autoName}.$(uppercase $RESIZE_PAPER_TYPE).SCALED.pdf"
  562. elif isResizeMode; then
  563. isEmpty "$_tgtFile" && OUTFILEPDF="${_autoName}.$(uppercase $RESIZE_PAPER_TYPE).pdf"
  564. else
  565. isEmpty "$_tgtFile" && OUTFILEPDF="${_autoName}.SCALED.pdf"
  566. fi
  567. isNotEmpty "$_tgtFile" && OUTFILEPDF="${_tgtFile%.pdf}.pdf"
  568. validateOutFile
  569. }
  570. # Returns $TRUE if the install flag is set
  571. shouldInstall() {
  572. return $RUN_SELF_INSTALL
  573. }
  574. # Returns $TRUE if the upgrade flag is set
  575. shouldUpgrade() {
  576. return $RUN_SELF_UPGRADE
  577. }
  578. # Install pdfScale
  579. selfInstall() {
  580. CURRENT_LOC="$(readlink -f $0)"
  581. TARGET_LOC="$1"
  582. isEmpty "$TARGET_LOC" && TARGET_LOC="/usr/local/bin/pdfscale"
  583. VERBOSE=0
  584. NEED_SUDO=$FALSE
  585. printVersion 3 " - Self Install"
  586. echo ""
  587. echo "Current location : $CURRENT_LOC"
  588. echo "Target location : $TARGET_LOC"
  589. if [[ "$CURRENT_LOC" = "$TARGET_LOC" ]]; then
  590. echo $'\n'"Error! Source and Target locations are the same!"
  591. echo "Cannot copy to itself..."
  592. exit $EXIT_INVALID_OPTION
  593. fi
  594. TARGET_FOLDER="$(dirname $TARGET_LOC)"
  595. local _answer="NO"
  596. if isNotDir "$TARGET_FOLDER"; then
  597. echo $'\nThe target folder does not exist\n > '"$TARGET_FOLDER"
  598. if assumeYes; then
  599. echo ''
  600. _answer="y"
  601. else
  602. read -p $'\nCreate the target folder? Y/y to continue > ' _answer
  603. _answer="$(lowercase $_answer)"
  604. fi
  605. if [[ "$_answer" = "y" || "$_answer" = "yes" ]]; then
  606. _answer="no"
  607. if mkdir -p "$TARGET_FOLDER" 2>/dev/null; then
  608. echo " > Folder Created!"
  609. else
  610. echo $'\n'"There was an error when trying to create the folder."
  611. if assumeYes; then
  612. echo $'\nTrying again with sudo, enter password if needed > '
  613. _answer="y"
  614. else
  615. read -p $'\nDo you want to try again with sudo (as root)? Y/y to continue > ' _answer
  616. _answer="$(lowercase $_answer)"
  617. fi
  618. if [[ "$_answer" = "y" || "$_answer" = "yes" ]]; then
  619. NEED_SUDO=$TRUE
  620. if sudo mkdir -p "$TARGET_FOLDER" 2>/dev/null; then
  621. echo "Folder Created!"
  622. else
  623. echo "There was an error when trying to create the folder."
  624. exit $EXIT_ERROR
  625. fi
  626. else
  627. echo "Exiting..."
  628. exit $EXIT_ERROR
  629. fi
  630. fi
  631. else
  632. echo "Exiting... (cancelled by user)"
  633. exit $EXIT_ERROR
  634. fi
  635. fi
  636. _answer="no"
  637. if isFile "$TARGET_LOC"; then
  638. echo $'\n'"The target file already exists: $TARGET_LOC"
  639. if assumeYes; then
  640. _answer="y"
  641. else
  642. read -p "Y/y to overwrite, anything else to cancel > " _answer
  643. _answer="$(lowercase $_answer)"
  644. fi
  645. if [[ "$_answer" = "y" || "$_answer" = "yes" ]]; then
  646. echo "Target will be replaced!"
  647. else
  648. echo "Exiting... (cancelled by user)"
  649. exit $EXIT_ERROR
  650. fi
  651. fi
  652. if [[ $NEED_SUDO -eq $TRUE ]]; then
  653. if sudo cp "$CURRENT_LOC" "$TARGET_LOC"; then
  654. echo $'\nSuccess! Program installed!'
  655. echo " > $TARGET_LOC"
  656. exit $EXIT_SUCCESS
  657. else
  658. echo "There was an error when trying to install the program."
  659. exit $EXIT_ERROR
  660. fi
  661. fi
  662. if cp "$CURRENT_LOC" "$TARGET_LOC"; then
  663. echo $'\nSuccess! Program installed!'
  664. echo " > $TARGET_LOC"
  665. exit $EXIT_SUCCESS
  666. else
  667. _answer="no"
  668. echo "There was an error when trying to install pdfScale."
  669. if assumeYes; then
  670. echo $'\nTrying again with sudo, enter password if needed > '
  671. _answer="y"
  672. else
  673. read -p $'Do you want to try again with sudo (as root)? Y/y to continue > ' _answer
  674. _answer="$(lowercase $_answer)"
  675. fi
  676. if [[ "$_answer" = "y" || "$_answer" = "yes" ]]; then
  677. NEED_SUDO=$TRUE
  678. if sudo cp "$CURRENT_LOC" "$TARGET_LOC"; then
  679. echo $'\nSuccess! Program installed!'
  680. echo " > $TARGET_LOC"
  681. exit $EXIT_SUCCESS
  682. else
  683. echo "There was an error when trying to install the program."
  684. exit $EXIT_ERROR
  685. fi
  686. else
  687. echo "Exiting... (cancelled by user)"
  688. exit $EXIT_ERROR
  689. fi
  690. fi
  691. exit $EXIT_ERROR
  692. }
  693. # Tries to download with curl or wget
  694. getUrl() {
  695. useInsecure && echo $'\nHTTPS Insecure flag is enabled!\nCertificates will be ignored by curl/wget\n'
  696. local url="$1"
  697. local target="$2"
  698. local _stat=""
  699. if isEmpty "$url" || isEmpty "$target"; then
  700. echo "Error! Invalid parameters for download."
  701. echo "URL > $url"
  702. echo "TARGET > $target"
  703. exit $EXIT_INVALID_OPTION
  704. fi
  705. WGET_BIN="$(which wget 2>/dev/null)"
  706. CURL_BIN="$(which curl 2>/dev/null)"
  707. if isExecutable "$WGET_BIN"; then
  708. useInsecure && WGET_BIN="$WGET_BIN --no-check-certificate"
  709. echo "Downloading file with wget"
  710. _stat="$($WGET_BIN -O "$target" "$url" 2>&1)"
  711. if [[ $? -eq 0 ]]; then
  712. return $TRUE
  713. else
  714. echo "Error when downloading file!"
  715. echo " > $url"
  716. echo "Status:"
  717. echo "$_stat"
  718. exit $EXIT_ERROR
  719. fi
  720. elif isExecutable "$CURL_BIN"; then
  721. useInsecure && CURL_BIN="$CURL_BIN --insecure"
  722. echo "Downloading file with curl"
  723. _stat="$($CURL_BIN -o "$target" "$url" 2>&1)"
  724. if [[ $? -eq 0 ]]; then
  725. return $TRUE
  726. else
  727. echo "Error when downloading file!"
  728. echo " > $url"
  729. echo "Status:"
  730. echo "$_stat"
  731. exit $EXIT_ERROR
  732. fi
  733. else
  734. echo "Error! Could not find Wget or Curl to perform download."
  735. echo "Please install either curl or wget and try again."
  736. exit $EXIT_FILE_NOT_FOUND
  737. fi
  738. }
  739. # Tries to remove temporary files from upgrade
  740. clearUpgrade() {
  741. echo $'\nCleaning up downloaded files from /tmp'
  742. if isFile "$TMP_TARGET"; then
  743. echo -n " > $TMP_TARGET > "
  744. rm "$TMP_TARGET" 2>/dev/null && echo "Ok" || echo "Fail"
  745. else
  746. echo " > no temporary tarball was found to remove"
  747. fi
  748. if isDir "$TMP_EXTRACTED"; then
  749. echo -n " > $TMP_EXTRACTED > "
  750. rm -rf "$TMP_EXTRACTED" 2>/dev/null && echo "Ok" || echo "Fail"
  751. else
  752. echo " > no temporary master folder was found to remove"
  753. fi
  754. }
  755. # Exit upgrade with message and status code
  756. # $1 Mensagem (printed if not empty)
  757. # $2 Status (defaults to $EXIT_ERROR)
  758. exitUpgrade() {
  759. isDir "$_cwd" && cd "$_cwd"
  760. isNotEmpty "$1" && echo "$1"
  761. clearUpgrade
  762. isNotEmpty "$2" && exit $2
  763. exit $EXIT_ERROR
  764. }
  765. # Downloads current version from github's MASTER branch
  766. selfUpgrade() {
  767. CURRENT_LOC="$(readlink -f $0)"
  768. _cwd="$(pwd)"
  769. local _cur_tstamp="$(date '+%Y%m%d-%H%M%S')"
  770. TMP_DIR='/tmp'
  771. TMP_TARGET="$TMP_DIR/pdfScale_$_cur_tstamp.tar.gz"
  772. TMP_EXTRACTED="$TMP_DIR/$PROJECT_NAME-$PROJECT_BRANCH"
  773. local _answer="no"
  774. printVersion 3 " - Self Upgrade"
  775. echo $'\n'"Preparing download to temp folder"
  776. echo " > $TMP_TARGET"
  777. getUrl "$PROJECT_URL/archive/$PROJECT_BRANCH.tar.gz" "$TMP_TARGET"
  778. if isNotFile "$TMP_TARGET"; then
  779. echo "Error! Could not find downloaded file!"
  780. exit $EXIT_FILE_NOT_FOUND
  781. fi
  782. echo $'\n'"Extracting compressed file"
  783. cd "$TMP_DIR"
  784. if ! (tar xzf "$TMP_TARGET" 2>/dev/null || gtar xzf "$TMP_TARGET" 2>/dev/null); then
  785. exitUpgrade "Extraction error."
  786. fi
  787. if ! cd "$TMP_EXTRACTED" 2>/dev/null; then
  788. exitUpgrade $'Error when accessing temporary folder\n > '"$TMP_EXTRACTED"
  789. fi
  790. if ! chmod +x pdfScale.sh; then
  791. exitUpgrade $'Error when setting new pdfScale to executable\n > '"$TMP_EXTRACTED/pdfScale.sh"
  792. fi
  793. local newver="$(./pdfScale.sh --version 2>/dev/null)"
  794. local curver="$(printVersion 3 2>/dev/null)"
  795. newver=($newver)
  796. curver=($curver)
  797. newver=${newver[1]#v}
  798. curver=${curver[1]#v}
  799. echo $'\n'" Current Version is: $curver"
  800. echo "Downloaded Version is: $newver"$'\n'
  801. if [[ "$newver" = "$curver" ]]; then
  802. echo "Seems like we have downloaded the same version that is installed."
  803. elif isBiggerVersion "$newver" "$curver"; then
  804. echo "Seems like the downloaded version is newer that the one installed."
  805. elif isBiggerVersion "$curver" "$newver"; then
  806. echo "Seems like the downloaded version is older that the one installed."
  807. echo "It is basically a miracle or you have came from the future with this version!"
  808. echo "BE CAREFUL NOT TO DELETE THE BETA/ALPHA VERSION WITH THIS UPDATE!"
  809. else
  810. exitUpgrade "An unidentified error has ocurred. Exiting..."
  811. fi
  812. if assumeYes; then
  813. echo $'\n'"Assume yes activated, current version will be replaced with master branch"
  814. _answer="y"
  815. else
  816. echo $'\n'"Are you sure that you want to replace the current installation with the downloaded one?"
  817. read -p "Y/y to continue, anything else to cancel > " _answer
  818. _answer="$(lowercase $_answer)"
  819. fi
  820. echo
  821. if [[ "$_answer" = "y" || "$_answer" = "yes" ]]; then
  822. echo "Upgrading..."
  823. if cp "./pdfScale.sh" "$CURRENT_LOC" 2>/dev/null; then
  824. exitUpgrade $'\n'"Success! Upgrade finished!"$'\n'" > $CURRENT_LOC" $EXIT_SUCCESS
  825. else
  826. _answer="no"
  827. echo $'\n'"There was an error when copying the new version."
  828. if assumeYes; then
  829. echo $'\nAssume yes activated, retrying with sudo.\nEnter password if needed > \n'
  830. _answer="y"
  831. else
  832. echo "Do you want to retry using sudo (as root)?"
  833. read -p "Y/y to continue, anything else to cancel > " _answer
  834. fi
  835. _answer="$(lowercase $_answer)"
  836. if [[ "$_answer" = "y" || "$_answer" = "yes" ]]; then
  837. echo "Upgrading with sudo..."
  838. if sudo cp "./pdfScale.sh" "$CURRENT_LOC" 2>/dev/null; then
  839. exitUpgrade $'\n'"Success! Upgrade finished!"$'\n'" > $CURRENT_LOC" $EXIT_SUCCESS
  840. else
  841. exitUpgrade "There was an error when copying the new version."
  842. fi
  843. else
  844. exitUpgrade "Exiting... (cancelled by user)"
  845. fi
  846. fi
  847. exitUpgrade "An unidentified error has ocurred. Exiting..."
  848. else
  849. exitUpgrade "Exiting... (cancelled by user)"
  850. fi
  851. exitUpgrade "An unidentified error has ocurred. Exiting..."
  852. }
  853. # Compares versions with x.x.x format
  854. isBiggerVersion() {
  855. local OIFS=$IFS
  856. IFS='.'
  857. local _first=($1)
  858. local _second=($2)
  859. local _ret=$FALSE
  860. if [[ ${_first[0]} -gt ${_second[0]} ]]; then
  861. _ret=$TRUE
  862. elif [[ ${_first[0]} -lt ${_second[0]} ]]; then
  863. _ret=$FALSE
  864. elif [[ ${_first[1]} -gt ${_second[1]} ]]; then
  865. _ret=$TRUE
  866. elif [[ ${_first[1]} -lt ${_second[1]} ]]; then
  867. _ret=$FALSE
  868. elif [[ ${_first[2]} -gt ${_second[2]} ]]; then
  869. _ret=$TRUE
  870. elif [[ ${_first[2]} -lt ${_second[2]} ]]; then
  871. _ret=$FALSE
  872. fi
  873. IFS=$OIFS
  874. return $_ret
  875. }
  876. # Checks if output file is valid and writable
  877. validateOutFile() {
  878. local _tgtDir="$(dirname "$OUTFILEPDF")"
  879. isDir "$_tgtDir" || initError "Output directory does not exist!"$'\n'"Target Dir: $_tgtDir" $EXIT_NOWRITE_PERMISSION
  880. isAbortOnOverwrite && isFile "$OUTFILEPDF" && initError $'Output file already exists and --no-overwrite was used!\nRemove the "-n" or "--no-overwrite" option if you want to overwrite the file\n'"Target File: $OUTFILEPDF" $EXIT_NOWRITE_PERMISSION
  881. isTouchable "$OUTFILEPDF" || initError "Could not get write permission for output file!"$'\n'"Target File: $OUTFILEPDF"$'\nPermission Denied' $EXIT_NOWRITE_PERMISSION
  882. }
  883. # Returns $TRUE if we should not overwrite $OUTFILEPDF, $FALSE otherwise
  884. isAbortOnOverwrite() {
  885. return $ABORT_ON_OVERWRITE
  886. }
  887. # Returns $TRUE if we should print the GS call to stdout
  888. shouldPrintGSCall() {
  889. return $PRINT_GS_CALL
  890. }
  891. # Returns $TRUE if we are simulating, dry-run (no GS execution)
  892. isDryRun() {
  893. return $SIMULATE
  894. }
  895. # Parses and validates the scaling factor
  896. parseScale() {
  897. AUTOMATIC_SCALING=$FALSE
  898. if ! isFloatBiggerThanZero "$1"; then
  899. printError "Invalid factor: $1"
  900. printError "The factor must be a floating point number greater than 0"
  901. printError "Example: for 80% use 0.8"
  902. exit $EXIT_INVALID_SCALE
  903. fi
  904. SCALE="$1"
  905. }
  906. # Parse a forced mode of operation
  907. parseMode() {
  908. local param="$(lowercase $1)"
  909. case "${param}" in
  910. c|catgrep|'cat+grep'|grep|g)
  911. ADAPTIVEMODE=$FALSE
  912. MODE="CATGREP"
  913. return $TRUE
  914. ;;
  915. i|imagemagick|identify)
  916. ADAPTIVEMODE=$FALSE
  917. MODE="IDENTIFY"
  918. return $TRUE
  919. ;;
  920. m|mdls|quartz|mac)
  921. ADAPTIVEMODE=$FALSE
  922. MODE="MDLS"
  923. return $TRUE
  924. ;;
  925. p|pdfinfo)
  926. ADAPTIVEMODE=$FALSE
  927. MODE="PDFINFO"
  928. return $TRUE
  929. ;;
  930. a|auto|automatic|adaptive)
  931. ADAPTIVEMODE=$TRUE
  932. MODE=""
  933. return $TRUE
  934. ;;
  935. *)
  936. initError "Invalid PDF Size Detection Mode: \"$1\"" $EXIT_INVALID_OPTION
  937. return $FALSE
  938. ;;
  939. esac
  940. return $FALSE
  941. }
  942. # Parses and validates the scaling factor
  943. parseFlipDetectionMode() {
  944. local param="$(lowercase $1)"
  945. case "${param}" in
  946. d|disable)
  947. FLIP_DETECTION=$FALSE
  948. FLIP_FORCE=$FALSE
  949. ;;
  950. f|force)
  951. FLIP_DETECTION=$FALSE
  952. FLIP_FORCE=$TRUE
  953. ;;
  954. a|auto|automatic)
  955. FLIP_DETECTION=$TRUE
  956. FLIP_FORCE=$FALSE
  957. ;;
  958. *)
  959. initError "Invalid Flip Detection Mode: \"$1\"" $EXIT_INVALID_OPTION
  960. return $FALSE
  961. ;;
  962. esac
  963. }
  964. # Parses and validates the scaling factor
  965. parseAutoRotationMode() {
  966. local param="$(lowercase $1)"
  967. case "${param}" in
  968. n|none|'/none')
  969. AUTO_ROTATION='/None'
  970. ;;
  971. a|all|'/all')
  972. AUTO_ROTATION='/All'
  973. ;;
  974. p|pagebypage|'/pagebypage'|auto)
  975. AUTO_ROTATION='/PageByPage'
  976. ;;
  977. *)
  978. initError "Invalid Auto Rotation Mode: \"$1\"" $EXIT_INVALID_OPTION
  979. return $FALSE
  980. ;;
  981. esac
  982. }
  983. # Validades the a paper resize CLI option and sets the paper to $RESIZE_PAPER_TYPE
  984. parsePaperResize() {
  985. isEmpty "$1" && initError 'Invalid Paper Type: (empty)' $EXIT_INVALID_PAPER_SIZE
  986. local lowercasePaper="$(lowercase $1)"
  987. local customPaper=($lowercasePaper)
  988. if [[ "$customPaper" = 'same' || "$customPaper" = 'keep' || "$customPaper" = 'source' ]]; then
  989. RESIZE_PAPER_TYPE='source'
  990. elif [[ "${customPaper[0]}" = 'custom' ]]; then
  991. if isNotValidMeasure "${customPaper[1]}" || ! isFloatBiggerThanZero "${customPaper[2]}" || ! isFloatBiggerThanZero "${customPaper[3]}"; then
  992. initError "Invalid Custom Paper Definition!"$'\n'"Use: -r 'custom <measurement> <width> <height>'"$'\n'"Measurements: mm, in, pts" $EXIT_INVALID_OPTION
  993. fi
  994. RESIZE_PAPER_TYPE="custom"
  995. CUSTOM_RESIZE_PAPER=$TRUE
  996. if isMilimeter "${customPaper[1]}"; then
  997. RESIZE_WIDTH="$(milimetersToPoints "${customPaper[2]}")"
  998. RESIZE_HEIGHT="$(milimetersToPoints "${customPaper[3]}")"
  999. elif isInch "${customPaper[1]}"; then
  1000. RESIZE_WIDTH="$(inchesToPoints "${customPaper[2]}")"
  1001. RESIZE_HEIGHT="$(inchesToPoints "${customPaper[3]}")"
  1002. elif isPoint "${customPaper[1]}"; then
  1003. RESIZE_WIDTH="${customPaper[2]}"
  1004. RESIZE_HEIGHT="${customPaper[3]}"
  1005. else
  1006. initError "Invalid Custom Paper Definition!"$'\n'"Use: -r 'custom <measurement> <width> <height>'"$'\n'"Measurements: mm, in, pts" $EXIT_INVALID_OPTION
  1007. fi
  1008. else
  1009. isPaperName "$lowercasePaper" || initError "Invalid Paper Type: $1" $EXIT_INVALID_PAPER_SIZE
  1010. RESIZE_PAPER_TYPE="$lowercasePaper"
  1011. fi
  1012. }
  1013. # Goes to GS -dColorImageResolution and -dGrayImageResolution parameters
  1014. parseImageResolution() {
  1015. if isNotAnInteger "$1"; then
  1016. printError "Invalid image resolution: $1"
  1017. printError "The image resolution must be an integer"
  1018. exit $EXIT_INVALID_IMAGE_RESOLUTION
  1019. fi
  1020. IMAGE_RESOLUTION="$1"
  1021. }
  1022. # Goes to GS -dColorImageDownsampleType and -dGrayImageDownsampleType parameters
  1023. parseImageDownSample() {
  1024. local param="$(lowercase $1)"
  1025. case "${param}" in
  1026. s|subsample|'/subsample')
  1027. IMAGE_DOWNSAMPLE_TYPE='/Subsample'
  1028. ;;
  1029. a|average|'/average')
  1030. IMAGE_DOWNSAMPLE_TYPE='/Average'
  1031. ;;
  1032. b|bicubic|'/bicubic'|auto)
  1033. IMAGE_DOWNSAMPLE_TYPE='/Bicubic'
  1034. ;;
  1035. *)
  1036. initError "Invalid Image Downsample Mode: \"$1\"" $EXIT_INVALID_OPTION
  1037. return $FALSE
  1038. ;;
  1039. esac
  1040. }
  1041. # Goes to GS -dColorImageDownsampleType and -dGrayImageDownsampleType parameters
  1042. parsePDFSettings() {
  1043. local param="$(lowercase $1)"
  1044. case "${param}" in
  1045. s|screen|'/screen')
  1046. PDF_SETTINGS='/screen'
  1047. ;;
  1048. e|ebook|'/ebook')
  1049. PDF_SETTINGS='/ebook'
  1050. ;;
  1051. p|printer|'/printer'|auto)
  1052. PDF_SETTINGS='/printer'
  1053. ;;
  1054. r|prepress|'/prepress')
  1055. PDF_SETTINGS='/prepress'
  1056. ;;
  1057. d|default|'/default')
  1058. PDF_SETTINGS='/default'
  1059. ;;
  1060. *)
  1061. initError "Invalid PDF Setting Profile: \"$1\""$'\nValid > printer, screen, ebook, prepress, default' $EXIT_INVALID_OPTION
  1062. return $FALSE
  1063. ;;
  1064. esac
  1065. }
  1066. # How to position the resized pages (sets translation)
  1067. parseHorizontalAlignment() {
  1068. local param="$(lowercase $1)"
  1069. case "${param}" in
  1070. l|left)
  1071. HOR_ALIGN='LEFT'
  1072. ;;
  1073. r|right)
  1074. HOR_ALIGN='RIGHT'
  1075. ;;
  1076. c|center|middle)
  1077. HOR_ALIGN='CENTER'
  1078. ;;
  1079. *)
  1080. initError "Invalid Horizontal Alignment Setting: \"$1\""$'\nValid > left, right, center' $EXIT_INVALID_OPTION
  1081. return $FALSE
  1082. ;;
  1083. esac
  1084. }
  1085. # How to position the resized pages (sets translation)
  1086. parseVerticalAlignment() {
  1087. local param="$(lowercase $1)"
  1088. case "${param}" in
  1089. t|top)
  1090. VERT_ALIGN='TOP'
  1091. ;;
  1092. b|bottom|bot)
  1093. VERT_ALIGN='BOTTOM'
  1094. ;;
  1095. c|center|middle)
  1096. VERT_ALIGN='CENTER'
  1097. ;;
  1098. *)
  1099. initError "Invalid Vertical Alignment Setting: \"$1\""$'\nValid > top, bottom, center' $EXIT_INVALID_OPTION
  1100. return $FALSE
  1101. ;;
  1102. esac
  1103. }
  1104. # Set X Translation Offset
  1105. parseXTransOffset() {
  1106. if isFloat "$1"; then
  1107. XTRANSOFFSET="$1"
  1108. return $TRUE
  1109. fi
  1110. printError "Invalid X Translation Offset: $1"
  1111. printError "The X Translation Offset must be a floating point number"
  1112. exit $EXIT_INVALID_OPTION
  1113. }
  1114. # Set Y Translation Offset
  1115. parseYTransOffset() {
  1116. if isFloat "$1"; then
  1117. YTRANSOFFSET="$1"
  1118. return $TRUE
  1119. fi
  1120. printError "Invalid Y Translation Offset: $1"
  1121. printError "The Y Translation Offset must be a floating point number"
  1122. exit $EXIT_INVALID_OPTION
  1123. }
  1124. # Parse Gray Background color
  1125. parseGrayBackground() {
  1126. if isFloatPercentage "$1"; then
  1127. BACKGROUNDCOLOR="$1"
  1128. BACKGROUNDCALL="$BACKGROUNDCOLOR setgray clippath fill " # the space at the end is important!
  1129. BACKGROUNDTYPE="GRAY"
  1130. BACKGROUNDLOG="$GrayColor Mode > $BACKGROUNDCOLOR"
  1131. return $TRUE
  1132. fi
  1133. printError "Invalid Gray Background color."
  1134. printError "Need 1 floating point number between 0 and 1."
  1135. printError "Eg: --background-gray \"0.80\""
  1136. printError "Invalid Param => $1"
  1137. exit $EXIT_INVALID_OPTION
  1138. }
  1139. # Parse CMYK Background color
  1140. parseCMYKBackground() {
  1141. if isFloatPercentage "$1" && isFloatPercentage "$2" && isFloatPercentage "$3" && isFloatPercentage "$4"; then
  1142. BACKGROUNDCOLOR="$1 $2 $3 $4"
  1143. BACKGROUNDCALL="$BACKGROUNDCOLOR setcmykcolor clippath fill " # the space at the end is important!
  1144. BACKGROUNDTYPE="CMYK"
  1145. BACKGROUNDLOG="$BACKGROUNDTYPE Mode > $BACKGROUNDCOLOR"
  1146. return $TRUE
  1147. fi
  1148. printError "Invalid CMYK Background colors."
  1149. printError "Need 4 floating point numbers between 0 and 1 in CMYK order."
  1150. printError "Eg: --background-cmyk \"C M Y K\""
  1151. printError " [C] => $1"
  1152. printError " [M] => $2"
  1153. printError " [Y] => $3"
  1154. printError " [K] => $4"
  1155. exit $EXIT_INVALID_OPTION
  1156. }
  1157. # Just loads the RGB Vars (without testing anything)
  1158. loadRGBVars(){
  1159. BACKGROUNDCOLOR="$1 $2 $3"
  1160. BACKGROUNDCALL="$BACKGROUNDCOLOR setrgbcolor clippath fill " # the space at the end is important!
  1161. BACKGROUNDTYPE="RGB"
  1162. BACKGROUNDLOG="$BACKGROUNDTYPE Mode > $BACKGROUNDCOLOR"
  1163. }
  1164. # Parse RGB Background color
  1165. parseRGBBackground() {
  1166. if isFloatPercentage "$1" && isFloatPercentage "$2" && isFloatPercentage "$3" ; then
  1167. loadRGBVars "$1" "$2" "$3"
  1168. return $TRUE
  1169. fi
  1170. if isRGBInteger "$1" && isRGBInteger "$2" && isRGBInteger "$3" ; then
  1171. loadRGBVars "$1" "$2" "$3"
  1172. return $TRUE
  1173. fi
  1174. printError "Invalid RGB Background colors. Need 3 parameters in RGB order."
  1175. printError "Numbers can be EITHER percentages between 0 and 1 or RGB integers between 0 and 255."
  1176. printError "Eg: --background-rgb \"34 123 255\""
  1177. printError " [R] => $1"
  1178. printError " [G] => $2"
  1179. printError " [B] => $3"
  1180. exit $EXIT_INVALID_OPTION
  1181. }
  1182. ################### PDF PAGE SIZE DETECTION ####################
  1183. ################################################################
  1184. # Detects operation mode and also runs the adaptive mode
  1185. # PAGESIZE LOGIC
  1186. # 1- Try to get Mediabox with GREP
  1187. # 2- MacOS => try to use mdls
  1188. # 3- Try to use pdfinfo
  1189. # 4- Try to use identify (imagemagick)
  1190. # 5- Fail
  1191. ################################################################
  1192. getPageSize() {
  1193. if isNotAdaptiveMode; then
  1194. vprint " Get Page Size: Adaptive Disabled"
  1195. if [[ $MODE = "CATGREP" ]]; then
  1196. vprint " Method: Grep"
  1197. getPageSizeCatGrep
  1198. elif [[ $MODE = "MDLS" ]]; then
  1199. vprint " Method: Mac Quartz mdls"
  1200. getPageSizeMdls
  1201. elif [[ $MODE = "PDFINFO" ]]; then
  1202. vprint " Method: PDFInfo"
  1203. getPageSizePdfInfo
  1204. elif [[ $MODE = "IDENTIFY" ]]; then
  1205. vprint " Method: ImageMagick's Identify"
  1206. getPageSizeImagemagick
  1207. else
  1208. printError "Error! Invalid Mode: $MODE"
  1209. printError "Aborting execution..."
  1210. exit $EXIT_INVALID_OPTION
  1211. fi
  1212. return $TRUE
  1213. fi
  1214. vprint " Get Page Size: Adaptive Enabled"
  1215. vprint " Method: Grep"
  1216. getPageSizeCatGrep
  1217. if pageSizeIsInvalid && [[ $OSNAME = "Darwin" ]]; then
  1218. vprint " Failed"
  1219. vprint " Method: Mac Quartz mdls"
  1220. getPageSizeMdls
  1221. fi
  1222. if pageSizeIsInvalid; then
  1223. vprint " Failed"
  1224. vprint " Method: PDFInfo"
  1225. getPageSizePdfInfo
  1226. fi
  1227. if pageSizeIsInvalid; then
  1228. vprint " Failed"
  1229. vprint " Method: ImageMagick's Identify"
  1230. getPageSizeImagemagick
  1231. fi
  1232. if pageSizeIsInvalid; then
  1233. vprint " Failed"
  1234. printError "Error when detecting PDF paper size!"
  1235. printError "All methods of detection failed"
  1236. printError "You may want to install pdfinfo or imagemagick"
  1237. exit $EXIT_INVALID_PAGE_SIZE_DETECTED
  1238. fi
  1239. return $TRUE
  1240. }
  1241. # Gets page size using imagemagick's identify
  1242. getPageSizeImagemagick() {
  1243. # Sanity and Adaptive together
  1244. if isNotFile "$IDBIN" && isNotAdaptiveMode; then
  1245. notAdaptiveFailed "Make sure you installed ImageMagick and have identify on your \$PATH" "ImageMagick's Identify"
  1246. elif isNotFile "$IDBIN" && isAdaptiveMode; then
  1247. return $FALSE
  1248. fi
  1249. # get data from image magick
  1250. local identify="$("$IDBIN" -format '%[fx:w] %[fx:h]BREAKME' "$INFILEPDF" 2>/dev/null)"
  1251. if isEmpty "$identify" && isNotAdaptiveMode; then
  1252. notAdaptiveFailed "ImageMagicks's Identify returned an empty string!"
  1253. elif isEmpty "$identify" && isAdaptiveMode; then
  1254. return $FALSE
  1255. fi
  1256. identify="${identify%%BREAKME*}" # get page size only for 1st page
  1257. identify=($identify) # make it an array
  1258. PGWIDTH=$(printf '%.0f' "${identify[0]}") # assign
  1259. PGHEIGHT=$(printf '%.0f' "${identify[1]}") # assign
  1260. return $TRUE
  1261. }
  1262. # Gets page size using Mac Quarts mdls
  1263. getPageSizeMdls() {
  1264. # Sanity and Adaptive together
  1265. if isNotFile "$MDLSBIN" && isNotAdaptiveMode; then
  1266. notAdaptiveFailed "Are you even trying this on a Mac?" "Mac Quartz mdls"
  1267. elif isNotFile "$MDLSBIN" && isAdaptiveMode; then
  1268. return $FALSE
  1269. fi
  1270. local identify="$("$MDLSBIN" -mdls -name kMDItemPageHeight -name kMDItemPageWidth "$INFILEPDF" 2>/dev/null)"
  1271. if isEmpty "$identify" && isNotAdaptiveMode; then
  1272. notAdaptiveFailed "Mac Quartz mdls returned an empty string!"
  1273. elif isEmpty "$identify" && isAdaptiveMode; then
  1274. return $FALSE
  1275. fi
  1276. identify=${identify//$'\t'/ } # change tab to space
  1277. identify=($identify) # make it an array
  1278. if [[ "${identify[5]}" = "(null)" || "${identify[2]}" = "(null)" ]] && isNotAdaptiveMode; then
  1279. notAdaptiveFailed "There was no metadata to read from the file! Is Spotlight OFF?"
  1280. elif [[ "${identify[5]}" = "(null)" || "${identify[2]}" = "(null)" ]] && isAdaptiveMode; then
  1281. return $FALSE
  1282. fi
  1283. PGWIDTH=$(printf '%.0f' "${identify[5]}") # assign
  1284. PGHEIGHT=$(printf '%.0f' "${identify[2]}") # assign
  1285. return $TRUE
  1286. }
  1287. # Gets page size using Linux PdfInfo
  1288. getPageSizePdfInfo() {
  1289. # Sanity and Adaptive together
  1290. if isNotFile "$PDFINFOBIN" && isNotAdaptiveMode; then
  1291. notAdaptiveFailed "Do you have pdfinfo installed and available on your \$PATH?" "Linux pdfinfo"
  1292. elif isNotFile "$PDFINFOBIN" && isAdaptiveMode; then
  1293. return $FALSE
  1294. fi
  1295. # get data from image magick
  1296. local identify="$("$PDFINFOBIN" "$INFILEPDF" 2>/dev/null | "$GREPBIN" -i 'Page size:' )"
  1297. if isEmpty "$identify" && isNotAdaptiveMode; then
  1298. notAdaptiveFailed "Linux PdfInfo returned an empty string!"
  1299. elif isEmpty "$identify" && isAdaptiveMode; then
  1300. return $FALSE
  1301. fi
  1302. identify="${identify##*Page size:}" # remove stuff
  1303. identify=($identify) # make it an array
  1304. PGWIDTH=$(printf '%.0f' "${identify[0]}") # assign
  1305. PGHEIGHT=$(printf '%.0f' "${identify[2]}") # assign
  1306. return $TRUE
  1307. }
  1308. # Gets page size using cat and grep
  1309. getPageSizeCatGrep() {
  1310. # get MediaBox info from PDF file using grep, these are all possible
  1311. # /MediaBox [0 0 595 841]
  1312. # /MediaBox [ 0 0 595.28 841.89]
  1313. # /MediaBox[ 0 0 595.28 841.89 ]
  1314. # Get MediaBox data if possible
  1315. local mediaBox="$("$GREPBIN" -a -e '/MediaBox' -m 1 "$INFILEPDF" 2>/dev/null)"
  1316. mediaBox="${mediaBox##*/MediaBox}"
  1317. mediaBox="${mediaBox##*[}"
  1318. mediaBox="${mediaBox%%]*}"
  1319. #echo "mediaBox=$mediaBox"
  1320. # No page size data available
  1321. if isEmpty "$mediaBox" && isNotAdaptiveMode; then
  1322. notAdaptiveFailed "There is no MediaBox in the pdf document!"
  1323. elif isEmpty "$mediaBox" && isAdaptiveMode; then
  1324. return $FALSE
  1325. fi
  1326. mediaBox=($mediaBox) # make it an array
  1327. mbCount=${#mediaBox[@]} # array size
  1328. # sanity
  1329. if [[ $mbCount -lt 4 ]] || ! isFloat "${mediaBox[2]}" || ! isFloat "${mediaBox[3]}" || isZero "${mediaBox[2]}" || isZero "${mediaBox[3]}"; then
  1330. if isNotAdaptiveMode; then
  1331. notAdaptiveFailed $'Error when reading the page size!\nThe page size information is invalid!'
  1332. fi
  1333. return $FALSE
  1334. fi
  1335. # we are done
  1336. PGWIDTH=$(printf '%.0f' "${mediaBox[2]}") # Get Round Width
  1337. PGHEIGHT=$(printf '%.0f' "${mediaBox[3]}") # Get Round Height
  1338. #echo "PGWIDTH=$PGWIDTH // PGHEIGHT=$PGHEIGHT"
  1339. return $TRUE
  1340. }
  1341. isZero() {
  1342. [[ "$1" == "0" ]] && return $TRUE
  1343. [[ "$1" == "0.0" ]] && return $TRUE
  1344. [[ "$1" == "0.00" ]] && return $TRUE
  1345. [[ "$1" == "0.000" ]] && return $TRUE
  1346. return $FALSE
  1347. }
  1348. # Prints error message and exits execution
  1349. notAdaptiveFailed() {
  1350. local errProgram="$2"
  1351. local errStr="$1"
  1352. if isEmpty "$2"; then
  1353. printError "Error when reading input file!"
  1354. printError "Could not determine the page size!"
  1355. else
  1356. printError "Error! $2 was not found!"
  1357. fi
  1358. isNotEmpty "$errStr" && printError "$errStr"
  1359. printError "Aborting! You may want to try the adaptive mode."
  1360. exit $EXIT_INVALID_PAGE_SIZE_DETECTED
  1361. }
  1362. # Verbose print of the Width and Height (Source or New) to screen
  1363. vPrintPageSizes() {
  1364. vprint " $1 Width: $PGWIDTH postscript-points"
  1365. vprint "$1 Height: $PGHEIGHT postscript-points"
  1366. }
  1367. #################### GHOSTSCRIPT PAPER INFO ####################
  1368. # Loads valid paper info to memory
  1369. getPaperInfo() {
  1370. # name inchesW inchesH mmW mmH pointsW pointsH
  1371. sizesUS="\
  1372. 11x17 11.0 17.0 279 432 792 1224
  1373. ledger 17.0 11.0 432 279 1224 792
  1374. legal 8.5 14.0 216 356 612 1008
  1375. letter 8.5 11.0 216 279 612 792
  1376. lettersmall 8.5 11.0 216 279 612 792
  1377. archE 36.0 48.0 914 1219 2592 3456
  1378. archD 24.0 36.0 610 914 1728 2592
  1379. archC 18.0 24.0 457 610 1296 1728
  1380. archB 12.0 18.0 305 457 864 1296
  1381. archA 9.0 12.0 229 305 648 864"
  1382. sizesISO="\
  1383. a0 33.1 46.8 841 1189 2384 3370
  1384. a1 23.4 33.1 594 841 1684 2384
  1385. a2 16.5 23.4 420 594 1191 1684
  1386. a3 11.7 16.5 297 420 842 1191
  1387. a4 8.3 11.7 210 297 595 842
  1388. a4small 8.3 11.7 210 297 595 842
  1389. a5 5.8 8.3 148 210 420 595
  1390. a6 4.1 5.8 105 148 297 420
  1391. a7 2.9 4.1 74 105 210 297
  1392. a8 2.1 2.9 52 74 148 210
  1393. a9 1.5 2.1 37 52 105 148
  1394. a10 1.0 1.5 26 37 73 105
  1395. isob0 39.4 55.7 1000 1414 2835 4008
  1396. isob1 27.8 39.4 707 1000 2004 2835
  1397. isob2 19.7 27.8 500 707 1417 2004
  1398. isob3 13.9 19.7 353 500 1001 1417
  1399. isob4 9.8 13.9 250 353 709 1001
  1400. isob5 6.9 9.8 176 250 499 709
  1401. isob6 4.9 6.9 125 176 354 499
  1402. c0 36.1 51.1 917 1297 2599 3677
  1403. c1 25.5 36.1 648 917 1837 2599
  1404. c2 18.0 25.5 458 648 1298 1837
  1405. c3 12.8 18.0 324 458 918 1298
  1406. c4 9.0 12.8 229 324 649 918
  1407. c5 6.4 9.0 162 229 459 649
  1408. c6 4.5 6.4 114 162 323 459"
  1409. sizesJIS="\
  1410. jisb0 NA NA 1030 1456 2920 4127
  1411. jisb1 NA NA 728 1030 2064 2920
  1412. jisb2 NA NA 515 728 1460 2064
  1413. jisb3 NA NA 364 515 1032 1460
  1414. jisb4 NA NA 257 364 729 1032
  1415. jisb5 NA NA 182 257 516 729
  1416. jisb6 NA NA 128 182 363 516"
  1417. sizesOther="\
  1418. flsa 8.5 13.0 216 330 612 936
  1419. flse 8.5 13.0 216 330 612 936
  1420. halfletter 5.5 8.5 140 216 396 612
  1421. hagaki 3.9 5.8 100 148 283 420"
  1422. sizesAll="\
  1423. $sizesUS
  1424. $sizesISO
  1425. $sizesJIS
  1426. $sizesOther"
  1427. }
  1428. # Gets a paper size in points and sets it to RESIZE_WIDTH and RESIZE_HEIGHT
  1429. getGSPaperSize() {
  1430. isEmpty "$sizesall" && getPaperInfo
  1431. while read l; do
  1432. local cols=($l)
  1433. if [[ "$1" == ${cols[0]} ]]; then
  1434. RESIZE_WIDTH=${cols[5]}
  1435. RESIZE_HEIGHT=${cols[6]}
  1436. return $TRUE
  1437. fi
  1438. done <<< "$sizesAll"
  1439. }
  1440. # Gets a paper size in points and sets it to RESIZE_WIDTH and RESIZE_HEIGHT
  1441. getGSPaperName() {
  1442. local w="$(printf "%.0f" $1)"
  1443. local h="$(printf "%.0f" $2)"
  1444. isEmpty "$sizesall" && getPaperInfo
  1445. # Because US Standard has inverted sizes, I need to scan 2 times
  1446. # instead of just testing if width is bigger than height
  1447. while read l; do
  1448. local cols=($l)
  1449. if [[ "$w" == ${cols[5]} && "$h" == ${cols[6]} ]]; then
  1450. printf "%s Portrait" $(uppercase ${cols[0]})
  1451. return $TRUE
  1452. fi
  1453. done <<< "$sizesAll"
  1454. while read l; do
  1455. local cols=($l)
  1456. if [[ "$w" == ${cols[6]} && "$h" == ${cols[5]} ]]; then
  1457. printf "%s Landscape" $(uppercase ${cols[0]})
  1458. return $TRUE
  1459. fi
  1460. done <<< "$sizesAll"
  1461. return $FALSE
  1462. }
  1463. # Loads an array with paper names to memory
  1464. getPaperNames() {
  1465. paperNames=(a0 a1 a2 a3 a4 a4small a5 a6 a7 a8 a9 a10 isob0 isob1 isob2 isob3 isob4 isob5 isob6 c0 c1 c2 c3 c4 c5 c6 \
  1466. 11x17 ledger legal letter lettersmall archE archD archC archB archA \
  1467. jisb0 jisb1 jisb2 jisb3 jisb4 jisb5 jisb6 \
  1468. flsa flse halfletter hagaki)
  1469. }
  1470. # Prints uppercase paper names to screen (used in help)
  1471. printPaperNames() {
  1472. isEmpty "$paperNames" && getPaperNames
  1473. for i in "${!paperNames[@]}"; do
  1474. [[ $i -eq 0 ]] && echo -n -e ' '
  1475. [[ $i -ne 0 && $((i % 5)) -eq 0 ]] && echo -n -e $'\n '
  1476. ppN="$(uppercase ${paperNames[i]})"
  1477. printf "%-14s" "$ppN"
  1478. done
  1479. echo ""
  1480. }
  1481. # Returns $TRUE if $! is a valid paper name, $FALSE otherwise
  1482. isPaperName() {
  1483. isEmpty "$1" && return $FALSE
  1484. isEmpty "$paperNames" && getPaperNames
  1485. for i in "${paperNames[@]}"; do
  1486. [[ "$i" = "$1" ]] && return $TRUE
  1487. done
  1488. return $FALSE
  1489. }
  1490. # Prints all tables with ghostscript paper information
  1491. printPaperInfo() {
  1492. printVersion 3
  1493. echo $'\n'"Paper Sizes Information"$'\n'
  1494. getPaperInfo
  1495. printPaperTable "ISO STANDARD" "$sizesISO"; echo
  1496. printPaperTable "US STANDARD" "$sizesUS"; echo
  1497. printPaperTable "JIS STANDARD *Aproximated Points" "$sizesJIS"; echo
  1498. printPaperTable "OTHERS" "$sizesOther"; echo
  1499. }
  1500. # GS paper table helper, prints a full line
  1501. printTableLine() {
  1502. echo '+-----------------------------------------------------------------+'
  1503. }
  1504. # GS paper table helper, prints a line with dividers
  1505. printTableDivider() {
  1506. echo '+-----------------+-------+-------+-------+-------+-------+-------+'
  1507. }
  1508. # GS paper table helper, prints a table header
  1509. printTableHeader() {
  1510. echo '| Name | inchW | inchH | mm W | mm H | pts W | pts H |'
  1511. }
  1512. # GS paper table helper, prints a table title
  1513. printTableTitle() {
  1514. printf "| %-64s%s\n" "$1" '|'
  1515. }
  1516. # GS paper table printer, prints a table for a paper variable
  1517. printPaperTable() {
  1518. printTableLine
  1519. printTableTitle "$1"
  1520. printTableLine
  1521. printTableHeader
  1522. printTableDivider
  1523. while read l; do
  1524. local cols=($l)
  1525. printf "| %-15s | %+5s | %+5s | %+5s | %+5s | %+5s | %+5s |\n" ${cols[*]};
  1526. done <<< "$2"
  1527. printTableDivider
  1528. }
  1529. # Returns $TRUE if $1 is a valid measurement for a custom paper, $FALSE otherwise
  1530. isNotValidMeasure() {
  1531. isMilimeter "$1" || isInch "$1" || isPoint "$1" && return $FALSE
  1532. return $TRUE
  1533. }
  1534. # Returns $TRUE if $1 is a valid milimeter string, $FALSE otherwise
  1535. isMilimeter() {
  1536. [[ "$1" = 'mm' || "$1" = 'milimeters' || "$1" = 'milimeter' ]] && return $TRUE
  1537. return $FALSE
  1538. }
  1539. # Returns $TRUE if $1 is a valid inch string, $FALSE otherwise
  1540. isInch() {
  1541. [[ "$1" = 'in' || "$1" = 'inch' || "$1" = 'inches' ]] && return $TRUE
  1542. return $FALSE
  1543. }
  1544. # Returns $TRUE if $1 is a valid point string, $FALSE otherwise
  1545. isPoint() {
  1546. [[ "$1" = 'pt' || "$1" = 'pts' || "$1" = 'point' || "$1" = 'points' ]] && return $TRUE
  1547. return $FALSE
  1548. }
  1549. # Returns $TRUE if a custom paper is being used, $FALSE otherwise
  1550. isCustomPaper() {
  1551. return $CUSTOM_RESIZE_PAPER
  1552. }
  1553. # Returns $FALSE if a custom paper is being used, $TRUE otherwise
  1554. isNotCustomPaper() {
  1555. isCustomPaper && return $FALSE
  1556. return $TRUE
  1557. }
  1558. ######################### CONVERSIONS ##########################
  1559. # Prints the lowercase char value for $1
  1560. lowercaseChar() {
  1561. case "$1" in
  1562. [A-Z])
  1563. n=$(printf "%d" "'$1")
  1564. n=$((n+32))
  1565. printf \\$(printf "%o" "$n")
  1566. ;;
  1567. *)
  1568. printf "%s" "$1"
  1569. ;;
  1570. esac
  1571. }
  1572. # Prints the lowercase version of a string
  1573. lowercase() {
  1574. word="$@"
  1575. for((i=0;i<${#word};i++))
  1576. do
  1577. ch="${word:$i:1}"
  1578. lowercaseChar "$ch"
  1579. done
  1580. }
  1581. # Prints the uppercase char value for $1
  1582. uppercaseChar(){
  1583. case "$1" in
  1584. [a-z])
  1585. n=$(printf "%d" "'$1")
  1586. n=$((n-32))
  1587. printf \\$(printf "%o" "$n")
  1588. ;;
  1589. *)
  1590. printf "%s" "$1"
  1591. ;;
  1592. esac
  1593. }
  1594. # Prints the uppercase version of a string
  1595. uppercase() {
  1596. word="$@"
  1597. for((i=0;i<${#word};i++))
  1598. do
  1599. ch="${word:$i:1}"
  1600. uppercaseChar "$ch"
  1601. done
  1602. }
  1603. # Prints the postscript points rounded equivalent from $1 mm
  1604. milimetersToPoints() {
  1605. local pts=$(echo "scale=8; $1 * 72 / 25.4" | "$BCBIN")
  1606. printf '%.0f' "$pts" # Print rounded conversion
  1607. }
  1608. # Prints the postscript points rounded equivalent from $1 inches
  1609. inchesToPoints() {
  1610. local pts=$(echo "scale=8; $1 * 72" | "$BCBIN")
  1611. printf '%.0f' "$pts" # Print rounded conversion
  1612. }
  1613. # Prints the mm equivalent from $1 postscript points
  1614. pointsToMilimeters() {
  1615. local pts=$(echo "scale=8; $1 / 72 * 25.4" | "$BCBIN")
  1616. printf '%.0f' "$pts" # Print rounded conversion
  1617. }
  1618. # Prints the inches equivalent from $1 postscript points
  1619. pointsToInches() {
  1620. local pts=$(echo "scale=8; $1 / 72" | "$BCBIN")
  1621. printf '%.1f' "$pts" # Print rounded conversion
  1622. }
  1623. ######################## MODE-DETECTION ########################
  1624. # Returns $TRUE if the scale was set manually, $FALSE if we are using automatic scaling
  1625. isManualScaledMode() {
  1626. [[ $AUTOMATIC_SCALING -eq $TRUE ]] && return $FALSE
  1627. return $TRUE
  1628. }
  1629. # Returns true if we are resizing a paper (ignores scaling), false otherwise
  1630. isResizeMode() {
  1631. isEmpty $RESIZE_PAPER_TYPE && return $FALSE
  1632. return $TRUE
  1633. }
  1634. # Returns true if we are resizing a paper and the scale was manually set
  1635. isMixedMode() {
  1636. isResizeMode && isManualScaledMode && return $TRUE
  1637. return $FALSE
  1638. }
  1639. # Return $TRUE if adaptive mode is enabled, $FALSE otherwise
  1640. isAdaptiveMode() {
  1641. return $ADAPTIVEMODE
  1642. }
  1643. # Return $TRUE if adaptive mode is disabled, $FALSE otherwise
  1644. isNotAdaptiveMode() {
  1645. isAdaptiveMode && return $FALSE
  1646. return $TRUE
  1647. }
  1648. ########################## VALIDATORS ##########################
  1649. # Returns $TRUE if we don't need to create a background
  1650. noBackground() {
  1651. [[ "$BACKGROUNDTYPE" == "CMYK" ]] && return $FALSE
  1652. [[ "$BACKGROUNDTYPE" == "RGB" ]] && return $FALSE
  1653. return $TRUE
  1654. }
  1655. # Returns $TRUE if we need to create a background
  1656. hasBackground() {
  1657. [[ "$BACKGROUNDTYPE" == "CMYK" ]] && return $TRUE
  1658. [[ "$BACKGROUNDTYPE" == "RGB" ]] && return $TRUE
  1659. return $FALSE
  1660. }
  1661. # Returns $TRUE if $PGWIDTH OR $PGWIDTH are empty or NOT an Integer, $FALSE otherwise
  1662. pageSizeIsInvalid() {
  1663. if isNotAnInteger "$PGWIDTH" || isNotAnInteger "$PGHEIGHT"; then
  1664. return $TRUE
  1665. fi
  1666. return $FALSE
  1667. }
  1668. # Return $TRUE if $1 is empty, $FALSE otherwise
  1669. isEmpty() {
  1670. [[ -z "$1" ]] && return $TRUE
  1671. return $FALSE
  1672. }
  1673. # Return $TRUE if $1 is NOT empty, $FALSE otherwise
  1674. isNotEmpty() {
  1675. [[ -z "$1" ]] && return $FALSE
  1676. return $TRUE
  1677. }
  1678. # Returns $TRUE if $1 is an integer, $FALSE otherwise
  1679. isAnInteger() {
  1680. case $1 in
  1681. ''|*[!0-9]*) return $FALSE ;;
  1682. *) return $TRUE ;;
  1683. esac
  1684. }
  1685. # Returns $TRUE if $1 is NOT an integer, $FALSE otherwise
  1686. isNotAnInteger() {
  1687. case $1 in
  1688. ''|*[!0-9]*) return $TRUE ;;
  1689. *) return $FALSE ;;
  1690. esac
  1691. }
  1692. # Returns $TRUE if $1 is an integer, $FALSE otherwise
  1693. isRGBInteger() {
  1694. isAnInteger "$1" && [[ $1 -ge 0 ]] && [[ $1 -le 255 ]] && return $TRUE
  1695. return $FALSE
  1696. }
  1697. # Returns $TRUE if $1 is a floating point number (or an integer), $FALSE otherwise
  1698. isFloat() {
  1699. [[ -n "$1" && "$1" =~ ^-?[0-9]*([.][0-9]+)?$ ]] && return $TRUE
  1700. return $FALSE
  1701. }
  1702. # Returns $TRUE if $1 is a floating point number bigger than zero, $FALSE otherwise
  1703. isFloatBiggerThanZero() {
  1704. isFloat "$1" && [[ (( $1 > 0 )) ]] && return $TRUE
  1705. return $FALSE
  1706. }
  1707. # Returns $TRUE if $1 is a floating point number between 0 and 1, $FALSE otherwise
  1708. isFloatPercentage() {
  1709. [[ -n "$1" && "$1" =~ ^-?[0]*([.][0-9]+)?$ ]] && return $TRUE
  1710. [[ "$1" == "1" ]] && return $TRUE
  1711. return $FALSE
  1712. }
  1713. # Returns $TRUE if $1 is readable, $FALSE otherwise
  1714. isReadable() {
  1715. [[ -r "$1" ]] && return $TRUE
  1716. return $FALSE;
  1717. }
  1718. # Returns $TRUE if $1 is a directory, $FALSE otherwise
  1719. isDir() {
  1720. [[ -d "$1" ]] && return $TRUE
  1721. return $FALSE;
  1722. }
  1723. # Returns $FALSE if $1 is a directory, $TRUE otherwise
  1724. isNotDir() {
  1725. isDir "$1" && return $FALSE
  1726. return $TRUE;
  1727. }
  1728. # Returns 0 if succeded, other integer otherwise
  1729. isTouchable() {
  1730. touch "$1" 2>/dev/null
  1731. }
  1732. # Returns $TRUE if $1 has a .pdf extension, false otherwsie
  1733. isPDF() {
  1734. [[ "$(lowercase $1)" =~ ^..*\.pdf$ ]] && return $TRUE
  1735. return $FALSE
  1736. }
  1737. # Returns $TRUE if $1 is a file, false otherwsie
  1738. isFile() {
  1739. [[ -f "$1" ]] && return $TRUE
  1740. return $FALSE
  1741. }
  1742. # Returns $TRUE if $1 is NOT a file, false otherwsie
  1743. isNotFile() {
  1744. [[ -f "$1" ]] && return $FALSE
  1745. return $TRUE
  1746. }
  1747. # Returns $TRUE if $1 is executable, false otherwsie
  1748. isExecutable() {
  1749. [[ -x "$1" ]] && return $TRUE
  1750. return $FALSE
  1751. }
  1752. # Returns $TRUE if $1 is NOT executable, false otherwsie
  1753. isNotExecutable() {
  1754. [[ -x "$1" ]] && return $FALSE
  1755. return $TRUE
  1756. }
  1757. # Returns $TRUE if $1 is a file and executable, false otherwsie
  1758. isAvailable() {
  1759. if isFile "$1" && isExecutable "$1"; then
  1760. return $TRUE
  1761. fi
  1762. return $FALSE
  1763. }
  1764. # Returns $TRUE if $1 is NOT a file or NOT executable, false otherwsie
  1765. isNotAvailable() {
  1766. if isNotFile "$1" || isNotExecutable "$1"; then
  1767. return $TRUE
  1768. fi
  1769. return $FALSE
  1770. }
  1771. # Returns $TRUE if we should avoid https certificate (on upgrade)
  1772. useInsecure() {
  1773. return $HTTPS_INSECURE
  1774. }
  1775. # Returns $TRUE if we should not ask anything and assume yes as answer
  1776. assumeYes() {
  1777. return $ASSUME_YES
  1778. }
  1779. # Returns $TRUE if we should ask the user for input
  1780. shouldAskUser() {
  1781. assumeYes && return $FALSE
  1782. return $TRUE
  1783. }
  1784. ###################### PRINTING TO SCREEN ######################
  1785. # Prints version
  1786. printVersion() {
  1787. local vStr=""
  1788. [[ "$2" = 'verbose' ]] && vStr=" - Verbose Execution"
  1789. local strBanner="$PDFSCALE_NAME v$VERSION$vStr"
  1790. if [[ $1 -eq 2 ]]; then
  1791. printError "$strBanner"
  1792. elif [[ $1 -eq 3 ]]; then
  1793. local extra="$(isNotEmpty "$2" && echo "$2")"
  1794. echo "$strBanner$extra"
  1795. else
  1796. vprint "$strBanner"
  1797. fi
  1798. }
  1799. # Prints input, output file info, if verbosing
  1800. vPrintFileInfo() {
  1801. vprint " Input File: $INFILEPDF"
  1802. vprint " Output File: $OUTFILEPDF"
  1803. }
  1804. # Prints the scale factor to screen, or custom message
  1805. vPrintScaleFactor() {
  1806. local scaleMsg="$SCALE"
  1807. isNotEmpty "$1" && scaleMsg="$1"
  1808. vprint " Scale Factor: $scaleMsg"
  1809. }
  1810. # Prints help info
  1811. printHelp() {
  1812. printVersion 3
  1813. local paperList="$(printPaperNames)"
  1814. echo "
  1815. Usage: $PDFSCALE_NAME <inFile.pdf>
  1816. $PDFSCALE_NAME -i <inFile.pdf>
  1817. $PDFSCALE_NAME [-v] [-s <factor>] [-m <page-detection>] <inFile.pdf> [outfile.pdf]
  1818. $PDFSCALE_NAME [-v] [-r <paper>] [-f <flip-detection>] [-a <auto-rotation>] <inFile.pdf> [outfile.pdf]
  1819. $PDFSCALE_NAME -p
  1820. $PDFSCALE_NAME -h
  1821. $PDFSCALE_NAME -V
  1822. Parameters:
  1823. -v, --verbose
  1824. Verbose mode, prints extra information
  1825. Use twice for timestamp
  1826. -h, --help
  1827. Print this help to screen and exits
  1828. -V, --version
  1829. Prints version to screen and exits
  1830. --install, --self-install [target-path]
  1831. Install itself to [target-path] or /usr/local/bin/pdfscale if not specified
  1832. Should contain the full path with the desired executable name
  1833. --upgrade, --self-upgrade
  1834. Upgrades itself in-place (same path/name of the pdfScale.sh caller)
  1835. Downloads the master branch tarball and tries to self-upgrade
  1836. --insecure, --no-check-certificate
  1837. Use curl/wget without SSL library support
  1838. --yes, --assume-yes
  1839. Will answer yes to any prompt on install or upgrade, use with care
  1840. -n, --no-overwrite
  1841. Aborts execution if the output PDF file already exists
  1842. By default, the output file will be overwritten
  1843. -m, --mode <mode>
  1844. Paper size detection mode
  1845. Modes: a, adaptive Default mode, tries all the methods below
  1846. g, grep Forces the use of Grep method
  1847. m, mdls Forces the use of MacOS Quartz mdls
  1848. p, pdfinfo Forces the use of PDFInfo
  1849. i, identify Forces the use of ImageMagick's Identify
  1850. -i, --info <file>
  1851. Prints <file> Paper Size information to screen and exits
  1852. -s, --scale <factor>
  1853. Changes the scaling factor or forces mixed mode
  1854. Defaults: $SCALE (scale mode) / Disabled (resize mode)
  1855. MUST be a number bigger than zero
  1856. Eg. -s 0.8 for 80% of the original size
  1857. -r, --resize <paper>
  1858. Triggers the Resize Paper Mode, disables auto-scaling of $SCALE
  1859. Resize PDF and fit-to-page
  1860. <paper> can be: source, custom or a valid std paper name, read below
  1861. -f, --flip-detect <mode>
  1862. Flip Detection Mode, defaults to 'auto'
  1863. Inverts Width <-> Height of a Resized PDF
  1864. Modes: a, auto Keeps source orientation, default
  1865. f, force Forces flip W <-> H
  1866. d, disable Disables flipping
  1867. -a, --auto-rotate <mode>
  1868. Setting for GS -dAutoRotatePages, defaults to 'PageByPage'
  1869. Uses text-orientation detection to set Portrait/Landscape
  1870. Modes: p, pagebypage Auto-rotates pages individually
  1871. n, none Retains orientation of each page
  1872. a, all Rotates all pages (or none) depending
  1873. on a kind of \"majority decision\"
  1874. --hor-align, --horizontal-alignment <left|center|right>
  1875. Where to translate the scaled page
  1876. Default: center
  1877. Options: left, right, center
  1878. --vert-align, --vertical-alignment <top|center|bottom>
  1879. Where to translate the scaled page
  1880. Default: center
  1881. Options: top, bottom, center
  1882. --xoffset, --xtrans-offset <FloatNumber>
  1883. Add/Subtract from the X translation (move left-right)
  1884. Default: 0.0 (zero)
  1885. Options: Positive or negative floating point number
  1886. --yoffset, --ytrans-offset <FloatNumber>
  1887. Add/Subtract from the Y translation (move top-bottom)
  1888. Default: 0.0 (zero)
  1889. Options: Positive or negative floating point number
  1890. --pdf-settings <gs-pdf-profile>
  1891. Ghostscript PDF Profile to use in -dPDFSETTINGS
  1892. Default: printer
  1893. Options: screen, ebook, printer, prepress, default
  1894. --image-downsample <gs-downsample-method>
  1895. Ghostscript Image Downsample Method
  1896. Default: bicubic
  1897. Options: subsample, average, bicubic
  1898. --image-resolution <dpi>
  1899. Resolution in DPI of color and grayscale images in output
  1900. Default: 300
  1901. --background-gray <percentage>
  1902. Creates a background with a gray color setting
  1903. Percentage is a floating point percentage number between 0(white) and 1(black)
  1904. --background-cmyk <\"C M Y K\">
  1905. Creates a background with a CMYK color setting
  1906. Must be quoted into a single parameter as in \"0.2 0.2 0.2 0.2\"
  1907. Each color parameter is a floating point percentage number (between 0 and 1)
  1908. --background-rgb <\"R G B\">
  1909. Creates a background with a RGB color setting
  1910. Must be quoted into a single parameter as in \"100 100 200\"
  1911. Postscript accepts both percentages or RGB numbers, but not mixed
  1912. Percentages are floating point numbers between 0 and 1 (1 0.5 0.2)
  1913. RGB numbers are integers between 0 and 255 (255 122 50)
  1914. --dry-run, --simulate
  1915. Just simulate execution. Will not run ghostscript
  1916. --print-gs-call, --gs-call
  1917. Print GS call to stdout. Will print at the very end between markers
  1918. -p, --print-papers
  1919. Prints Standard Paper info tables to screen and exits
  1920. Scaling Mode:
  1921. - The default mode of operation is scaling mode with fixed paper
  1922. size and scaling pre-set to $SCALE
  1923. - By not using the resize mode you are using scaling mode
  1924. - Flip-Detection and Auto-Rotation are disabled in Scaling mode,
  1925. you can use '-r source -s <scale>' to override.
  1926. - Ghostscript placement is from bottom-left position. This means that
  1927. a bottom-left placement has ZERO for both X and Y translations.
  1928. Resize Paper Mode:
  1929. - Disables the default scaling factor! ($SCALE)
  1930. - Changes the PDF Paper Size in points. Will fit-to-page
  1931. Mixed Mode:
  1932. - In mixed mode both the -s option and -r option must be specified
  1933. - The PDF will be first resized then scaled
  1934. Output filename:
  1935. - Having the extension .pdf on the output file name is optional,
  1936. it will be added if not present.
  1937. - The output filename is optional. If no file name is passed
  1938. the output file will have the same name/destination of the
  1939. input file with added suffixes:
  1940. .SCALED.pdf is added to scaled files
  1941. .<PAPERSIZE>.pdf is added to resized files
  1942. .<PAPERSIZE>.SCALED.pdf is added in mixed mode
  1943. Standard Paper Names: (case-insensitive)
  1944. $paperList
  1945. Custom Paper Size:
  1946. - Paper size can be set manually in Milimeters, Inches or Points
  1947. - Custom paper definition MUST be quoted into a single parameter
  1948. - Actual size is applied in points (mms and inches are transformed)
  1949. - Measurements: mm, mms, milimeters
  1950. pt, pts, points
  1951. in, inch, inches
  1952. Use: $PDFSCALE_NAME -r 'custom <measurement> <width> <height>'
  1953. Ex: $PDFSCALE_NAME -r 'custom mm 300 300'
  1954. Using Source Paper Size: (no-resizing)
  1955. - Wildcard 'source' is used used to keep paper size the same as the input
  1956. - Usefull to run Auto-Rotation without resizing
  1957. - Eg. $PDFSCALE_NAME -r source ./input.pdf
  1958. Options and Parameters Parsing:
  1959. - From v2.1.0 (long-opts) there is no need to pass file names at the end
  1960. - Anything that is not a short-option is case-insensitive
  1961. - Short-options: case-sensitive Eg. -v for Verbose, -V for Version
  1962. - Long-options: case-insensitive Eg. --SCALE and --scale are the same
  1963. - Subparameters: case-insensitive Eg. -m PdFinFo is valid
  1964. - Grouping short-options is not supported Eg. -vv, or -vs 0.9
  1965. Additional Notes:
  1966. - File and folder names with spaces should be quoted or escaped
  1967. - Using a scale bigger than 1.0 may result on cropping parts of the PDF
  1968. - For detailed paper types information, use: $PDFSCALE_NAME -p
  1969. Examples:
  1970. $PDFSCALE_NAME myPdfFile.pdf
  1971. $PDFSCALE_NAME -i '/home/My Folder/My PDF File.pdf'
  1972. $PDFSCALE_NAME myPdfFile.pdf \"My Scaled Pdf\"
  1973. $PDFSCALE_NAME -v -v myPdfFile.pdf
  1974. $PDFSCALE_NAME -s 0.85 myPdfFile.pdf My\\ Scaled\\ Pdf.pdf
  1975. $PDFSCALE_NAME -m pdfinfo -s 0.80 -v myPdfFile.pdf
  1976. $PDFSCALE_NAME -v -v -m i -s 0.7 myPdfFile.pdf
  1977. $PDFSCALE_NAME -r A4 myPdfFile.pdf
  1978. $PDFSCALE_NAME -v -v -r \"custom mm 252 356\" -s 0.9 -f \"../input file.pdf\" \"../my new pdf\"
  1979. "
  1980. }
  1981. # Prints usage info
  1982. usage() {
  1983. [[ "$2" != 'nobanner' ]] && printVersion 2
  1984. isNotEmpty "$1" && printError $'\n'"$1"
  1985. printError $'\n'"Usage: $PDFSCALE_NAME [-v] [-s <factor>] [-m <mode>] [-r <paper> [-f <mode>] [-a <mode>]] <inFile.pdf> [outfile.pdf]"
  1986. printError "Help : $PDFSCALE_NAME -h"
  1987. }
  1988. # Prints Verbose information
  1989. vprint() {
  1990. [[ $VERBOSE -eq 0 ]] && return $TRUE
  1991. timestamp=""
  1992. [[ $VERBOSE -gt 1 ]] && timestamp="$(date +%Y-%m-%d:%H:%M:%S) | "
  1993. echo "$timestamp$1"
  1994. }
  1995. # Prints dependency information and aborts execution
  1996. printDependency() {
  1997. printVersion 2
  1998. local brewName="$1"
  1999. [[ "$1" = 'pdfinfo' && "$OSNAME" = "Darwin" ]] && brewName="xpdf"
  2000. printError $'\n'"ERROR! You need to install the package '$1'"$'\n'
  2001. printError "Linux apt-get.: sudo apt-get install $1"
  2002. printError "Linux yum.....: sudo yum install $1"
  2003. printError "MacOS homebrew: brew install $brewName"
  2004. printError $'\n'"Aborting..."
  2005. exit $EXIT_MISSING_DEPENDENCY
  2006. }
  2007. # Prints initialization errors and aborts execution
  2008. initError() {
  2009. local errStr="$1"
  2010. local exitStat=$2
  2011. isEmpty "$exitStat" && exitStat=$EXIT_ERROR
  2012. usage "ERROR! $errStr" "$3"
  2013. exit $exitStat
  2014. }
  2015. # Prints to stderr
  2016. printError() {
  2017. echo >&2 "$@"
  2018. }
  2019. ########################## EXECUTION ###########################
  2020. initDeps
  2021. getOptions "${@}"
  2022. main
  2023. exit $?