Bash Script to scale and/or resize PDFs from the command line.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

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