Bash Script to scale and/or resize PDFs from the command line.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

2054 lignes
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 / 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.2"
  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. # Tries to download with curl or wget
  630. getUrl() {
  631. local url="$1"
  632. local target="$2"
  633. local _stat=""
  634. if isEmpty "$url" || isEmpty "$target"; then
  635. echo "Error! Invalid parameters for download."
  636. echo "URL > $url"
  637. echo "TARGET > $target"
  638. exit $EXIT_INVALID_OPTION
  639. fi
  640. WGET_BIN="$(which wget 2>/dev/null)"
  641. CURL_BIN="$(which curl 2>/dev/null)"
  642. if isExecutable "$WGET_BIN"; then
  643. useInsecure && WGET_BIN="$WGET_BIN --no-check-certificate"
  644. echo "Downloading file with wget"
  645. _stat="$("$WGET_BIN" -O "$target" "$url" 2>&1)"
  646. if [[ $? -eq 0 ]]; then
  647. return $TRUE
  648. else
  649. echo "Error when downloading file!"
  650. echo " > $url"
  651. echo "Status:"
  652. echo "$_stat"
  653. exit $EXIT_ERROR
  654. fi
  655. elif isExecutable "$CURL_BIN"; then
  656. useInsecure && CURL_BIN="$CURL_BIN --insecure"
  657. echo "Downloading file with curl"
  658. _stat="$("$CURL_BIN" -o "$target" "$url" 2>&1)"
  659. if [[ $? -eq 0 ]]; then
  660. return $TRUE
  661. else
  662. echo "Error when downloading file!"
  663. echo " > $url"
  664. echo "Status:"
  665. echo "$_stat"
  666. exit $EXIT_ERROR
  667. fi
  668. else
  669. echo "Error! Could not find Wget or Curl to perform download."
  670. echo "Please install either curl or wget and try again."
  671. exit $EXIT_FILE_NOT_FOUND
  672. fi
  673. }
  674. # Tries to remove temporary files from upgrade
  675. clearUpgrade() {
  676. echo $'\nCleaning up downloaded files from /tmp'
  677. if isFile "$TMP_TARGET"; then
  678. echo -n " Remove $TMP_TARGET > "
  679. rm "$TMP_TARGET" 2>/dev/null && echo "Ok" || echo "Fail"
  680. else
  681. echo " No temporary tarball was found to remove."
  682. fi
  683. if isDir "$TMP_EXTRACTED"; then
  684. echo -n " Remove $TMP_EXTRACTED > "
  685. rm -rf "$TMP_EXTRACTED" 2>/dev/null && echo "Ok" || echo "Fail"
  686. else
  687. echo " No temporary master folder was found to remove."
  688. fi
  689. }
  690. # Exit upgrade with message and status code
  691. # $1 Mensagem (printed if not empty)
  692. # $2 Status (defaults to $EXIT_ERROR)
  693. exitUpgrade() {
  694. isDir "$_cwd" && cd "$_cwd"
  695. isNotEmpty "$1" && echo "$1"
  696. clearUpgrade
  697. isNotEmpty "$2" && exit $2
  698. exit $EXIT_ERROR
  699. }
  700. # Downloads current version from github's MASTER branch
  701. selfUpgrade() {
  702. CURRENT_LOC="$(readlink -f $0)"
  703. _cwd="$(pwd)"
  704. local _cur_tstamp="$(date '+%Y%m%d-%H%M%S')"
  705. TMP_DIR='/tmp'
  706. TMP_TARGET="$TMP_DIR/pdfScale_$_cur_tstamp.tar.gz"
  707. TMP_EXTRACTED="$TMP_DIR/$PROJECT_NAME-$PROJECT_BRANCH"
  708. local _answer="no"
  709. printVersion 3 " - Self Upgrade"
  710. echo $'\n'"Preparing download to temp folder"
  711. echo " > $TMP_TARGET"
  712. getUrl "$PROJECT_URL/archive/$PROJECT_BRANCH.tar.gz" "$TMP_TARGET"
  713. if isNotFile "$TMP_TARGET"; then
  714. echo "Error! Could not find downloaded file!"
  715. exit $EXIT_FILE_NOT_FOUND
  716. fi
  717. echo $'\n'"Extracting compressed file"
  718. cd "$TMP_DIR"
  719. if ! (tar xzf "$TMP_TARGET" 2>/dev/null || gtar xzf "$TMP_TARGET" 2>/dev/null); then
  720. exitUpgrade "Extraction error."
  721. fi
  722. if ! cd "$TMP_EXTRACTED" 2>/dev/null; then
  723. exitUpgrade $'Error when accessing temporary folder\n > '"$TMP_EXTRACTED"
  724. fi
  725. if ! chmod +x pdfScale.sh; then
  726. exitUpgrade $'Error when setting new pdfScale to executable\n > '"$TMP_EXTRACTED/pdfScale.sh"
  727. fi
  728. local newver="$(./pdfScale.sh --version 2>/dev/null)"
  729. local curver="$(printVersion 3 2>/dev/null)"
  730. newver=($newver)
  731. curver=($curver)
  732. newver=${newver[1]#v}
  733. curver=${curver[1]#v}
  734. echo $'\n'" Current Version is: $curver"
  735. echo "Downloaded Version is: $newver"$'\n'
  736. if [[ "$newver" = "$curver" ]]; then
  737. echo "Seems like we have downloaded the same version that is installed."
  738. elif isBiggerVersion "$newver" "$curver"; then
  739. echo "Seems like the downloaded version is newer that the one installed."
  740. elif isBiggerVersion "$curver" "$newver"; then
  741. echo "Seems like the downloaded version is older that the one installed."
  742. echo "It is basically a miracle or you have came from the future with this version!"
  743. echo "BE CAREFUL NOT TO DELETE THE BETA/ALPHA VERSION WITH THIS UPDATE!"
  744. else
  745. exitUpgrade "An unidentified error has ocurred. Exiting..."
  746. fi
  747. echo $'\n'"Are you sure that you want to replace the current instalation with the downloaded one?"
  748. read -p "Y/y to continue, anything else to cancel > " _answer
  749. _answer="$(lowercase $_answer)"
  750. echo
  751. if [[ "$_answer" = "y" || "$_answer" = "yes" ]]; then
  752. echo "Upgrading..."
  753. if cp "./pdfScale.sh" "$CURRENT_LOC" 2>/dev/null; then
  754. exitUpgrade $'\n'"Success! Upgrade finished!"$'\n'" > $CURRENT_LOC" $EXIT_SUCCESS
  755. else
  756. _answer="no"
  757. echo $'\n'"There was an error when copying the new version."
  758. echo "Do you want to retry using sudo (as root)?"
  759. read -p "Y/y to continue, anything else to cancel > " _answer
  760. _answer="$(lowercase $_answer)"
  761. if [[ "$_answer" = "y" || "$_answer" = "yes" ]]; then
  762. echo "Upgrading with sudo..."
  763. if sudo cp "./pdfScale.sh" "$CURRENT_LOC" 2>/dev/null; then
  764. exitUpgrade $'\n'"Success! Upgrade finished!"$'\n'" > $CURRENT_LOC" $EXIT_SUCCESS
  765. else
  766. exitUpgrade "There was an error when copying the new version."
  767. fi
  768. else
  769. exitUpgrade "Exiting... (cancelled by user)"
  770. fi
  771. fi
  772. exitUpgrade "An unidentified error has ocurred. Exiting..."
  773. else
  774. exitUpgrade "Exiting... (cancelled by user)"
  775. fi
  776. exitUpgrade "An unidentified error has ocurred. Exiting..."
  777. }
  778. # Compares versions with x.x.x format
  779. isBiggerVersion() {
  780. local OIFS=$IFS
  781. IFS='.'
  782. local _first=($1)
  783. local _second=($2)
  784. local _ret=$FALSE
  785. if [[ ${_first[0]} -gt ${_second[0]} ]]; then
  786. _ret=$TRUE
  787. elif [[ ${_first[0]} -lt ${_second[0]} ]]; then
  788. _ret=$FALSE
  789. elif [[ ${_first[1]} -gt ${_second[1]} ]]; then
  790. _ret=$TRUE
  791. elif [[ ${_first[1]} -lt ${_second[1]} ]]; then
  792. _ret=$FALSE
  793. elif [[ ${_first[2]} -gt ${_second[2]} ]]; then
  794. _ret=$TRUE
  795. elif [[ ${_first[2]} -lt ${_second[2]} ]]; then
  796. _ret=$FALSE
  797. fi
  798. IFS=$OIFS
  799. return $_ret
  800. }
  801. # Checks if output file is valid and writable
  802. validateOutFile() {
  803. local _tgtDir="$(dirname "$OUTFILEPDF")"
  804. isDir "$_tgtDir" || initError "Output directory does not exist!"$'\n'"Target Dir: $_tgtDir" $EXIT_NOWRITE_PERMISSION
  805. 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
  806. isTouchable "$OUTFILEPDF" || initError "Could not get write permission for output file!"$'\n'"Target File: $OUTFILEPDF"$'\nPermission Denied' $EXIT_NOWRITE_PERMISSION
  807. }
  808. # Returns $TRUE if we should not overwrite $OUTFILEPDF, $FALSE otherwise
  809. isAbortOnOverwrite() {
  810. return $ABORT_ON_OVERWRITE
  811. }
  812. # Returns $TRUE if we should print the GS call to stdout
  813. shouldPrintGSCall() {
  814. return $PRINT_GS_CALL
  815. }
  816. # Returns $TRUE if we are simulating, dry-run (no GS execution)
  817. isDryRun() {
  818. return $SIMULATE
  819. }
  820. # Parses and validates the scaling factor
  821. parseScale() {
  822. AUTOMATIC_SCALING=$FALSE
  823. if ! isFloatBiggerThanZero "$1"; then
  824. printError "Invalid factor: $1"
  825. printError "The factor must be a floating point number greater than 0"
  826. printError "Example: for 80% use 0.8"
  827. exit $EXIT_INVALID_SCALE
  828. fi
  829. SCALE="$1"
  830. }
  831. # Parse a forced mode of operation
  832. parseMode() {
  833. local param="$(lowercase $1)"
  834. case "${param}" in
  835. c|catgrep|'cat+grep'|grep|g)
  836. ADAPTIVEMODE=$FALSE
  837. MODE="CATGREP"
  838. return $TRUE
  839. ;;
  840. i|imagemagick|identify)
  841. ADAPTIVEMODE=$FALSE
  842. MODE="IDENTIFY"
  843. return $TRUE
  844. ;;
  845. m|mdls|quartz|mac)
  846. ADAPTIVEMODE=$FALSE
  847. MODE="MDLS"
  848. return $TRUE
  849. ;;
  850. p|pdfinfo)
  851. ADAPTIVEMODE=$FALSE
  852. MODE="PDFINFO"
  853. return $TRUE
  854. ;;
  855. a|auto|automatic|adaptive)
  856. ADAPTIVEMODE=$TRUE
  857. MODE=""
  858. return $TRUE
  859. ;;
  860. *)
  861. initError "Invalid PDF Size Detection Mode: \"$1\"" $EXIT_INVALID_OPTION
  862. return $FALSE
  863. ;;
  864. esac
  865. return $FALSE
  866. }
  867. # Parses and validates the scaling factor
  868. parseFlipDetectionMode() {
  869. local param="$(lowercase $1)"
  870. case "${param}" in
  871. d|disable)
  872. FLIP_DETECTION=$FALSE
  873. FLIP_FORCE=$FALSE
  874. ;;
  875. f|force)
  876. FLIP_DETECTION=$FALSE
  877. FLIP_FORCE=$TRUE
  878. ;;
  879. a|auto|automatic)
  880. FLIP_DETECTION=$TRUE
  881. FLIP_FORCE=$FALSE
  882. ;;
  883. *)
  884. initError "Invalid Flip Detection Mode: \"$1\"" $EXIT_INVALID_OPTION
  885. return $FALSE
  886. ;;
  887. esac
  888. }
  889. # Parses and validates the scaling factor
  890. parseAutoRotationMode() {
  891. local param="$(lowercase $1)"
  892. case "${param}" in
  893. n|none|'/none')
  894. AUTO_ROTATION='/None'
  895. ;;
  896. a|all|'/all')
  897. AUTO_ROTATION='/All'
  898. ;;
  899. p|pagebypage|'/pagebypage'|auto)
  900. AUTO_ROTATION='/PageByPage'
  901. ;;
  902. *)
  903. initError "Invalid Auto Rotation Mode: \"$1\"" $EXIT_INVALID_OPTION
  904. return $FALSE
  905. ;;
  906. esac
  907. }
  908. # Validades the a paper resize CLI option and sets the paper to $RESIZE_PAPER_TYPE
  909. parsePaperResize() {
  910. isEmpty "$1" && initError 'Invalid Paper Type: (empty)' $EXIT_INVALID_PAPER_SIZE
  911. local lowercasePaper="$(lowercase $1)"
  912. local customPaper=($lowercasePaper)
  913. if [[ "$customPaper" = 'same' || "$customPaper" = 'keep' || "$customPaper" = 'source' ]]; then
  914. RESIZE_PAPER_TYPE='source'
  915. elif [[ "${customPaper[0]}" = 'custom' ]]; then
  916. if isNotValidMeasure "${customPaper[1]}" || ! isFloatBiggerThanZero "${customPaper[2]}" || ! isFloatBiggerThanZero "${customPaper[3]}"; then
  917. initError "Invalid Custom Paper Definition!"$'\n'"Use: -r 'custom <measurement> <width> <height>'"$'\n'"Measurements: mm, in, pts" $EXIT_INVALID_OPTION
  918. fi
  919. RESIZE_PAPER_TYPE="custom"
  920. CUSTOM_RESIZE_PAPER=$TRUE
  921. if isMilimeter "${customPaper[1]}"; then
  922. RESIZE_WIDTH="$(milimetersToPoints "${customPaper[2]}")"
  923. RESIZE_HEIGHT="$(milimetersToPoints "${customPaper[3]}")"
  924. elif isInch "${customPaper[1]}"; then
  925. RESIZE_WIDTH="$(inchesToPoints "${customPaper[2]}")"
  926. RESIZE_HEIGHT="$(inchesToPoints "${customPaper[3]}")"
  927. elif isPoint "${customPaper[1]}"; then
  928. RESIZE_WIDTH="${customPaper[2]}"
  929. RESIZE_HEIGHT="${customPaper[3]}"
  930. else
  931. initError "Invalid Custom Paper Definition!"$'\n'"Use: -r 'custom <measurement> <width> <height>'"$'\n'"Measurements: mm, in, pts" $EXIT_INVALID_OPTION
  932. fi
  933. else
  934. isPaperName "$lowercasePaper" || initError "Invalid Paper Type: $1" $EXIT_INVALID_PAPER_SIZE
  935. RESIZE_PAPER_TYPE="$lowercasePaper"
  936. fi
  937. }
  938. # Goes to GS -dColorImageResolution and -dGrayImageResolution parameters
  939. parseImageResolution() {
  940. if isNotAnInteger "$1"; then
  941. printError "Invalid image resolution: $1"
  942. printError "The image resolution must be an integer"
  943. exit $EXIT_INVALID_IMAGE_RESOLUTION
  944. fi
  945. IMAGE_RESOLUTION="$1"
  946. }
  947. # Goes to GS -dColorImageDownsampleType and -dGrayImageDownsampleType parameters
  948. parseImageDownSample() {
  949. local param="$(lowercase $1)"
  950. case "${param}" in
  951. s|subsample|'/subsample')
  952. IMAGE_DOWNSAMPLE_TYPE='/Subsample'
  953. ;;
  954. a|average|'/average')
  955. IMAGE_DOWNSAMPLE_TYPE='/Average'
  956. ;;
  957. b|bicubic|'/bicubic'|auto)
  958. IMAGE_DOWNSAMPLE_TYPE='/Bicubic'
  959. ;;
  960. *)
  961. initError "Invalid Image Downsample Mode: \"$1\"" $EXIT_INVALID_OPTION
  962. return $FALSE
  963. ;;
  964. esac
  965. }
  966. # Goes to GS -dColorImageDownsampleType and -dGrayImageDownsampleType parameters
  967. parsePDFSettings() {
  968. local param="$(lowercase $1)"
  969. case "${param}" in
  970. s|screen|'/screen')
  971. PDF_SETTINGS='/screen'
  972. ;;
  973. e|ebook|'/ebook')
  974. PDF_SETTINGS='/ebook'
  975. ;;
  976. p|printer|'/printer'|auto)
  977. PDF_SETTINGS='/printer'
  978. ;;
  979. r|prepress|'/prepress')
  980. PDF_SETTINGS='/prepress'
  981. ;;
  982. d|default|'/default')
  983. PDF_SETTINGS='/default'
  984. ;;
  985. *)
  986. initError "Invalid PDF Setting Profile: \"$1\""$'\nValid > printer, screen, ebook, prepress, default' $EXIT_INVALID_OPTION
  987. return $FALSE
  988. ;;
  989. esac
  990. }
  991. # How to position the resized pages (sets translation)
  992. parseHorizontalAlignment() {
  993. local param="$(lowercase $1)"
  994. case "${param}" in
  995. l|left)
  996. HOR_ALIGN='LEFT'
  997. ;;
  998. r|right)
  999. HOR_ALIGN='RIGHT'
  1000. ;;
  1001. c|center|middle)
  1002. HOR_ALIGN='CENTER'
  1003. ;;
  1004. *)
  1005. initError "Invalid Horizontal Alignment Setting: \"$1\""$'\nValid > left, right, center' $EXIT_INVALID_OPTION
  1006. return $FALSE
  1007. ;;
  1008. esac
  1009. }
  1010. # How to position the resized pages (sets translation)
  1011. parseVerticalAlignment() {
  1012. local param="$(lowercase $1)"
  1013. case "${param}" in
  1014. t|top)
  1015. VERT_ALIGN='TOP'
  1016. ;;
  1017. b|bottom|bot)
  1018. VERT_ALIGN='BOTTOM'
  1019. ;;
  1020. c|center|middle)
  1021. VERT_ALIGN='CENTER'
  1022. ;;
  1023. *)
  1024. initError "Invalid Vertical Alignment Setting: \"$1\""$'\nValid > top, bottom, center' $EXIT_INVALID_OPTION
  1025. return $FALSE
  1026. ;;
  1027. esac
  1028. }
  1029. # Set X Translation Offset
  1030. parseXTransOffset() {
  1031. if isFloat "$1"; then
  1032. XTRANSOFFSET="$1"
  1033. return $TRUE
  1034. fi
  1035. printError "Invalid X Translation Offset: $1"
  1036. printError "The X Translation Offset must be a floating point number"
  1037. exit $EXIT_INVALID_OPTION
  1038. }
  1039. # Set Y Translation Offset
  1040. parseYTransOffset() {
  1041. if isFloat "$1"; then
  1042. YTRANSOFFSET="$1"
  1043. return $TRUE
  1044. fi
  1045. printError "Invalid Y Translation Offset: $1"
  1046. printError "The Y Translation Offset must be a floating point number"
  1047. exit $EXIT_INVALID_OPTION
  1048. }
  1049. ################### PDF PAGE SIZE DETECTION ####################
  1050. ################################################################
  1051. # Detects operation mode and also runs the adaptive mode
  1052. # PAGESIZE LOGIC
  1053. # 1- Try to get Mediabox with GREP
  1054. # 2- MacOS => try to use mdls
  1055. # 3- Try to use pdfinfo
  1056. # 4- Try to use identify (imagemagick)
  1057. # 5- Fail
  1058. ################################################################
  1059. getPageSize() {
  1060. if isNotAdaptiveMode; then
  1061. vprint " Get Page Size: Adaptive Disabled"
  1062. if [[ $MODE = "CATGREP" ]]; then
  1063. vprint " Method: Grep"
  1064. getPageSizeCatGrep
  1065. elif [[ $MODE = "MDLS" ]]; then
  1066. vprint " Method: Mac Quartz mdls"
  1067. getPageSizeMdls
  1068. elif [[ $MODE = "PDFINFO" ]]; then
  1069. vprint " Method: PDFInfo"
  1070. getPageSizePdfInfo
  1071. elif [[ $MODE = "IDENTIFY" ]]; then
  1072. vprint " Method: ImageMagick's Identify"
  1073. getPageSizeImagemagick
  1074. else
  1075. printError "Error! Invalid Mode: $MODE"
  1076. printError "Aborting execution..."
  1077. exit $EXIT_INVALID_OPTION
  1078. fi
  1079. return $TRUE
  1080. fi
  1081. vprint " Get Page Size: Adaptive Enabled"
  1082. vprint " Method: Grep"
  1083. getPageSizeCatGrep
  1084. if pageSizeIsInvalid && [[ $OSNAME = "Darwin" ]]; then
  1085. vprint " Failed"
  1086. vprint " Method: Mac Quartz mdls"
  1087. getPageSizeMdls
  1088. fi
  1089. if pageSizeIsInvalid; then
  1090. vprint " Failed"
  1091. vprint " Method: PDFInfo"
  1092. getPageSizePdfInfo
  1093. fi
  1094. if pageSizeIsInvalid; then
  1095. vprint " Failed"
  1096. vprint " Method: ImageMagick's Identify"
  1097. getPageSizeImagemagick
  1098. fi
  1099. if pageSizeIsInvalid; then
  1100. vprint " Failed"
  1101. printError "Error when detecting PDF paper size!"
  1102. printError "All methods of detection failed"
  1103. printError "You may want to install pdfinfo or imagemagick"
  1104. exit $EXIT_INVALID_PAGE_SIZE_DETECTED
  1105. fi
  1106. return $TRUE
  1107. }
  1108. # Gets page size using imagemagick's identify
  1109. getPageSizeImagemagick() {
  1110. # Sanity and Adaptive together
  1111. if isNotFile "$IDBIN" && isNotAdaptiveMode; then
  1112. notAdaptiveFailed "Make sure you installed ImageMagick and have identify on your \$PATH" "ImageMagick's Identify"
  1113. elif isNotFile "$IDBIN" && isAdaptiveMode; then
  1114. return $FALSE
  1115. fi
  1116. # get data from image magick
  1117. local identify="$("$IDBIN" -format '%[fx:w] %[fx:h]BREAKME' "$INFILEPDF" 2>/dev/null)"
  1118. if isEmpty "$identify" && isNotAdaptiveMode; then
  1119. notAdaptiveFailed "ImageMagicks's Identify returned an empty string!"
  1120. elif isEmpty "$identify" && isAdaptiveMode; then
  1121. return $FALSE
  1122. fi
  1123. identify="${identify%%BREAKME*}" # get page size only for 1st page
  1124. identify=($identify) # make it an array
  1125. PGWIDTH=$(printf '%.0f' "${identify[0]}") # assign
  1126. PGHEIGHT=$(printf '%.0f' "${identify[1]}") # assign
  1127. return $TRUE
  1128. }
  1129. # Gets page size using Mac Quarts mdls
  1130. getPageSizeMdls() {
  1131. # Sanity and Adaptive together
  1132. if isNotFile "$MDLSBIN" && isNotAdaptiveMode; then
  1133. notAdaptiveFailed "Are you even trying this on a Mac?" "Mac Quartz mdls"
  1134. elif isNotFile "$MDLSBIN" && isAdaptiveMode; then
  1135. return $FALSE
  1136. fi
  1137. local identify="$("$MDLSBIN" -mdls -name kMDItemPageHeight -name kMDItemPageWidth "$INFILEPDF" 2>/dev/null)"
  1138. if isEmpty "$identify" && isNotAdaptiveMode; then
  1139. notAdaptiveFailed "Mac Quartz mdls returned an empty string!"
  1140. elif isEmpty "$identify" && isAdaptiveMode; then
  1141. return $FALSE
  1142. fi
  1143. identify=${identify//$'\t'/ } # change tab to space
  1144. identify=($identify) # make it an array
  1145. if [[ "${identify[5]}" = "(null)" || "${identify[2]}" = "(null)" ]] && isNotAdaptiveMode; then
  1146. notAdaptiveFailed "There was no metadata to read from the file! Is Spotlight OFF?"
  1147. elif [[ "${identify[5]}" = "(null)" || "${identify[2]}" = "(null)" ]] && isAdaptiveMode; then
  1148. return $FALSE
  1149. fi
  1150. PGWIDTH=$(printf '%.0f' "${identify[5]}") # assign
  1151. PGHEIGHT=$(printf '%.0f' "${identify[2]}") # assign
  1152. return $TRUE
  1153. }
  1154. # Gets page size using Linux PdfInfo
  1155. getPageSizePdfInfo() {
  1156. # Sanity and Adaptive together
  1157. if isNotFile "$PDFINFOBIN" && isNotAdaptiveMode; then
  1158. notAdaptiveFailed "Do you have pdfinfo installed and available on your \$PATH?" "Linux pdfinfo"
  1159. elif isNotFile "$PDFINFOBIN" && isAdaptiveMode; then
  1160. return $FALSE
  1161. fi
  1162. # get data from image magick
  1163. local identify="$("$PDFINFOBIN" "$INFILEPDF" 2>/dev/null | "$GREPBIN" -i 'Page size:' )"
  1164. if isEmpty "$identify" && isNotAdaptiveMode; then
  1165. notAdaptiveFailed "Linux PdfInfo returned an empty string!"
  1166. elif isEmpty "$identify" && isAdaptiveMode; then
  1167. return $FALSE
  1168. fi
  1169. identify="${identify##*Page size:}" # remove stuff
  1170. identify=($identify) # make it an array
  1171. PGWIDTH=$(printf '%.0f' "${identify[0]}") # assign
  1172. PGHEIGHT=$(printf '%.0f' "${identify[2]}") # assign
  1173. return $TRUE
  1174. }
  1175. # Gets page size using cat and grep
  1176. getPageSizeCatGrep() {
  1177. # get MediaBox info from PDF file using grep, these are all possible
  1178. # /MediaBox [0 0 595 841]
  1179. # /MediaBox [ 0 0 595.28 841.89]
  1180. # /MediaBox[ 0 0 595.28 841.89 ]
  1181. # Get MediaBox data if possible
  1182. local mediaBox="$("$GREPBIN" -a -e '/MediaBox' -m 1 "$INFILEPDF" 2>/dev/null)"
  1183. mediaBox="${mediaBox##*/MediaBox}"
  1184. # No page size data available
  1185. if isEmpty "$mediaBox" && isNotAdaptiveMode; then
  1186. notAdaptiveFailed "There is no MediaBox in the pdf document!"
  1187. elif isEmpty "$mediaBox" && isAdaptiveMode; then
  1188. return $FALSE
  1189. fi
  1190. # remove chars [ and ]
  1191. mediaBox="${mediaBox//[}"
  1192. mediaBox="${mediaBox//]}"
  1193. mediaBox=($mediaBox) # make it an array
  1194. mbCount=${#mediaBox[@]} # array size
  1195. # sanity
  1196. if [[ $mbCount -lt 4 ]]; then
  1197. printError "Error when reading the page size!"
  1198. printError "The page size information is invalid!"
  1199. exit $EXIT_INVALID_PAGE_SIZE_DETECTED
  1200. fi
  1201. # we are done
  1202. PGWIDTH=$(printf '%.0f' "${mediaBox[2]}") # Get Round Width
  1203. PGHEIGHT=$(printf '%.0f' "${mediaBox[3]}") # Get Round Height
  1204. return $TRUE
  1205. }
  1206. # Prints error message and exits execution
  1207. notAdaptiveFailed() {
  1208. local errProgram="$2"
  1209. local errStr="$1"
  1210. if isEmpty "$2"; then
  1211. printError "Error when reading input file!"
  1212. printError "Could not determine the page size!"
  1213. else
  1214. printError "Error! $2 was not found!"
  1215. fi
  1216. isNotEmpty "$errStr" && printError "$errStr"
  1217. printError "Aborting! You may want to try the adaptive mode."
  1218. exit $EXIT_INVALID_PAGE_SIZE_DETECTED
  1219. }
  1220. # Verbose print of the Width and Height (Source or New) to screen
  1221. vPrintPageSizes() {
  1222. vprint " $1 Width: $PGWIDTH postscript-points"
  1223. vprint "$1 Height: $PGHEIGHT postscript-points"
  1224. }
  1225. #################### GHOSTSCRIPT PAPER INFO ####################
  1226. # Loads valid paper info to memory
  1227. getPaperInfo() {
  1228. # name inchesW inchesH mmW mmH pointsW pointsH
  1229. sizesUS="\
  1230. 11x17 11.0 17.0 279 432 792 1224
  1231. ledger 17.0 11.0 432 279 1224 792
  1232. legal 8.5 14.0 216 356 612 1008
  1233. letter 8.5 11.0 216 279 612 792
  1234. lettersmall 8.5 11.0 216 279 612 792
  1235. archE 36.0 48.0 914 1219 2592 3456
  1236. archD 24.0 36.0 610 914 1728 2592
  1237. archC 18.0 24.0 457 610 1296 1728
  1238. archB 12.0 18.0 305 457 864 1296
  1239. archA 9.0 12.0 229 305 648 864"
  1240. sizesISO="\
  1241. a0 33.1 46.8 841 1189 2384 3370
  1242. a1 23.4 33.1 594 841 1684 2384
  1243. a2 16.5 23.4 420 594 1191 1684
  1244. a3 11.7 16.5 297 420 842 1191
  1245. a4 8.3 11.7 210 297 595 842
  1246. a4small 8.3 11.7 210 297 595 842
  1247. a5 5.8 8.3 148 210 420 595
  1248. a6 4.1 5.8 105 148 297 420
  1249. a7 2.9 4.1 74 105 210 297
  1250. a8 2.1 2.9 52 74 148 210
  1251. a9 1.5 2.1 37 52 105 148
  1252. a10 1.0 1.5 26 37 73 105
  1253. isob0 39.4 55.7 1000 1414 2835 4008
  1254. isob1 27.8 39.4 707 1000 2004 2835
  1255. isob2 19.7 27.8 500 707 1417 2004
  1256. isob3 13.9 19.7 353 500 1001 1417
  1257. isob4 9.8 13.9 250 353 709 1001
  1258. isob5 6.9 9.8 176 250 499 709
  1259. isob6 4.9 6.9 125 176 354 499
  1260. c0 36.1 51.1 917 1297 2599 3677
  1261. c1 25.5 36.1 648 917 1837 2599
  1262. c2 18.0 25.5 458 648 1298 1837
  1263. c3 12.8 18.0 324 458 918 1298
  1264. c4 9.0 12.8 229 324 649 918
  1265. c5 6.4 9.0 162 229 459 649
  1266. c6 4.5 6.4 114 162 323 459"
  1267. sizesJIS="\
  1268. jisb0 NA NA 1030 1456 2920 4127
  1269. jisb1 NA NA 728 1030 2064 2920
  1270. jisb2 NA NA 515 728 1460 2064
  1271. jisb3 NA NA 364 515 1032 1460
  1272. jisb4 NA NA 257 364 729 1032
  1273. jisb5 NA NA 182 257 516 729
  1274. jisb6 NA NA 128 182 363 516"
  1275. sizesOther="\
  1276. flsa 8.5 13.0 216 330 612 936
  1277. flse 8.5 13.0 216 330 612 936
  1278. halfletter 5.5 8.5 140 216 396 612
  1279. hagaki 3.9 5.8 100 148 283 420"
  1280. sizesAll="\
  1281. $sizesUS
  1282. $sizesISO
  1283. $sizesJIS
  1284. $sizesOther"
  1285. }
  1286. # Gets a paper size in points and sets it to RESIZE_WIDTH and RESIZE_HEIGHT
  1287. getGSPaperSize() {
  1288. isEmpty "$sizesall" && getPaperInfo
  1289. while read l; do
  1290. local cols=($l)
  1291. if [[ "$1" == ${cols[0]} ]]; then
  1292. RESIZE_WIDTH=${cols[5]}
  1293. RESIZE_HEIGHT=${cols[6]}
  1294. return $TRUE
  1295. fi
  1296. done <<< "$sizesAll"
  1297. }
  1298. # Gets a paper size in points and sets it to RESIZE_WIDTH and RESIZE_HEIGHT
  1299. getGSPaperName() {
  1300. local w="$(printf "%.0f" $1)"
  1301. local h="$(printf "%.0f" $2)"
  1302. isEmpty "$sizesall" && getPaperInfo
  1303. # Because US Standard has inverted sizes, I need to scan 2 times
  1304. # instead of just testing if width is bigger than height
  1305. while read l; do
  1306. local cols=($l)
  1307. if [[ "$w" == ${cols[5]} && "$h" == ${cols[6]} ]]; then
  1308. printf "%s Portrait" $(uppercase ${cols[0]})
  1309. return $TRUE
  1310. fi
  1311. done <<< "$sizesAll"
  1312. while read l; do
  1313. local cols=($l)
  1314. if [[ "$w" == ${cols[6]} && "$h" == ${cols[5]} ]]; then
  1315. printf "%s Landscape" $(uppercase ${cols[0]})
  1316. return $TRUE
  1317. fi
  1318. done <<< "$sizesAll"
  1319. return $FALSE
  1320. }
  1321. # Loads an array with paper names to memory
  1322. getPaperNames() {
  1323. 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 \
  1324. 11x17 ledger legal letter lettersmall archE archD archC archB archA \
  1325. jisb0 jisb1 jisb2 jisb3 jisb4 jisb5 jisb6 \
  1326. flsa flse halfletter hagaki)
  1327. }
  1328. # Prints uppercase paper names to screen (used in help)
  1329. printPaperNames() {
  1330. isEmpty "$paperNames" && getPaperNames
  1331. for i in "${!paperNames[@]}"; do
  1332. [[ $i -eq 0 ]] && echo -n -e ' '
  1333. [[ $i -ne 0 && $((i % 5)) -eq 0 ]] && echo -n -e $'\n '
  1334. ppN="$(uppercase ${paperNames[i]})"
  1335. printf "%-14s" "$ppN"
  1336. done
  1337. echo ""
  1338. }
  1339. # Returns $TRUE if $! is a valid paper name, $FALSE otherwise
  1340. isPaperName() {
  1341. isEmpty "$1" && return $FALSE
  1342. isEmpty "$paperNames" && getPaperNames
  1343. for i in "${paperNames[@]}"; do
  1344. [[ "$i" = "$1" ]] && return $TRUE
  1345. done
  1346. return $FALSE
  1347. }
  1348. # Prints all tables with ghostscript paper information
  1349. printPaperInfo() {
  1350. printVersion 3
  1351. echo $'\n'"Paper Sizes Information"$'\n'
  1352. getPaperInfo
  1353. printPaperTable "ISO STANDARD" "$sizesISO"; echo
  1354. printPaperTable "US STANDARD" "$sizesUS"; echo
  1355. printPaperTable "JIS STANDARD *Aproximated Points" "$sizesJIS"; echo
  1356. printPaperTable "OTHERS" "$sizesOther"; echo
  1357. }
  1358. # GS paper table helper, prints a full line
  1359. printTableLine() {
  1360. echo '+-----------------------------------------------------------------+'
  1361. }
  1362. # GS paper table helper, prints a line with dividers
  1363. printTableDivider() {
  1364. echo '+-----------------+-------+-------+-------+-------+-------+-------+'
  1365. }
  1366. # GS paper table helper, prints a table header
  1367. printTableHeader() {
  1368. echo '| Name | inchW | inchH | mm W | mm H | pts W | pts H |'
  1369. }
  1370. # GS paper table helper, prints a table title
  1371. printTableTitle() {
  1372. printf "| %-64s%s\n" "$1" '|'
  1373. }
  1374. # GS paper table printer, prints a table for a paper variable
  1375. printPaperTable() {
  1376. printTableLine
  1377. printTableTitle "$1"
  1378. printTableLine
  1379. printTableHeader
  1380. printTableDivider
  1381. while read l; do
  1382. local cols=($l)
  1383. printf "| %-15s | %+5s | %+5s | %+5s | %+5s | %+5s | %+5s |\n" ${cols[*]};
  1384. done <<< "$2"
  1385. printTableDivider
  1386. }
  1387. # Returns $TRUE if $1 is a valid measurement for a custom paper, $FALSE otherwise
  1388. isNotValidMeasure() {
  1389. isMilimeter "$1" || isInch "$1" || isPoint "$1" && return $FALSE
  1390. return $TRUE
  1391. }
  1392. # Returns $TRUE if $1 is a valid milimeter string, $FALSE otherwise
  1393. isMilimeter() {
  1394. [[ "$1" = 'mm' || "$1" = 'milimeters' || "$1" = 'milimeter' ]] && return $TRUE
  1395. return $FALSE
  1396. }
  1397. # Returns $TRUE if $1 is a valid inch string, $FALSE otherwise
  1398. isInch() {
  1399. [[ "$1" = 'in' || "$1" = 'inch' || "$1" = 'inches' ]] && return $TRUE
  1400. return $FALSE
  1401. }
  1402. # Returns $TRUE if $1 is a valid point string, $FALSE otherwise
  1403. isPoint() {
  1404. [[ "$1" = 'pt' || "$1" = 'pts' || "$1" = 'point' || "$1" = 'points' ]] && return $TRUE
  1405. return $FALSE
  1406. }
  1407. # Returns $TRUE if a custom paper is being used, $FALSE otherwise
  1408. isCustomPaper() {
  1409. return $CUSTOM_RESIZE_PAPER
  1410. }
  1411. # Returns $FALSE if a custom paper is being used, $TRUE otherwise
  1412. isNotCustomPaper() {
  1413. isCustomPaper && return $FALSE
  1414. return $TRUE
  1415. }
  1416. ######################### CONVERSIONS ##########################
  1417. # Prints the lowercase char value for $1
  1418. lowercaseChar() {
  1419. case "$1" in
  1420. [A-Z])
  1421. n=$(printf "%d" "'$1")
  1422. n=$((n+32))
  1423. printf \\$(printf "%o" "$n")
  1424. ;;
  1425. *)
  1426. printf "%s" "$1"
  1427. ;;
  1428. esac
  1429. }
  1430. # Prints the lowercase version of a string
  1431. lowercase() {
  1432. word="$@"
  1433. for((i=0;i<${#word};i++))
  1434. do
  1435. ch="${word:$i:1}"
  1436. lowercaseChar "$ch"
  1437. done
  1438. }
  1439. # Prints the uppercase char value for $1
  1440. uppercaseChar(){
  1441. case "$1" in
  1442. [a-z])
  1443. n=$(printf "%d" "'$1")
  1444. n=$((n-32))
  1445. printf \\$(printf "%o" "$n")
  1446. ;;
  1447. *)
  1448. printf "%s" "$1"
  1449. ;;
  1450. esac
  1451. }
  1452. # Prints the uppercase version of a string
  1453. uppercase() {
  1454. word="$@"
  1455. for((i=0;i<${#word};i++))
  1456. do
  1457. ch="${word:$i:1}"
  1458. uppercaseChar "$ch"
  1459. done
  1460. }
  1461. # Prints the postscript points rounded equivalent from $1 mm
  1462. milimetersToPoints() {
  1463. local pts=$(echo "scale=8; $1 * 72 / 25.4" | "$BCBIN")
  1464. printf '%.0f' "$pts" # Print rounded conversion
  1465. }
  1466. # Prints the postscript points rounded equivalent from $1 inches
  1467. inchesToPoints() {
  1468. local pts=$(echo "scale=8; $1 * 72" | "$BCBIN")
  1469. printf '%.0f' "$pts" # Print rounded conversion
  1470. }
  1471. # Prints the mm equivalent from $1 postscript points
  1472. pointsToMilimeters() {
  1473. local pts=$(echo "scale=8; $1 / 72 * 25.4" | "$BCBIN")
  1474. printf '%.0f' "$pts" # Print rounded conversion
  1475. }
  1476. # Prints the inches equivalent from $1 postscript points
  1477. pointsToInches() {
  1478. local pts=$(echo "scale=8; $1 / 72" | "$BCBIN")
  1479. printf '%.1f' "$pts" # Print rounded conversion
  1480. }
  1481. ######################## MODE-DETECTION ########################
  1482. # Returns $TRUE if the scale was set manually, $FALSE if we are using automatic scaling
  1483. isManualScaledMode() {
  1484. [[ $AUTOMATIC_SCALING -eq $TRUE ]] && return $FALSE
  1485. return $TRUE
  1486. }
  1487. # Returns true if we are resizing a paper (ignores scaling), false otherwise
  1488. isResizeMode() {
  1489. isEmpty $RESIZE_PAPER_TYPE && return $FALSE
  1490. return $TRUE
  1491. }
  1492. # Returns true if we are resizing a paper and the scale was manually set
  1493. isMixedMode() {
  1494. isResizeMode && isManualScaledMode && return $TRUE
  1495. return $FALSE
  1496. }
  1497. # Return $TRUE if adaptive mode is enabled, $FALSE otherwise
  1498. isAdaptiveMode() {
  1499. return $ADAPTIVEMODE
  1500. }
  1501. # Return $TRUE if adaptive mode is disabled, $FALSE otherwise
  1502. isNotAdaptiveMode() {
  1503. isAdaptiveMode && return $FALSE
  1504. return $TRUE
  1505. }
  1506. ########################## VALIDATORS ##########################
  1507. # Returns $TRUE if $PGWIDTH OR $PGWIDTH are empty or NOT an Integer, $FALSE otherwise
  1508. pageSizeIsInvalid() {
  1509. if isNotAnInteger "$PGWIDTH" || isNotAnInteger "$PGHEIGHT"; then
  1510. return $TRUE
  1511. fi
  1512. return $FALSE
  1513. }
  1514. # Return $TRUE if $1 is empty, $FALSE otherwise
  1515. isEmpty() {
  1516. [[ -z "$1" ]] && return $TRUE
  1517. return $FALSE
  1518. }
  1519. # Return $TRUE if $1 is NOT empty, $FALSE otherwise
  1520. isNotEmpty() {
  1521. [[ -z "$1" ]] && return $FALSE
  1522. return $TRUE
  1523. }
  1524. # Returns $TRUE if $1 is an integer, $FALSE otherwise
  1525. isAnInteger() {
  1526. case $1 in
  1527. ''|*[!0-9]*) return $FALSE ;;
  1528. *) return $TRUE ;;
  1529. esac
  1530. }
  1531. # Returns $TRUE if $1 is NOT an integer, $FALSE otherwise
  1532. isNotAnInteger() {
  1533. case $1 in
  1534. ''|*[!0-9]*) return $TRUE ;;
  1535. *) return $FALSE ;;
  1536. esac
  1537. }
  1538. # Returns $TRUE if $1 is a floating point number (or an integer), $FALSE otherwise
  1539. isFloat() {
  1540. [[ -n "$1" && "$1" =~ ^-?[0-9]*([.][0-9]+)?$ ]] && return $TRUE
  1541. return $FALSE
  1542. }
  1543. # Returns $TRUE if $1 is a floating point number bigger than zero, $FALSE otherwise
  1544. isFloatBiggerThanZero() {
  1545. isFloat "$1" && [[ (( $1 > 0 )) ]] && return $TRUE
  1546. return $FALSE
  1547. }
  1548. # Returns $TRUE if $1 is readable, $FALSE otherwise
  1549. isReadable() {
  1550. [[ -r "$1" ]] && return $TRUE
  1551. return $FALSE;
  1552. }
  1553. # Returns $TRUE if $1 is a directory, $FALSE otherwise
  1554. isDir() {
  1555. [[ -d "$1" ]] && return $TRUE
  1556. return $FALSE;
  1557. }
  1558. # Returns $FALSE if $1 is a directory, $TRUE otherwise
  1559. isNotDir() {
  1560. isDir "$1" && return $FALSE
  1561. return $TRUE;
  1562. }
  1563. # Returns 0 if succeded, other integer otherwise
  1564. isTouchable() {
  1565. touch "$1" 2>/dev/null
  1566. }
  1567. # Returns $TRUE if $1 has a .pdf extension, false otherwsie
  1568. isPDF() {
  1569. [[ "$(lowercase $1)" =~ ^..*\.pdf$ ]] && return $TRUE
  1570. return $FALSE
  1571. }
  1572. # Returns $TRUE if $1 is a file, false otherwsie
  1573. isFile() {
  1574. [[ -f "$1" ]] && return $TRUE
  1575. return $FALSE
  1576. }
  1577. # Returns $TRUE if $1 is NOT a file, false otherwsie
  1578. isNotFile() {
  1579. [[ -f "$1" ]] && return $FALSE
  1580. return $TRUE
  1581. }
  1582. # Returns $TRUE if $1 is executable, false otherwsie
  1583. isExecutable() {
  1584. [[ -x "$1" ]] && return $TRUE
  1585. return $FALSE
  1586. }
  1587. # Returns $TRUE if $1 is NOT executable, false otherwsie
  1588. isNotExecutable() {
  1589. [[ -x "$1" ]] && return $FALSE
  1590. return $TRUE
  1591. }
  1592. # Returns $TRUE if $1 is a file and executable, false otherwsie
  1593. isAvailable() {
  1594. if isFile "$1" && isExecutable "$1"; then
  1595. return $TRUE
  1596. fi
  1597. return $FALSE
  1598. }
  1599. # Returns $TRUE if $1 is NOT a file or NOT executable, false otherwsie
  1600. isNotAvailable() {
  1601. if isNotFile "$1" || isNotExecutable "$1"; then
  1602. return $TRUE
  1603. fi
  1604. return $FALSE
  1605. }
  1606. # Returns $TRUE if we should avoid https certificate (on upgrade)
  1607. useInsecure() {
  1608. return $HTTPS_INSECURE
  1609. }
  1610. ###################### PRINTING TO SCREEN ######################
  1611. # Prints version
  1612. printVersion() {
  1613. local vStr=""
  1614. [[ "$2" = 'verbose' ]] && vStr=" - Verbose Execution"
  1615. local strBanner="$PDFSCALE_NAME v$VERSION$vStr"
  1616. if [[ $1 -eq 2 ]]; then
  1617. printError "$strBanner"
  1618. elif [[ $1 -eq 3 ]]; then
  1619. local extra="$(isNotEmpty "$2" && echo "$2")"
  1620. echo "$strBanner$extra"
  1621. else
  1622. vprint "$strBanner"
  1623. fi
  1624. }
  1625. # Prints input, output file info, if verbosing
  1626. vPrintFileInfo() {
  1627. vprint " Input File: $INFILEPDF"
  1628. vprint " Output File: $OUTFILEPDF"
  1629. }
  1630. # Prints the scale factor to screen, or custom message
  1631. vPrintScaleFactor() {
  1632. local scaleMsg="$SCALE"
  1633. isNotEmpty "$1" && scaleMsg="$1"
  1634. vprint " Scale Factor: $scaleMsg"
  1635. }
  1636. # Prints help info
  1637. printHelp() {
  1638. printVersion 3
  1639. local paperList="$(printPaperNames)"
  1640. echo "
  1641. Usage: $PDFSCALE_NAME <inFile.pdf>
  1642. $PDFSCALE_NAME -i <inFile.pdf>
  1643. $PDFSCALE_NAME [-v] [-s <factor>] [-m <page-detection>] <inFile.pdf> [outfile.pdf]
  1644. $PDFSCALE_NAME [-v] [-r <paper>] [-f <flip-detection>] [-a <auto-rotation>] <inFile.pdf> [outfile.pdf]
  1645. $PDFSCALE_NAME -p
  1646. $PDFSCALE_NAME -h
  1647. $PDFSCALE_NAME -V
  1648. Parameters:
  1649. -v, --verbose
  1650. Verbose mode, prints extra information
  1651. Use twice for timestamp
  1652. -h, --help
  1653. Print this help to screen and exits
  1654. -V, --version
  1655. Prints version to screen and exits
  1656. --install, --self-install [target-path]
  1657. Install itself to [target-path] or /usr/local/bin/pdfscale if not specified
  1658. Should contain the full path with the desired executable name
  1659. --upgrade, --self-upgrade
  1660. Upgrades itself in-place (same path/name of the pdfScale.sh caller)
  1661. Downloads the master branch tarball and tries to self-upgrade
  1662. -n, --no-overwrite
  1663. Aborts execution if the output PDF file already exists
  1664. By default, the output file will be overwritten
  1665. -m, --mode <mode>
  1666. Paper size detection mode
  1667. Modes: a, adaptive Default mode, tries all the methods below
  1668. g, grep Forces the use of Grep method
  1669. m, mdls Forces the use of MacOS Quartz mdls
  1670. p, pdfinfo Forces the use of PDFInfo
  1671. i, identify Forces the use of ImageMagick's Identify
  1672. -i, --info <file>
  1673. Prints <file> Paper Size information to screen and exits
  1674. -s, --scale <factor>
  1675. Changes the scaling factor or forces mixed mode
  1676. Defaults: $SCALE (scale mode) / Disabled (resize mode)
  1677. MUST be a number bigger than zero
  1678. Eg. -s 0.8 for 80% of the original size
  1679. -r, --resize <paper>
  1680. Triggers the Resize Paper Mode, disables auto-scaling of $SCALE
  1681. Resize PDF and fit-to-page
  1682. <paper> can be: source, custom or a valid std paper name, read below
  1683. -f, --flip-detect <mode>
  1684. Flip Detection Mode, defaults to 'auto'
  1685. Inverts Width <-> Height of a Resized PDF
  1686. Modes: a, auto Keeps source orientation, default
  1687. f, force Forces flip W <-> H
  1688. d, disable Disables flipping
  1689. -a, --auto-rotate <mode>
  1690. Setting for GS -dAutoRotatePages, defaults to 'PageByPage'
  1691. Uses text-orientation detection to set Portrait/Landscape
  1692. Modes: p, pagebypage Auto-rotates pages individually
  1693. n, none Retains orientation of each page
  1694. a, all Rotates all pages (or none) depending
  1695. on a kind of \"majority decision\"
  1696. --hor-align, --horizontal-alignment <left|center|right>
  1697. Where to translate the scaled page
  1698. Default: center
  1699. Options: left, right, center
  1700. --vert-align, --vertical-alignment <top|center|bottom>
  1701. Where to translate the scaled page
  1702. Default: center
  1703. Options: top, bootom, center
  1704. --xoffset, --xtrans-offset <FloatNumber>
  1705. Add/Subtract from the X translation (move left-right)
  1706. Default: 0.0 (zero)
  1707. Options: Positive or negative floating point number
  1708. --yoffset, --ytrans-offset <FloatNumber>
  1709. Add/Subtract from the Y translation (move top-bottim)
  1710. Default: 0.0 (zero)
  1711. Options: Positive or negative floating point number
  1712. --pdf-settings <gs-pdf-profile>
  1713. Ghostscript PDF Profile to use in -dPDFSETTINGS
  1714. Default: printer
  1715. Options: screen, ebook, printer, prepress, default
  1716. --image-downsample <gs-downsample-method>
  1717. Ghostscript Image Downsample Method
  1718. Default: bicubic
  1719. Options: subsample, average, bicubic
  1720. --image-resolution <dpi>
  1721. Resolution in DPI of color and grayscale images in output
  1722. Default: 300
  1723. --dry-run, --simulate
  1724. Just simulate execution. Will not run ghostscript
  1725. --print-gs-call, --gs-call
  1726. Print GS call to stdout. Will print at the very end between markers
  1727. -p, --print-papers
  1728. Prints Standard Paper info tables to screen and exits
  1729. Scaling Mode:
  1730. - The default mode of operation is scaling mode with fixed paper
  1731. size and scaling pre-set to $SCALE
  1732. - By not using the resize mode you are using scaling mode
  1733. - Flip-Detection and Auto-Rotation are disabled in Scaling mode,
  1734. you can use '-r source -s <scale>' to override.
  1735. - Ghostscript placement is from bottom-left position. This means that
  1736. a bottom-left placement has ZERO for both X and Y translations.
  1737. Resize Paper Mode:
  1738. - Disables the default scaling factor! ($SCALE)
  1739. - Changes the PDF Paper Size in points. Will fit-to-page
  1740. Mixed Mode:
  1741. - In mixed mode both the -s option and -r option must be specified
  1742. - The PDF will be first resized then scaled
  1743. Output filename:
  1744. - Having the extension .pdf on the output file name is optional,
  1745. it will be added if not present.
  1746. - The output filename is optional. If no file name is passed
  1747. the output file will have the same name/destination of the
  1748. input file with added suffixes:
  1749. .SCALED.pdf is added to scaled files
  1750. .<PAPERSIZE>.pdf is added to resized files
  1751. .<PAPERSIZE>.SCALED.pdf is added in mixed mode
  1752. Standard Paper Names: (case-insensitive)
  1753. $paperList
  1754. Custom Paper Size:
  1755. - Paper size can be set manually in Milimeters, Inches or Points
  1756. - Custom paper definition MUST be quoted into a single parameter
  1757. - Actual size is applied in points (mms and inches are transformed)
  1758. - Measurements: mm, mms, milimeters
  1759. pt, pts, points
  1760. in, inch, inches
  1761. Use: $PDFSCALE_NAME -r 'custom <measurement> <width> <height>'
  1762. Ex: $PDFSCALE_NAME -r 'custom mm 300 300'
  1763. Using Source Paper Size: (no-resizing)
  1764. - Wildcard 'source' is used used to keep paper size the same as the input
  1765. - Usefull to run Auto-Rotation without resizing
  1766. - Eg. $PDFSCALE_NAME -r source ./input.dpf
  1767. Options and Parameters Parsing:
  1768. - From v2.1.0 (long-opts) there is no need to pass file names at the end
  1769. - Anything that is not a short-option is case-insensitive
  1770. - Short-options: case-sensitive Eg. -v for Verbose, -V for Version
  1771. - Long-options: case-insensitive Eg. --SCALE and --scale are the same
  1772. - Subparameters: case-insensitive Eg. -m PdFinFo is valid
  1773. - Grouping short-options is not supported Eg. -vv, or -vs 0.9
  1774. Additional Notes:
  1775. - File and folder names with spaces should be quoted or escaped
  1776. - The scaling is centered and using a scale bigger than 1.0 may
  1777. result on cropping parts of the PDF
  1778. - For detailed paper types information, use: $PDFSCALE_NAME -p
  1779. Examples:
  1780. $PDFSCALE_NAME myPdfFile.pdf
  1781. $PDFSCALE_NAME -i '/home/My Folder/My PDF File.pdf'
  1782. $PDFSCALE_NAME myPdfFile.pdf \"My Scaled Pdf\"
  1783. $PDFSCALE_NAME -v -v myPdfFile.pdf
  1784. $PDFSCALE_NAME -s 0.85 myPdfFile.pdf My\\ Scaled\\ Pdf.pdf
  1785. $PDFSCALE_NAME -m pdfinfo -s 0.80 -v myPdfFile.pdf
  1786. $PDFSCALE_NAME -v -v -m i -s 0.7 myPdfFile.pdf
  1787. $PDFSCALE_NAME -r A4 myPdfFile.pdf
  1788. $PDFSCALE_NAME -v -v -r \"custom mm 252 356\" -s 0.9 -f \"../input file.pdf\" \"../my new pdf\"
  1789. "
  1790. }
  1791. # Prints usage info
  1792. usage() {
  1793. [[ "$2" != 'nobanner' ]] && printVersion 2
  1794. isNotEmpty "$1" && printError $'\n'"$1"
  1795. printError $'\n'"Usage: $PDFSCALE_NAME [-v] [-s <factor>] [-m <mode>] [-r <paper> [-f <mode>] [-a <mode>]] <inFile.pdf> [outfile.pdf]"
  1796. printError "Help : $PDFSCALE_NAME -h"
  1797. }
  1798. # Prints Verbose information
  1799. vprint() {
  1800. [[ $VERBOSE -eq 0 ]] && return $TRUE
  1801. timestamp=""
  1802. [[ $VERBOSE -gt 1 ]] && timestamp="$(date +%Y-%m-%d:%H:%M:%S) | "
  1803. echo "$timestamp$1"
  1804. }
  1805. # Prints dependency information and aborts execution
  1806. printDependency() {
  1807. printVersion 2
  1808. local brewName="$1"
  1809. [[ "$1" = 'pdfinfo' && "$OSNAME" = "Darwin" ]] && brewName="xpdf"
  1810. printError $'\n'"ERROR! You need to install the package '$1'"$'\n'
  1811. printError "Linux apt-get.: sudo apt-get install $1"
  1812. printError "Linux yum.....: sudo yum install $1"
  1813. printError "MacOS homebrew: brew install $brewName"
  1814. printError $'\n'"Aborting..."
  1815. exit $EXIT_MISSING_DEPENDENCY
  1816. }
  1817. # Prints initialization errors and aborts execution
  1818. initError() {
  1819. local errStr="$1"
  1820. local exitStat=$2
  1821. isEmpty "$exitStat" && exitStat=$EXIT_ERROR
  1822. usage "ERROR! $errStr" "$3"
  1823. exit $exitStat
  1824. }
  1825. # Prints to stderr
  1826. printError() {
  1827. echo >&2 "$@"
  1828. }
  1829. ########################## EXECUTION ###########################
  1830. initDeps
  1831. getOptions "${@}"
  1832. main
  1833. exit $?