Bash Script to scale and/or resize PDFs from the command line.
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 

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