Bash Script to scale and/or resize PDFs from the command line.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

1278 行
42 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 - 2017 / 05 / 14
  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.0.4"
  13. ###################### EXTERNAL PROGRAMS #######################
  14. GSBIN="" # GhostScript Binary
  15. BCBIN="" # BC Math Binary
  16. IDBIN="" # Identify Binary
  17. PDFINFOBIN="" # PDF Info Binary
  18. MDLSBIN="" # MacOS mdls Binary
  19. ##################### ENVIRONMENT SET-UP #######################
  20. LC_MEASUREMENT="C" # To make sure our numbers have .decimals
  21. LC_ALL="C" # Some languages use , as decimal token
  22. LC_CTYPE="C"
  23. LC_NUMERIC="C"
  24. TRUE=0 # Silly stuff
  25. FALSE=1
  26. ########################### GLOBALS ############################
  27. SCALE="0.95" # scaling factor (0.95 = 95%, e.g.)
  28. VERBOSE=0 # verbosity Level
  29. PDFSCALE_NAME="$(basename $0)" # simplified name of this script
  30. OSNAME="$(uname 2>/dev/null)" # Check where we are running
  31. JUST_IDENTIFY=$FALSE # Flag to just show PDF info
  32. ADAPTIVEMODE=$TRUE # Automatically try to guess best mode
  33. AUTOMATIC_SCALING=$TRUE # Default scaling in $SCALE, override by resize mode
  34. MODE="" # Which page size detection to use
  35. RESIZE_PAPER_TYPE="" # Pre-defined paper to use
  36. CUSTOM_RESIZE_PAPER=$FALSE # If we are using a custom-defined paper
  37. FLIP_DETECTION=$TRUE # If we should run the Flip-detection
  38. FLIP_FORCE=$FALSE # If we should force Flipping
  39. AUTO_ROTATION='/PageByPage' # GS call auto-rotation setting
  40. PGWIDTH="" # Input PDF Page Width
  41. PGHEIGHT="" # Input PDF Page Height
  42. RESIZE_WIDTH="" # Resized PDF Page Width
  43. RESIZE_HEIGHT="" # Resized PDF Page Height
  44. ########################## EXIT FLAGS ##########################
  45. EXIT_SUCCESS=0
  46. EXIT_ERROR=1
  47. EXIT_INVALID_PAGE_SIZE_DETECTED=10
  48. EXIT_FILE_NOT_FOUND=20
  49. EXIT_INPUT_NOT_PDF=21
  50. EXIT_INVALID_OPTION=22
  51. EXIT_NO_INPUT_FILE=23
  52. EXIT_INVALID_SCALE=24
  53. EXIT_MISSING_DEPENDENCY=25
  54. EXIT_IMAGEMAGIK_NOT_FOUND=26
  55. EXIT_MAC_MDLS_NOT_FOUND=27
  56. EXIT_PDFINFO_NOT_FOUND=28
  57. EXIT_TEMP_FILE_EXISTS=40
  58. EXIT_INVALID_PAPER_SIZE=50
  59. ############################# MAIN #############################
  60. # Main function called at the end
  61. main() {
  62. printPDFSizes # may exit here
  63. vprint " Input File: $INFILEPDF"
  64. vprint " Output File: $OUTFILEPDF"
  65. getPageSize
  66. vPrintPageSizes ' Source'
  67. local finalRet=$EXIT_ERROR
  68. local tempFile=""
  69. local tempSuffix="$RANDOM$RANDOM""_TEMP_$RANDOM$RANDOM.pdf"
  70. if isMixedMode; then
  71. outputFile="$OUTFILEPDF" # backup outFile name
  72. tempFile="${OUTFILEPDF%.pdf}.$tempSuffix" # set a temp file name
  73. if isFile "$tempFile"; then
  74. printError $'Error! Temporary file name already exists!\n'"File: $tempFile"$'\nAborting execution to avoid overwriting the file.\nPlease Try again...'
  75. exit $EXIT_TEMP_FILE_EXISTS
  76. fi
  77. OUTFILEPDF="$tempFile" # set output to tmp file
  78. pageResize # resize to tmp file
  79. finalRet=$?
  80. INFILEPDF="$tempFile" # get tmp file as input
  81. OUTFILEPDF="$outputFile" # reset final target
  82. PGWIDTH=$RESIZE_WIDTH # we already know the new page size
  83. PGHEIGHT=$RESIZE_HEIGHT # from the last command (Resize)
  84. vPrintPageSizes ' New'
  85. vPrintScaleFactor
  86. pageScale # scale the resized pdf
  87. finalRet=$(($finalRet+$?))
  88. # remove tmp file
  89. rm "$tempFile" >/dev/null 2>&1 || printError "Error when removing temporary file: $tempFile"
  90. elif isResizeMode; then
  91. vPrintScaleFactor "Disabled (resize only)"
  92. pageResize
  93. finalRet=$?
  94. else
  95. local scaleMode=""
  96. isManualScaledMode && scaleMode='(manual)' || scaleMode='(auto)'
  97. vPrintScaleFactor "$SCALE $scaleMode"
  98. pageScale
  99. finalRet=$?
  100. fi
  101. if [[ $finalRet -eq $EXIT_SUCCESS ]]; then
  102. vprint " Final Status: File created successfully"
  103. else
  104. vprint " Final Status: Errors were detected. Exit status: $finalRet"
  105. fi
  106. return $finalRet
  107. }
  108. # Prints PDF Info and exits with $EXIT_SUCCESS, but only if $JUST_IDENTIFY is $TRUE
  109. printPDFSizes() {
  110. if [[ $JUST_IDENTIFY -eq $TRUE ]]; then
  111. VERBOSE=0
  112. printVersion 3 " - Paper Sizes"
  113. getPageSize || initError "Could not get pagesize!"
  114. local paperType="$(getGSPaperName $PGWIDTH $PGHEIGHT)"
  115. isEmpty "$paperType" && paperType="Custom Paper Size"
  116. printf '%s\n' "------------+-----------------------------"
  117. printf " File | %s\n" "$(basename "$INFILEPDF")"
  118. printf " Paper Type | %s\n" "$paperType"
  119. printf '%s\n' "------------+-----------------------------"
  120. printf '%s\n' " | WIDTH x HEIGHT"
  121. printf " Points | %+8s x %-8s\n" "$PGWIDTH" "$PGHEIGHT"
  122. printf " Milimeters | %+8s x %-8s\n" "$(pointsToMilimeters $PGWIDTH)" "$(pointsToMilimeters $PGHEIGHT)"
  123. printf " Inches | %+8s x %-8s\n" "$(pointsToInches $PGWIDTH)" "$(pointsToInches $PGHEIGHT)"
  124. exit $EXIT_SUCCESS
  125. fi
  126. return $EXIT_SUCCESS
  127. }
  128. ###################### GHOSTSCRIPT CALLS #######################
  129. # Runs the ghostscript scaling script
  130. pageScale() {
  131. # Compute translation factors (to center page).
  132. XTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGWIDTH" | "$BCBIN")
  133. YTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGHEIGHT" | "$BCBIN")
  134. vprint " Translation X: $XTRANS"
  135. vprint " Translation Y: $YTRANS"
  136. local increase=$(echo "scale=0; (($SCALE - 1) * 100)/1" | "$BCBIN")
  137. vprint " Run Scaling: $increase %"
  138. # Scale page
  139. "$GSBIN" \
  140. -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \
  141. -dCompatibilityLevel="1.5" -dPDFSETTINGS="/printer" \
  142. -dColorConversionStrategy=/LeaveColorUnchanged \
  143. -dSubsetFonts=true -dEmbedAllFonts=true \
  144. -dDEVICEWIDTHPOINTS=$PGWIDTH -dDEVICEHEIGHTPOINTS=$PGHEIGHT \
  145. -sOutputFile="$OUTFILEPDF" \
  146. -c "<</BeginPage{$SCALE $SCALE scale $XTRANS $YTRANS translate}>> setpagedevice" \
  147. -f "$INFILEPDF"
  148. return $?
  149. }
  150. # Runs the ghostscript paper resize script
  151. pageResize() {
  152. # Get new paper sizes if not custom paper
  153. isNotCustomPaper && getGSPaperSize "$RESIZE_PAPER_TYPE"
  154. vprint " Auto Rotate: $(basename $AUTO_ROTATION)"
  155. # Flip detect
  156. local tmpInverter=""
  157. if [[ $FLIP_DETECTION -eq $TRUE || $FLIP_FORCE -eq $TRUE ]]; then
  158. if [[ $PGWIDTH -gt $PGHEIGHT && $RESIZE_WIDTH -lt $RESIZE_HEIGHT ]] || [[ $FLIP_FORCE -eq $TRUE ]]; then
  159. [[ $FLIP_FORCE -eq $TRUE ]] && vprint " Flip Detect: Forced Mode!" || vprint " Flip Detect: Wrong orientation detected!"
  160. vprint " Inverting Width <-> Height"
  161. tmpInverter=$RESIZE_HEIGHT
  162. RESIZE_HEIGHT=$RESIZE_WIDTH
  163. RESIZE_WIDTH=$tmpInverter
  164. else
  165. vprint " Flip Detect: No change needed"
  166. fi
  167. else
  168. vprint " Flip Detect: Disabled"
  169. fi
  170. vprint " Run Resizing: $(uppercase "$RESIZE_PAPER_TYPE") ( "$RESIZE_WIDTH" x "$RESIZE_HEIGHT" ) pts"
  171. # Change page size
  172. "$GSBIN" \
  173. -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \
  174. -dCompatibilityLevel="1.5" -dPDFSETTINGS="/printer" \
  175. -dColorConversionStrategy=/LeaveColorUnchanged \
  176. -dSubsetFonts=true -dEmbedAllFonts=true \
  177. -dDEVICEWIDTHPOINTS=$RESIZE_WIDTH -dDEVICEHEIGHTPOINTS=$RESIZE_HEIGHT \
  178. -dAutoRotatePages=$AUTO_ROTATION \
  179. -dFIXEDMEDIA -dPDFFitPage \
  180. -sOutputFile="$OUTFILEPDF" \
  181. -f "$INFILEPDF"
  182. return $?
  183. }
  184. ########################## INITIALIZERS #########################
  185. # Loads external dependencies and checks for errors
  186. initDeps() {
  187. GREPBIN="$(which grep 2>/dev/null)"
  188. GSBIN="$(which gs 2>/dev/null)"
  189. BCBIN="$(which bc 2>/dev/null)"
  190. IDBIN=$(which identify 2>/dev/null)
  191. MDLSBIN="$(which mdls 2>/dev/null)"
  192. PDFINFOBIN="$(which pdfinfo 2>/dev/null)"
  193. vprint "Checking for basename, grep, ghostscript and bcmath"
  194. basename "" >/dev/null 2>&1 || printDependency 'basename'
  195. notIsAvailable "$GREPBIN" && printDependency 'grep'
  196. notIsAvailable "$GSBIN" && printDependency 'ghostscript'
  197. notIsAvailable "$BCBIN" && printDependency 'bc'
  198. return $TRUE
  199. }
  200. # Checks for dependencies errors, run after getting options
  201. checkDeps() {
  202. if [[ $MODE = "IDENTIFY" ]]; then
  203. vprint "Checking for imagemagick's identify"
  204. if notIsAvailable "$IDBIN"; then printDependency 'imagemagick'; fi
  205. fi
  206. if [[ $MODE = "PDFINFO" ]]; then
  207. vprint "Checking for pdfinfo"
  208. if notIsAvailable "$PDFINFOBIN"; then printDependency 'pdfinfo'; fi
  209. fi
  210. if [[ $MODE = "MDLS" ]]; then
  211. vprint "Checking for MacOS mdls"
  212. if notIsAvailable "$MDLSBIN"; then
  213. initError 'mdls executable was not found! Is this even MacOS?' $EXIT_MAC_MDLS_NOT_FOUND 'nobanner'
  214. fi
  215. fi
  216. return $TRUE
  217. }
  218. ######################### CLI OPTIONS ##########################
  219. # Parse options
  220. getOptions() {
  221. while getopts ":vhVis:m:r:pf:a:" o; do
  222. case "${o}" in
  223. v)
  224. ((VERBOSE++))
  225. ;;
  226. h)
  227. printHelp
  228. exit $EXIT_SUCCESS
  229. ;;
  230. V)
  231. printVersion 3
  232. exit $EXIT_SUCCESS
  233. ;;
  234. i)
  235. JUST_IDENTIFY=$TRUE
  236. ;;
  237. s)
  238. parseScale ${OPTARG}
  239. ;;
  240. m)
  241. parseMode ${OPTARG}
  242. ;;
  243. r)
  244. parsePaperResize ${OPTARG}
  245. ;;
  246. p)
  247. printPaperInfo
  248. exit $EXIT_SUCCESS
  249. ;;
  250. f)
  251. parseFlipDetectionMode ${OPTARG}
  252. ;;
  253. a)
  254. parseAutoRotationMode ${OPTARG}
  255. ;;
  256. *)
  257. initError "Invalid Option: -$OPTARG" $EXIT_INVALID_OPTION
  258. ;;
  259. esac
  260. done
  261. shift $((OPTIND-1))
  262. if [[ $JUST_IDENTIFY -eq $TRUE ]]; then
  263. VERBOSE=0
  264. fi
  265. # Validate input PDF file
  266. INFILEPDF="$1"
  267. isEmpty "$INFILEPDF" && initError "Input file is empty!" $EXIT_NO_INPUT_FILE
  268. isPDF "$INFILEPDF" || initError "Input file is not a PDF file: $INFILEPDF" $EXIT_INPUT_NOT_PDF
  269. isFile "$INFILEPDF" || initError "Input file not found: $INFILEPDF" $EXIT_FILE_NOT_FOUND
  270. printVersion 1 'verbose'
  271. checkDeps
  272. if isMixedMode; then
  273. vprint " Mixed Tasks: Resize & Scale"
  274. isEmpty "$2" && OUTFILEPDF="${INFILEPDF%.pdf}.$(uppercase $RESIZE_PAPER_TYPE).SCALED.pdf"
  275. elif isResizeMode; then
  276. vprint " Single Task: Resize PDF Paper"
  277. isEmpty "$2" && OUTFILEPDF="${INFILEPDF%.pdf}.$(uppercase $RESIZE_PAPER_TYPE).pdf"
  278. else
  279. vprint " Single Task: Scale PDF Contents"
  280. isEmpty "$2" && OUTFILEPDF="${INFILEPDF%.pdf}.SCALED.pdf"
  281. fi
  282. isNotEmpty "$2" && OUTFILEPDF="${2%.pdf}.pdf"
  283. }
  284. # Parses and validates the scaling factor
  285. parseScale() {
  286. AUTOMATIC_SCALING=$FALSE
  287. if ! isFloatBiggerThanZero "$1"; then
  288. printError "Invalid factor: $1"
  289. printError "The factor must be a floating point number greater than 0"
  290. printError "Example: for 80% use 0.8"
  291. exit $EXIT_INVALID_SCALE
  292. fi
  293. SCALE="$1"
  294. }
  295. # Parse a forced mode of operation
  296. parseMode() {
  297. local param="$(lowercase $1)"
  298. case "${param}" in
  299. c|catgrep|'cat+grep'|grep|g)
  300. ADAPTIVEMODE=$FALSE
  301. MODE="CATGREP"
  302. return $TRUE
  303. ;;
  304. i|imagemagick|identify)
  305. ADAPTIVEMODE=$FALSE
  306. MODE="IDENTIFY"
  307. return $TRUE
  308. ;;
  309. m|mdls|quartz|mac)
  310. ADAPTIVEMODE=$FALSE
  311. MODE="MDLS"
  312. return $TRUE
  313. ;;
  314. p|pdfinfo)
  315. ADAPTIVEMODE=$FALSE
  316. MODE="PDFINFO"
  317. return $TRUE
  318. ;;
  319. *)
  320. ADAPTIVEMODE=$TRUE
  321. MODE=""
  322. if [[ "$param" != 'a' && "$param" != 'auto' && "$param" != 'automatic' && "$param" != 'adaptive' ]]; then
  323. printError "Error! Invalid PDF Size Detection Mode: \"$1\", using adaptive mode!"
  324. return $FALSE
  325. fi
  326. return $TRUE
  327. ;;
  328. esac
  329. return $FALSE
  330. }
  331. # Parses and validates the scaling factor
  332. parseFlipDetectionMode() {
  333. local param="$(lowercase $1)"
  334. case "${param}" in
  335. d|disable)
  336. FLIP_DETECTION=$FALSE
  337. FLIP_FORCE=$FALSE
  338. ;;
  339. f|force)
  340. FLIP_DETECTION=$FALSE
  341. FLIP_FORCE=$TRUE
  342. ;;
  343. *)
  344. [[ "$param" != 'a' && "$param" != 'auto' ]] && printError "Error! Invalid Flip Detection Mode: \"$1\", using automatic mode!"
  345. FLIP_DETECTION=$TRUE
  346. FLIP_FORCE=$FALSE
  347. ;;
  348. esac
  349. }
  350. # Parses and validates the scaling factor
  351. parseAutoRotationMode() {
  352. local param="$(lowercase $1)"
  353. case "${param}" in
  354. n|none)
  355. AUTO_ROTATION='/None'
  356. ;;
  357. a|all)
  358. AUTO_ROTATION='/All'
  359. ;;
  360. p|pagebypage|auto)
  361. AUTO_ROTATION='/PageByPage'
  362. ;;
  363. *)
  364. printError "Error! Invalid Auto Rotation Mode: $param, using default: $(basename $AUTO_ROTATION)"
  365. ;;
  366. esac
  367. }
  368. ################### PDF PAGE SIZE DETECTION ####################
  369. ################################################################
  370. # Detects operation mode and also runs the adaptive mode
  371. # PAGESIZE LOGIC
  372. # 1- Try to get Mediabox with GREP
  373. # 2- MacOS => try to use mdls
  374. # 3- Try to use pdfinfo
  375. # 4- Try to use identify (imagemagick)
  376. # 5- Fail
  377. ################################################################
  378. getPageSize() {
  379. if isNotAdaptiveMode; then
  380. vprint " Get Page Size: Adaptive Disabled"
  381. if [[ $MODE = "CATGREP" ]]; then
  382. vprint " Method: Grep"
  383. getPageSizeCatGrep
  384. elif [[ $MODE = "MDLS" ]]; then
  385. vprint " Method: Mac Quartz mdls"
  386. getPageSizeMdls
  387. elif [[ $MODE = "PDFINFO" ]]; then
  388. vprint " Method: PDFInfo"
  389. getPageSizePdfInfo
  390. elif [[ $MODE = "IDENTIFY" ]]; then
  391. vprint " Method: ImageMagick's Identify"
  392. getPageSizeImagemagick
  393. else
  394. printError "Error! Invalid Mode: $MODE"
  395. printError "Aborting execution..."
  396. exit $EXIT_INVALID_OPTION
  397. fi
  398. return $TRUE
  399. fi
  400. vprint " Get Page Size: Adaptive Enabled"
  401. vprint " Method: Grep"
  402. getPageSizeCatGrep
  403. if pageSizeIsInvalid && [[ $OSNAME = "Darwin" ]]; then
  404. vprint " Failed"
  405. vprint " Method: Mac Quartz mdls"
  406. getPageSizeMdls
  407. fi
  408. if pageSizeIsInvalid; then
  409. vprint " Failed"
  410. vprint " Method: PDFInfo"
  411. getPageSizePdfInfo
  412. fi
  413. if pageSizeIsInvalid; then
  414. vprint " Failed"
  415. vprint " Method: ImageMagick's Identify"
  416. getPageSizeImagemagick
  417. fi
  418. if pageSizeIsInvalid; then
  419. vprint " Failed"
  420. printError "Error when detecting PDF paper size!"
  421. printError "All methods of detection failed"
  422. printError "You may want to install pdfinfo or imagemagick"
  423. exit $EXIT_INVALID_PAGE_SIZE_DETECTED
  424. fi
  425. return $TRUE
  426. }
  427. # Gets page size using imagemagick's identify
  428. getPageSizeImagemagick() {
  429. # Sanity and Adaptive together
  430. if notIsFile "$IDBIN" && isNotAdaptiveMode; then
  431. notAdaptiveFailed "Make sure you installed ImageMagick and have identify on your \$PATH" "ImageMagick's Identify"
  432. elif notIsFile "$IDBIN" && isAdaptiveMode; then
  433. return $FALSE
  434. fi
  435. # get data from image magick
  436. local identify="$("$IDBIN" -format '%[fx:w] %[fx:h]BREAKME' "$INFILEPDF" 2>/dev/null)"
  437. if isEmpty "$identify" && isNotAdaptiveMode; then
  438. notAdaptiveFailed "ImageMagicks's Identify returned an empty string!"
  439. elif isEmpty "$identify" && isAdaptiveMode; then
  440. return $FALSE
  441. fi
  442. identify="${identify%%BREAKME*}" # get page size only for 1st page
  443. identify=($identify) # make it an array
  444. PGWIDTH=$(printf '%.0f' "${identify[0]}") # assign
  445. PGHEIGHT=$(printf '%.0f' "${identify[1]}") # assign
  446. return $TRUE
  447. }
  448. # Gets page size using Mac Quarts mdls
  449. getPageSizeMdls() {
  450. # Sanity and Adaptive together
  451. if notIsFile "$MDLSBIN" && isNotAdaptiveMode; then
  452. notAdaptiveFailed "Are you even trying this on a Mac?" "Mac Quartz mdls"
  453. elif notIsFile "$MDLSBIN" && isAdaptiveMode; then
  454. return $FALSE
  455. fi
  456. local identify="$("$MDLSBIN" -mdls -name kMDItemPageHeight -name kMDItemPageWidth "$INFILEPDF" 2>/dev/null)"
  457. if isEmpty "$identify" && isNotAdaptiveMode; then
  458. notAdaptiveFailed "Mac Quartz mdls returned an empty string!"
  459. elif isEmpty "$identify" && isAdaptiveMode; then
  460. return $FALSE
  461. fi
  462. identify=${identify//$'\t'/ } # change tab to space
  463. identify=($identify) # make it an array
  464. if [[ "${identify[5]}" = "(null)" || "${identify[2]}" = "(null)" ]] && isNotAdaptiveMode; then
  465. notAdaptiveFailed "There was no metadata to read from the file! Is Spotlight OFF?"
  466. elif [[ "${identify[5]}" = "(null)" || "${identify[2]}" = "(null)" ]] && isAdaptiveMode; then
  467. return $FALSE
  468. fi
  469. PGWIDTH=$(printf '%.0f' "${identify[5]}") # assign
  470. PGHEIGHT=$(printf '%.0f' "${identify[2]}") # assign
  471. return $TRUE
  472. }
  473. # Gets page size using Linux PdfInfo
  474. getPageSizePdfInfo() {
  475. # Sanity and Adaptive together
  476. if notIsFile "$PDFINFOBIN" && isNotAdaptiveMode; then
  477. notAdaptiveFailed "Do you have pdfinfo installed and available on your \$PATH?" "Linux pdfinfo"
  478. elif notIsFile "$PDFINFOBIN" && isAdaptiveMode; then
  479. return $FALSE
  480. fi
  481. # get data from image magick
  482. local identify="$("$PDFINFOBIN" "$INFILEPDF" 2>/dev/null | "$GREPBIN" -i 'Page size:' )"
  483. if isEmpty "$identify" && isNotAdaptiveMode; then
  484. notAdaptiveFailed "Linux PdfInfo returned an empty string!"
  485. elif isEmpty "$identify" && isAdaptiveMode; then
  486. return $FALSE
  487. fi
  488. identify="${identify##*Page size:}" # remove stuff
  489. identify=($identify) # make it an array
  490. PGWIDTH=$(printf '%.0f' "${identify[0]}") # assign
  491. PGHEIGHT=$(printf '%.0f' "${identify[2]}") # assign
  492. return $TRUE
  493. }
  494. # Gets page size using cat and grep
  495. getPageSizeCatGrep() {
  496. # get MediaBox info from PDF file using grep, these are all possible
  497. # /MediaBox [0 0 595 841]
  498. # /MediaBox [ 0 0 595.28 841.89]
  499. # /MediaBox[ 0 0 595.28 841.89 ]
  500. # Get MediaBox data if possible
  501. local mediaBox="$("$GREPBIN" -a -e '/MediaBox' -m 1 "$INFILEPDF" 2>/dev/null)"
  502. mediaBox="${mediaBox##*/MediaBox}"
  503. # No page size data available
  504. if isEmpty "$mediaBox" && isNotAdaptiveMode; then
  505. notAdaptiveFailed "There is no MediaBox in the pdf document!"
  506. elif isEmpty "$mediaBox" && isAdaptiveMode; then
  507. return $FALSE
  508. fi
  509. # remove chars [ and ]
  510. mediaBox="${mediaBox//[}"
  511. mediaBox="${mediaBox//]}"
  512. mediaBox=($mediaBox) # make it an array
  513. mbCount=${#mediaBox[@]} # array size
  514. # sanity
  515. if [[ $mbCount -lt 4 ]]; then
  516. printError "Error when reading the page size!"
  517. printError "The page size information is invalid!"
  518. exit $EXIT_INVALID_PAGE_SIZE_DETECTED
  519. fi
  520. # we are done
  521. PGWIDTH=$(printf '%.0f' "${mediaBox[2]}") # Get Round Width
  522. PGHEIGHT=$(printf '%.0f' "${mediaBox[3]}") # Get Round Height
  523. return $TRUE
  524. }
  525. # Prints error message and exits execution
  526. notAdaptiveFailed() {
  527. local errProgram="$2"
  528. local errStr="$1"
  529. if isEmpty "$2"; then
  530. printError "Error when reading input file!"
  531. printError "Could not determine the page size!"
  532. else
  533. printError "Error! $2 was not found!"
  534. fi
  535. isNotEmpty "$errStr" && printError "$errStr"
  536. printError "Aborting! You may want to try the adaptive mode."
  537. exit $EXIT_INVALID_PAGE_SIZE_DETECTED
  538. }
  539. # Verbose print of the Width and Height (Source or New) to screen
  540. vPrintPageSizes() {
  541. vprint " $1 Width: $PGWIDTH postscript-points"
  542. vprint "$1 Height: $PGHEIGHT postscript-points"
  543. }
  544. #################### GHOSTSCRIPT PAPER INFO ####################
  545. # Loads GS paper info to memory
  546. getPaperInfo() {
  547. # name inchesW inchesH mmW mmH pointsW pointsH
  548. sizesUS="\
  549. 11x17 11.0 17.0 279 432 792 1224
  550. ledger 17.0 11.0 432 279 1224 792
  551. legal 8.5 14.0 216 356 612 1008
  552. letter 8.5 11.0 216 279 612 792
  553. lettersmall 8.5 11.0 216 279 612 792
  554. archE 36.0 48.0 914 1219 2592 3456
  555. archD 24.0 36.0 610 914 1728 2592
  556. archC 18.0 24.0 457 610 1296 1728
  557. archB 12.0 18.0 305 457 864 1296
  558. archA 9.0 12.0 229 305 648 864"
  559. sizesISO="\
  560. a0 33.1 46.8 841 1189 2384 3370
  561. a1 23.4 33.1 594 841 1684 2384
  562. a2 16.5 23.4 420 594 1191 1684
  563. a3 11.7 16.5 297 420 842 1191
  564. a4 8.3 11.7 210 297 595 842
  565. a4small 8.3 11.7 210 297 595 842
  566. a5 5.8 8.3 148 210 420 595
  567. a6 4.1 5.8 105 148 297 420
  568. a7 2.9 4.1 74 105 210 297
  569. a8 2.1 2.9 52 74 148 210
  570. a9 1.5 2.1 37 52 105 148
  571. a10 1.0 1.5 26 37 73 105
  572. isob0 39.4 55.7 1000 1414 2835 4008
  573. isob1 27.8 39.4 707 1000 2004 2835
  574. isob2 19.7 27.8 500 707 1417 2004
  575. isob3 13.9 19.7 353 500 1001 1417
  576. isob4 9.8 13.9 250 353 709 1001
  577. isob5 6.9 9.8 176 250 499 709
  578. isob6 4.9 6.9 125 176 354 499
  579. c0 36.1 51.1 917 1297 2599 3677
  580. c1 25.5 36.1 648 917 1837 2599
  581. c2 18.0 25.5 458 648 1298 1837
  582. c3 12.8 18.0 324 458 918 1298
  583. c4 9.0 12.8 229 324 649 918
  584. c5 6.4 9.0 162 229 459 649
  585. c6 4.5 6.4 114 162 323 459"
  586. sizesJIS="\
  587. jisb0 NA NA 1030 1456 2920 4127
  588. jisb1 NA NA 728 1030 2064 2920
  589. jisb2 NA NA 515 728 1460 2064
  590. jisb3 NA NA 364 515 1032 1460
  591. jisb4 NA NA 257 364 729 1032
  592. jisb5 NA NA 182 257 516 729
  593. jisb6 NA NA 128 182 363 516"
  594. sizesOther="\
  595. flsa 8.5 13.0 216 330 612 936
  596. flse 8.5 13.0 216 330 612 936
  597. halfletter 5.5 8.5 140 216 396 612
  598. hagaki 3.9 5.8 100 148 283 420"
  599. sizesAll="\
  600. $sizesUS
  601. $sizesISO
  602. $sizesJIS
  603. $sizesOther"
  604. }
  605. # Gets a paper size in points and sets it to RESIZE_WIDTH and RESIZE_HEIGHT
  606. getGSPaperSize() {
  607. isEmpty "$sizesall" && getPaperInfo
  608. while read l; do
  609. local cols=($l)
  610. if [[ "$1" == ${cols[0]} ]]; then
  611. RESIZE_WIDTH=${cols[5]}
  612. RESIZE_HEIGHT=${cols[6]}
  613. return $TRUE
  614. fi
  615. done <<< "$sizesAll"
  616. }
  617. # Gets a paper size in points and sets it to RESIZE_WIDTH and RESIZE_HEIGHT
  618. getGSPaperName() {
  619. local w="$(printf "%.0f" $1)"
  620. local h="$(printf "%.0f" $2)"
  621. isEmpty "$sizesall" && getPaperInfo
  622. # Because US Standard has inverted sizes, I need to scan 2 times
  623. # instead of just testing if width is bigger than height
  624. while read l; do
  625. local cols=($l)
  626. if [[ "$w" == ${cols[5]} && "$h" == ${cols[6]} ]]; then
  627. printf "%s Portrait" $(uppercase ${cols[0]})
  628. return $TRUE
  629. fi
  630. done <<< "$sizesAll"
  631. while read l; do
  632. local cols=($l)
  633. if [[ "$w" == ${cols[6]} && "$h" == ${cols[5]} ]]; then
  634. printf "%s Landscape" $(uppercase ${cols[0]})
  635. return $TRUE
  636. fi
  637. done <<< "$sizesAll"
  638. return $FALSE
  639. }
  640. # Loads an array with paper names to memory
  641. getPaperNames() {
  642. 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 \
  643. 11x17 ledger legal letter lettersmall archE archD archC archB archA \
  644. jisb0 jisb1 jisb2 jisb3 jisb4 jisb5 jisb6 \
  645. flsa flse halfletter hagaki)
  646. }
  647. # Prints uppercase paper names to screen (used in help)
  648. printPaperNames() {
  649. isEmpty "$paperNames" && getPaperNames
  650. for i in "${!paperNames[@]}"; do
  651. [[ $i -eq 0 ]] && echo -n -e ' '
  652. [[ $i -ne 0 && $((i % 5)) -eq 0 ]] && echo -n -e $'\n '
  653. ppN="$(uppercase ${paperNames[i]})"
  654. printf "%-14s" "$ppN"
  655. done
  656. echo ""
  657. }
  658. # Returns $TRUE if $! is a valid paper name, $FALSE otherwise
  659. isPaperName() {
  660. isEmpty "$1" && return $FALSE
  661. isEmpty "$paperNames" && getPaperNames
  662. for i in "${paperNames[@]}"; do
  663. [[ "$i" = "$1" ]] && return $TRUE
  664. done
  665. return $FALSE
  666. }
  667. # Prints all tables with ghostscript paper information
  668. printPaperInfo() {
  669. printVersion
  670. echo $'\n'"Valid Ghostscript Paper Sizes accepted"$'\n'
  671. getPaperInfo
  672. printPaperTable "ISO STANDARD" "$sizesISO"; echo
  673. printPaperTable "US STANDARD" "$sizesUS"; echo
  674. printPaperTable "JIS STANDARD *Aproximated Points" "$sizesJIS"; echo
  675. printPaperTable "OTHERS" "$sizesOther"; echo
  676. }
  677. # GS paper table helper, prints a full line
  678. printTableLine() {
  679. echo '+-----------------------------------------------------------------+'
  680. }
  681. # GS paper table helper, prints a line with dividers
  682. printTableDivider() {
  683. echo '+-----------------+-------+-------+-------+-------+-------+-------+'
  684. }
  685. # GS paper table helper, prints a table header
  686. printTableHeader() {
  687. echo '| Name | inchW | inchH | mm W | mm H | pts W | pts H |'
  688. }
  689. # GS paper table helper, prints a table title
  690. printTableTitle() {
  691. printf "| %-64s%s\n" "$1" '|'
  692. }
  693. # GS paper table printer, prints a table for a paper variable
  694. printPaperTable() {
  695. printTableLine
  696. printTableTitle "$1"
  697. printTableLine
  698. printTableHeader
  699. printTableDivider
  700. while read l; do
  701. local cols=($l)
  702. printf "| %-15s | %+5s | %+5s | %+5s | %+5s | %+5s | %+5s |\n" ${cols[*]};
  703. done <<< "$2"
  704. printTableDivider
  705. }
  706. # Validades the a paper resize CLI option and sets the paper to $RESIZE_PAPER_TYPE
  707. parsePaperResize() {
  708. isEmpty "$1" && initError 'Invalid Paper Type: (empty)' $EXIT_INVALID_PAPER_SIZE
  709. local lowercasePaper="$(lowercase $1)"
  710. if [[ "$1" = 'custom' ]]; then
  711. if isNotValidMeasure "$2" || ! isFloatBiggerThanZero "$3" || ! isFloatBiggerThanZero "$4"; then
  712. initError "Invalid Custom Paper Definition!"$'\n'"Use: -r 'custom <measurement> <width> <height>'"$'\n'"Measurements: mm, in, pts" $EXIT_INVALID_OPTION
  713. fi
  714. RESIZE_PAPER_TYPE="custom"
  715. CUSTOM_RESIZE_PAPER=$TRUE
  716. if isMilimeter "$2"; then
  717. RESIZE_WIDTH="$(milimetersToPoints "$3")"
  718. RESIZE_HEIGHT="$(milimetersToPoints "$4")"
  719. elif isInch "$2"; then
  720. RESIZE_WIDTH="$(inchesToPoints "$3")"
  721. RESIZE_HEIGHT="$(inchesToPoints "$4")"
  722. elif isPoint "$2"; then
  723. RESIZE_WIDTH="$3"
  724. RESIZE_HEIGHT="$4"
  725. else
  726. initError "Invalid Custom Paper Definition!"$'\n'"Use: -r 'custom <measurement> <width> <height>'"$'\n'"Measurements: mm, in, pts" $EXIT_INVALID_OPTION
  727. fi
  728. else
  729. isPaperName "$lowercasePaper" || initError "Invalid Paper Type: $1" $EXIT_INVALID_PAPER_SIZE
  730. RESIZE_PAPER_TYPE="$lowercasePaper"
  731. fi
  732. }
  733. # Returns $TRUE if $1 is a valid measurement for a custom paper, $FALSE otherwise
  734. isNotValidMeasure() {
  735. isMilimeter "$1" || isInch "$1" || isPoint "$1" && return $FALSE
  736. return $TRUE
  737. }
  738. # Returns $TRUE if $1 is a valid milimeter string, $FALSE otherwise
  739. isMilimeter() {
  740. [[ "$1" = 'mm' || "$1" = 'milimeters' || "$1" = 'milimeter' ]] && return $TRUE
  741. return $FALSE
  742. }
  743. # Returns $TRUE if $1 is a valid inch string, $FALSE otherwise
  744. isInch() {
  745. [[ "$1" = 'in' || "$1" = 'inch' || "$1" = 'inches' ]] && return $TRUE
  746. return $FALSE
  747. }
  748. # Returns $TRUE if $1 is a valid point string, $FALSE otherwise
  749. isPoint() {
  750. [[ "$1" = 'pt' || "$1" = 'pts' || "$1" = 'point' || "$1" = 'points' ]] && return $TRUE
  751. return $FALSE
  752. }
  753. # Returns $TRUE if a custom paper is being used, $FALSE otherwise
  754. isCustomPaper() {
  755. return $CUSTOM_RESIZE_PAPER
  756. }
  757. isNotCustomPaper() {
  758. isCustomPaper && return $FALSE
  759. return $TRUE
  760. }
  761. # Returns $TRUE if the scale was set manually, $FALSE if we are using automatic scaling
  762. isManualScaledMode() {
  763. [[ $AUTOMATIC_SCALING -eq $TRUE ]] && return $FALSE
  764. return $TRUE
  765. }
  766. # Returns true if we are resizing a paper (ignores scaling), false otherwise
  767. isResizeMode() {
  768. isEmpty $RESIZE_PAPER_TYPE && return $FALSE
  769. return $TRUE
  770. }
  771. # Returns true if we are resizing a paper and the scale was manually set
  772. isMixedMode() {
  773. isResizeMode && isManualScaledMode && return $TRUE
  774. return $FALSE
  775. }
  776. # Prints the lowercase char value for $1
  777. lowercaseChar() {
  778. case "$1" in
  779. [A-Z])
  780. n=$(printf "%d" "'$1")
  781. n=$((n+32))
  782. printf \\$(printf "%o" "$n")
  783. ;;
  784. *)
  785. printf "%s" "$1"
  786. ;;
  787. esac
  788. }
  789. # Prints the lowercase version of a string
  790. lowercase() {
  791. word="$@"
  792. for((i=0;i<${#word};i++))
  793. do
  794. ch="${word:$i:1}"
  795. lowercaseChar "$ch"
  796. done
  797. }
  798. # Prints the uppercase char value for $1
  799. uppercaseChar(){
  800. case "$1" in
  801. [a-z])
  802. n=$(printf "%d" "'$1")
  803. n=$((n-32))
  804. printf \\$(printf "%o" "$n")
  805. ;;
  806. *)
  807. printf "%s" "$1"
  808. ;;
  809. esac
  810. }
  811. # Prints the uppercase version of a string
  812. uppercase() {
  813. word="$@"
  814. for((i=0;i<${#word};i++))
  815. do
  816. ch="${word:$i:1}"
  817. uppercaseChar "$ch"
  818. done
  819. }
  820. # Prints the postscript points rounded equivalent from $1 mm
  821. milimetersToPoints() {
  822. local pts=$(echo "scale=8; $1 * 72 / 25.4" | "$BCBIN")
  823. printf '%.0f' "$pts" # Print rounded conversion
  824. }
  825. # Prints the postscript points rounded equivalent from $1 inches
  826. inchesToPoints() {
  827. local pts=$(echo "scale=8; $1 * 72" | "$BCBIN")
  828. printf '%.0f' "$pts" # Print rounded conversion
  829. }
  830. # Prints the mm equivalent from $1 postscript points
  831. pointsToMilimeters() {
  832. local pts=$(echo "scale=8; $1 / 72 * 25.4" | "$BCBIN")
  833. printf '%.0f' "$pts" # Print rounded conversion
  834. }
  835. # Prints the inches equivalent from $1 postscript points
  836. pointsToInches() {
  837. local pts=$(echo "scale=8; $1 / 72" | "$BCBIN")
  838. printf '%.1f' "$pts" # Print rounded conversion
  839. }
  840. ########################## VALIDATORS ##########################
  841. # Returns $TRUE if $PGWIDTH OR $PGWIDTH are empty or NOT an Integer, $FALSE otherwise
  842. pageSizeIsInvalid() {
  843. if isNotAnInteger "$PGWIDTH" || isNotAnInteger "$PGHEIGHT"; then
  844. return $TRUE
  845. fi
  846. return $FALSE
  847. }
  848. # Return $TRUE if adaptive mode is enabled, $FALSE otherwise
  849. isAdaptiveMode() {
  850. return $ADAPTIVEMODE
  851. }
  852. # Return $TRUE if adaptive mode is disabled, $FALSE otherwise
  853. isNotAdaptiveMode() {
  854. isAdaptiveMode && return $FALSE
  855. return $TRUE
  856. }
  857. # Return $TRUE if $1 is empty, $FALSE otherwise
  858. isEmpty() {
  859. [[ -z "$1" ]] && return $TRUE
  860. return $FALSE
  861. }
  862. # Return $TRUE if $1 is NOT empty, $FALSE otherwise
  863. isNotEmpty() {
  864. [[ -z "$1" ]] && return $FALSE
  865. return $TRUE
  866. }
  867. # Returns $TRUE if $1 is an integer, $FALSE otherwise
  868. isAnInteger() {
  869. case $1 in
  870. ''|*[!0-9]*) return $FALSE ;;
  871. *) return $TRUE ;;
  872. esac
  873. }
  874. # Returns $TRUE if $1 is NOT an integer, $FALSE otherwise
  875. isNotAnInteger() {
  876. case $1 in
  877. ''|*[!0-9]*) return $TRUE ;;
  878. *) return $FALSE ;;
  879. esac
  880. }
  881. # Returns $TRUE if $1 is a floating point number (or an integer), $FALSE otherwise
  882. isFloat() {
  883. [[ -n "$1" && "$1" =~ ^-?[0-9]*([.][0-9]+)?$ ]] && return $TRUE
  884. return $FALSE
  885. }
  886. # Returns $TRUE if $1 is a floating point number bigger than zero, $FALSE otherwise
  887. isFloatBiggerThanZero() {
  888. isFloat "$1" && [[ (( $1 > 0 )) ]] && return $TRUE
  889. return $FALSE
  890. }
  891. # Returns $TRUE if $1 has a .pdf extension, false otherwsie
  892. isPDF() {
  893. [[ "$1" =~ ^..*\.pdf$ ]] && return $TRUE
  894. return $FALSE
  895. }
  896. # Returns $TRUE if $1 is a file, false otherwsie
  897. isFile() {
  898. [[ -f "$1" ]] && return $TRUE
  899. return $FALSE
  900. }
  901. # Returns $TRUE if $1 is NOT a file, false otherwsie
  902. notIsFile() {
  903. [[ -f "$1" ]] && return $FALSE
  904. return $TRUE
  905. }
  906. # Returns $TRUE if $1 is executable, false otherwsie
  907. isExecutable() {
  908. [[ -x "$1" ]] && return $TRUE
  909. return $FALSE
  910. }
  911. # Returns $TRUE if $1 is NOT executable, false otherwsie
  912. notIsExecutable() {
  913. [[ -x "$1" ]] && return $FALSE
  914. return $TRUE
  915. }
  916. # Returns $TRUE if $1 is a file and executable, false otherwsie
  917. isAvailable() {
  918. if isFile "$1" && isExecutable "$1"; then
  919. return $TRUE
  920. fi
  921. return $FALSE
  922. }
  923. # Returns $TRUE if $1 is NOT a file or NOT executable, false otherwsie
  924. notIsAvailable() {
  925. if notIsFile "$1" || notIsExecutable "$1"; then
  926. return $TRUE
  927. fi
  928. return $FALSE
  929. }
  930. ###################### PRINTING TO SCREEN ######################
  931. # Prints version
  932. printVersion() {
  933. local vStr=""
  934. [[ "$2" = 'verbose' ]] && vStr=" - Verbose Execution"
  935. local strBanner="$PDFSCALE_NAME v$VERSION$vStr"
  936. if [[ $1 -eq 2 ]]; then
  937. printError "$strBanner"
  938. elif [[ $1 -eq 3 ]]; then
  939. local extra="$(isNotEmpty "$2" && echo "$2")"
  940. echo "$strBanner$extra"
  941. else
  942. vprint "$strBanner"
  943. fi
  944. }
  945. # Prints the scale factor to screen, or custom message
  946. vPrintScaleFactor() {
  947. local scaleMsg="$SCALE"
  948. isNotEmpty "$1" && scaleMsg="$1"
  949. vprint " Scale Factor: $scaleMsg"
  950. }
  951. # Prints help info
  952. printHelp() {
  953. printVersion 3
  954. local paperList="$(printPaperNames)"
  955. echo "
  956. Usage: $PDFSCALE_NAME <inFile.pdf>
  957. $PDFSCALE_NAME -i <inFile.pdf>
  958. $PDFSCALE_NAME [-v] [-s <factor>] [-m <page-detection>] <inFile.pdf> [outfile.pdf]
  959. $PDFSCALE_NAME [-v] [-r <paper>] [-f <flip-detection>] [-a <auto-rotation>] <inFile.pdf> [outfile.pdf]
  960. $PDFSCALE_NAME -p
  961. $PDFSCALE_NAME -h
  962. $PDFSCALE_NAME -V
  963. Parameters:
  964. -v Verbose mode, prints extra information
  965. Use twice for timestamp
  966. -h Print this help to screen and exits
  967. -V Prints version to screen and exits
  968. -m <mode> Page size Detection mode
  969. May disable the Adaptive Mode
  970. -i <file> Prints <file> Page Size information to screen and exits
  971. -s <factor> Changes the scaling factor or forces scaling
  972. Defaults: $SCALE / no scaling (resize mode)
  973. MUST be a number bigger than zero
  974. Eg. -s 0.8 for 80% of the original size
  975. -r <paper> Triggers the Resize Paper Mode
  976. Resize PDF paper proportionally
  977. Uses a valid paper name or a custom defined paper
  978. -f <mode> Flip Detection Mode, defaults to 'auto'.
  979. Inverts Width <-> Height of a Resized PDF.
  980. Modes: a, auto - automatic detection, default
  981. f, force - forces flip W <-> H
  982. d, disable - disables flipping
  983. -a <mode> GS Auto-Rotation Setting, defaults to 'PageByPage'.
  984. Setting for GS -dAutoRotatePages.
  985. Modes: p, pagebypage - auto-rotates pages individually
  986. a, all - rotates all pages (or none) depending
  987. on a kind of \"majority decision\"
  988. n, none - retains orientation of each page
  989. -p Prints Ghostscript paper info tables to screen
  990. Scaling Mode:
  991. The default mode of operation is scaling mode with fixed paper
  992. size and scaling pre-set to $SCALE. By not using the resize mode
  993. you are using scaling mode. Flip-Detection and Auto-Rotation are
  994. disabled in Scaling mode.
  995. Resize Paper Mode:
  996. Disables the default scaling factor! ($SCALE)
  997. Changes the PDF Paper Size in points. Will fit-to-page.
  998. Mixed Mode:
  999. In mixed mode both the -s option and -r option must be specified.
  1000. The PDF will be first resized then scaled.
  1001. Output filename:
  1002. The output filename is optional. If no file name is passed
  1003. the output file will have the same name/destination of the
  1004. input file with added suffixes:
  1005. .SCALED.pdf is added to scaled files
  1006. .<PAPERSIZE>.pdf is added to resized files
  1007. .<PAPERSIZE>.SCALED.pdf is added in mixed mode
  1008. Page Size Detection Modes:
  1009. a, adaptive Default mode, tries all the methods below
  1010. g, grep Forces the use of grep method
  1011. m, mdls Forces the use of MacOS Quartz mdls
  1012. p, pdfinfo Forces the use of PDFInfo
  1013. i, identify Forces the use of ImageMagick's Identify
  1014. Valid Paper Names: (case-insensitive)
  1015. $paperList
  1016. Custom Paper Size:
  1017. Paper size can be set manually in Milimeters, Inches or Points.
  1018. Use: $PDFSCALE_NAME -r 'custom <measurement> <width> <height>'
  1019. Ex: $PDFSCALE_NAME -r 'custom mm 300 300'
  1020. Measurements can be: mm, inch, pts.
  1021. Custom paper definition MUST be quoted into a single parameter.
  1022. Actual size is applied in points (mms and inches are transformed).
  1023. Additional Notes:
  1024. - Adaptive Page size detection will try different modes until
  1025. it gets a page size. You can force a mode with -m 'mode'.
  1026. - Options must be passed before the file names to be parsed.
  1027. - Having the extension .pdf on the output file name is optional,
  1028. it will be added if not present.
  1029. - File and folder names with spaces should be quoted or escaped.
  1030. - The scaling is centered and using a scale bigger than 1 may
  1031. result on cropping parts of the pdf.
  1032. - Most of the options are case-insensitive, Ex: -m PdFinFo
  1033. Examples:
  1034. $PDFSCALE_NAME myPdfFile.pdf
  1035. $PDFSCALE_NAME -i '/home/My Folder/My PDF File.pdf'
  1036. $PDFSCALE_NAME myPdfFile.pdf \"My Scaled Pdf\"
  1037. $PDFSCALE_NAME -v -v myPdfFile.pdf
  1038. $PDFSCALE_NAME -s 0.85 myPdfFile.pdf My\\ Scaled\\ Pdf.pdf
  1039. $PDFSCALE_NAME -m pdfinfo -s 0.80 -v myPdfFile.pdf
  1040. $PDFSCALE_NAME -v -v -m i -s 0.7 myPdfFile.pdf
  1041. $PDFSCALE_NAME -r A4 myPdfFile.pdf
  1042. $PDFSCALE_NAME -v -v -r \"custom mm 252 356\" -s 0.9 -f \"../input file.pdf\" \"../my new pdf\"
  1043. "
  1044. }
  1045. # Prints usage info
  1046. usage() {
  1047. [[ "$2" != 'nobanner' ]] && printVersion 2
  1048. isNotEmpty "$1" && printError "$1"
  1049. printError "Usage: $PDFSCALE_NAME [-v] [-s <factor>] [-m <mode>] <inFile.pdf> [outfile.pdf]"
  1050. printError "Try: $PDFSCALE_NAME -h # for help"
  1051. }
  1052. # Prints Verbose information
  1053. vprint() {
  1054. [[ $VERBOSE -eq 0 ]] && return $TRUE
  1055. timestamp=""
  1056. [[ $VERBOSE -gt 1 ]] && timestamp="$(date +%Y-%m-%d:%H:%M:%S) | "
  1057. echo "$timestamp$1"
  1058. }
  1059. # Prints dependency information and aborts execution
  1060. printDependency() {
  1061. #printVersion 2
  1062. local brewName="$1"
  1063. [[ "$1" = 'pdfinfo' && "$OSNAME" = "Darwin" ]] && brewName="xpdf"
  1064. printError $'\n'"ERROR! You need to install the package '$1'"$'\n'
  1065. printError "Linux apt-get.: sudo apt-get install $1"
  1066. printError "Linux yum.....: sudo yum install $1"
  1067. printError "MacOS homebrew: brew install $brewName"
  1068. printError $'\n'"Aborting..."
  1069. exit $EXIT_MISSING_DEPENDENCY
  1070. }
  1071. # Prints initialization errors and aborts execution
  1072. initError() {
  1073. local errStr="$1"
  1074. local exitStat=$2
  1075. isEmpty "$exitStat" && exitStat=$EXIT_ERROR
  1076. usage "ERROR! $errStr" "$3"
  1077. exit $exitStat
  1078. }
  1079. # Prints to stderr
  1080. printError() {
  1081. echo >&2 "$@"
  1082. }
  1083. ########################## EXECUTION ###########################
  1084. initDeps
  1085. getOptions "${@}"
  1086. main
  1087. exit $?