Bash Script to scale and/or resize PDFs from the command line.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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