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

990 regels
27 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. #
  8. # This script: https://github.com/tavinus/pdfScale
  9. # Based on: http://ma.juii.net/blog/scale-page-content-of-pdf-files
  10. # And: https://gist.github.com/MichaelJCole/86e4968dbfc13256228a
  11. ###################################################
  12. # PAGESIZE LOGIC
  13. # 1- Try to get Mediabox with CAT/GREP
  14. # 2- MacOS => try to use mdls
  15. # Linux => try to use pdfinfo
  16. # 3- Try to use identify (imagemagick)
  17. # 4- Fail
  18. # Remove postscript method,
  19. # may have licensing problems
  20. ###################################################
  21. VERSION="2.0.0"
  22. SCALE="0.95" # scaling factor (0.95 = 95%, e.g.)
  23. VERBOSE=0 # verbosity Level
  24. PDFSCALE_NAME="$(basename $0)" # simplified name of this script
  25. # Set with which later
  26. GSBIN="" # GhostScript Binary
  27. BCBIN="" # BC Math Binary
  28. IDBIN="" # Identify Binary
  29. PDFINFOBIN="" # PDF Info Binary
  30. MDLSBIN="" # MacOS mdls Binary
  31. OSNAME="$(uname 2>/dev/null)" # Check where we are running
  32. LC_MEASUREMENT="C" # To make sure our numbers have .decimals
  33. LC_ALL="C" # Some languages use , as decimal token
  34. LC_CTYPE="C"
  35. LC_NUMERIC="C"
  36. TRUE=0 # Silly stuff
  37. FALSE=1
  38. ADAPTIVEMODE=$TRUE # Automatically try to guess best mode
  39. AUTOMATIC_SCALING=$TRUE # Default scaling in $SCALE, override by resize mode
  40. MODE=""
  41. RESIZE_PAPER_TYPE=""
  42. PGWIDTH=""
  43. PGHEIGHT=""
  44. RESIZE_WIDTH=""
  45. RESIZE_HEIGHT=""
  46. # Exit flags
  47. EXIT_SUCCESS=0
  48. EXIT_ERROR=1
  49. EXIT_INVALID_PAGE_SIZE_DETECTED=10
  50. EXIT_FILE_NOT_FOUND=20
  51. EXIT_INPUT_NOT_PDF=21
  52. EXIT_INVALID_OPTION=22
  53. EXIT_NO_INPUT_FILE=23
  54. EXIT_INVALID_SCALE=24
  55. EXIT_MISSING_DEPENDENCY=25
  56. EXIT_IMAGEMAGIK_NOT_FOUND=26
  57. EXIT_MAC_MDLS_NOT_FOUND=27
  58. EXIT_PDFINFO_NOT_FOUND=28
  59. EXIT_INVALID_PAPER_SIZE=50
  60. # Parses and validates the scaling factor
  61. parseScale() {
  62. AUTOMATIC_SCALING=$FALSE
  63. if ! [[ -n "$1" && "$1" =~ ^-?[0-9]*([.][0-9]+)?$ && (($1 > 0 )) ]] ; then
  64. printError "Invalid factor: $1"
  65. printError "The factor must be a floating point number greater than 0"
  66. printError "Example: for 80% use 0.8"
  67. exit $EXIT_INVALID_SCALE
  68. fi
  69. SCALE=$1
  70. }
  71. # Parse a forced mode of operation
  72. parseMode() {
  73. if [[ -z $1 ]]; then
  74. printError "Mode is empty, please specify the desired mode"
  75. printError "Falling back to adaptive mode!"
  76. ADAPTIVEMODE=$TRUE
  77. MODE=""
  78. return $FALSE
  79. fi
  80. if [[ $1 = 'c' || $1 = 'catgrep' || $1 = 'cat+grep' || $1 = 'CatGrep' || $1 = 'C' || $1 = 'CATGREP' ]]; then
  81. ADAPTIVEMODE=$FALSE
  82. MODE="CATGREP"
  83. return $TRUE
  84. elif [[ $1 = 'i' || $1 = 'imagemagick' || $1 = 'identify' || $1 = 'ImageMagick' || $1 = 'Identify' || $1 = 'I' || $1 = 'IDENTIFY' ]]; then
  85. ADAPTIVEMODE=$FALSE
  86. MODE="IDENTIFY"
  87. return $TRUE
  88. elif [[ $1 = 'm' || $1 = 'mdls' || $1 = 'MDLS' || $1 = 'quartz' || $1 = 'mac' || $1 = 'M' ]]; then
  89. ADAPTIVEMODE=$FALSE
  90. MODE="MDLS"
  91. return $TRUE
  92. elif [[ $1 = 'p' || $1 = 'pdfinfo' || $1 = 'PDFINFO' || $1 = 'PdfInfo' || $1 = 'P' ]]; then
  93. ADAPTIVEMODE=$FALSE
  94. MODE="PDFINFO"
  95. return $TRUE
  96. elif [[ $1 = 'a' || $1 = 'adaptive' || $1 = 'automatic' || $1 = 'A' || $1 = 'ADAPTIVE' || $1 = 'AUTOMATIC' ]]; then
  97. ADAPTIVEMODE=$TRUE
  98. MODE=""
  99. return $TRUE
  100. else
  101. printError "Invalid mode: $1"
  102. printError "Falling back to adaptive mode!"
  103. ADAPTIVEMODE=$TRUE
  104. MODE=""
  105. return $FALSE
  106. fi
  107. return $FALSE
  108. }
  109. # Gets page size using imagemagick's identify
  110. getPageSizeImagemagick() {
  111. # Sanity and Adaptive together
  112. if notIsFile "$IDBIN" && isNotAdaptiveMode; then
  113. notAdaptiveFailed "Make sure you installed ImageMagick and have identify on your \$PATH" "ImageMagick's Identify"
  114. elif notIsFile "$IDBIN" && isAdaptiveMode; then
  115. return $FALSE
  116. fi
  117. # get data from image magick
  118. local identify="$("$IDBIN" -format '%[fx:w] %[fx:h]BREAKME' "$INFILEPDF" 2>/dev/null)"
  119. if isEmpty "$identify" && isNotAdaptiveMode; then
  120. notAdaptiveFailed "ImageMagicks's Identify returned an empty string!"
  121. elif isEmpty "$identify" && isAdaptiveMode; then
  122. return $FALSE
  123. fi
  124. identify="${identify%%BREAKME*}" # get page size only for 1st page
  125. identify=($identify) # make it an array
  126. PGWIDTH=$(printf '%.0f' "${identify[0]}") # assign
  127. PGHEIGHT=$(printf '%.0f' "${identify[1]}") # assign
  128. return $TRUE
  129. }
  130. # Gets page size using Mac Quarts mdls
  131. getPageSizeMdls() {
  132. # Sanity and Adaptive together
  133. if notIsFile "$MDLSBIN" && isNotAdaptiveMode; then
  134. notAdaptiveFailed "Are you even trying this on a Mac?" "Mac Quartz mdls"
  135. elif notIsFile "$MDLSBIN" && isAdaptiveMode; then
  136. return $FALSE
  137. fi
  138. local identify="$("$MDLSBIN" -mdls -name kMDItemPageHeight -name kMDItemPageWidth "$INFILEPDF" 2>/dev/null)"
  139. if isEmpty "$identify" && isNotAdaptiveMode; then
  140. notAdaptiveFailed "Mac Quartz mdls returned an empty string!"
  141. elif isEmpty "$identify" && isAdaptiveMode; then
  142. return $FALSE
  143. fi
  144. identify=${identify//$'\t'/ } # change tab to space
  145. identify=($identify) # make it an array
  146. if [[ "${identify[5]}" = "(null)" || "${identify[5]}" = "(null)" ]] && isNotAdaptiveMode; then
  147. notAdaptiveFailed "There was no metadata to read from the file! Is Spotlight OFF?"
  148. elif [[ "${identify[5]}" = "(null)" || "${identify[5]}" = "(null)" ]] && isAdaptiveMode; then
  149. return $FALSE
  150. fi
  151. PGWIDTH=$(printf '%.0f' "${identify[5]}") # assign
  152. PGHEIGHT=$(printf '%.0f' "${identify[2]}") # assign
  153. return $TRUE
  154. }
  155. # Gets page size using Linux PdfInfo
  156. getPageSizePdfInfo() {
  157. # Sanity and Adaptive together
  158. if notIsFile "$PDFINFOBIN" && isNotAdaptiveMode; then
  159. notAdaptiveFailed "Do you have pdfinfo installed and available on your \$PATH?" "Linux pdfinfo"
  160. elif notIsFile "$PDFINFOBIN" && isAdaptiveMode; then
  161. return $FALSE
  162. fi
  163. # get data from image magick
  164. local identify="$("$PDFINFOBIN" "$INFILEPDF" 2>/dev/null | grep -i 'Page size:' )"
  165. if isEmpty "$identify" && isNotAdaptiveMode; then
  166. notAdaptiveFailed "Linux PdfInfo returned an empty string!"
  167. elif isEmpty "$identify" && isAdaptiveMode; then
  168. return $FALSE
  169. fi
  170. identify="${identify##*Page size:}" # remove stuff
  171. identify=($identify) # make it an array
  172. PGWIDTH=$(printf '%.0f' "${identify[0]}") # assign
  173. PGHEIGHT=$(printf '%.0f' "${identify[2]}") # assign
  174. return $TRUE
  175. }
  176. # Gets page size using cat and grep
  177. getPageSizeCatGrep() {
  178. # get MediaBox info from PDF file using cat and grep, these are all possible
  179. # /MediaBox [0 0 595 841]
  180. # /MediaBox [ 0 0 595.28 841.89]
  181. # /MediaBox[ 0 0 595.28 841.89 ]
  182. # Get MediaBox data if possible
  183. local mediaBox="$(cat "$INFILEPDF" | grep -a '/MediaBox' | head -n1)"
  184. mediaBox="${mediaBox##*/MediaBox}"
  185. # No page size data available
  186. if isEmpty "$mediaBox" && isNotAdaptiveMode; then
  187. notAdaptiveFailed "There is no MediaBox in the pdf document!"
  188. elif isEmpty "$mediaBox" && isAdaptiveMode; then
  189. return $FALSE
  190. fi
  191. # remove chars [ and ]
  192. mediaBox="${mediaBox//[}"
  193. mediaBox="${mediaBox//]}"
  194. mediaBox=($mediaBox) # make it an array
  195. mbCount=${#mediaBox[@]} # array size
  196. # sanity
  197. if [[ $mbCount -lt 4 ]]; then
  198. printError "Error when reading the page size!"
  199. printError "The page size information is invalid!"
  200. exit $EXIT_INVALID_PAGE_SIZE_DETECTED
  201. fi
  202. # we are done
  203. PGWIDTH=$(printf '%.0f' "${mediaBox[2]}") # Get Round Width
  204. PGHEIGHT=$(printf '%.0f' "${mediaBox[3]}") # Get Round Height
  205. return $TRUE
  206. }
  207. # Prints error message and exits execution
  208. notAdaptiveFailed() {
  209. local errProgram="$2"
  210. local errStr="$1"
  211. if isEmpty "$2"; then
  212. printError "Error when reading input file!"
  213. printError "Could not determine the page size!"
  214. else
  215. printError "Error! $2 was not found!"
  216. fi
  217. isNotEmpty "$errStr" && printError "$errStr"
  218. printError "Aborting! You may want to try the adaptive mode."
  219. exit $EXIT_INVALID_PAGE_SIZE_DETECTED
  220. }
  221. # Return $TRUE if adaptive mode is enabled, false otherwise
  222. isAdaptiveMode() {
  223. return $ADAPTIVEMODE
  224. }
  225. # Return $TRUE if adaptive mode is disabled, false otherwise
  226. isNotAdaptiveMode() {
  227. isAdaptiveMode && return $FALSE
  228. return $TRUE
  229. }
  230. # Return $TRUE if $1 is empty, false otherwise
  231. isEmpty() {
  232. [[ -z "$1" ]] && return $TRUE
  233. return $FALSE
  234. }
  235. # Return $TRUE if $1 is NOT empty, false otherwise
  236. isNotEmpty() {
  237. [[ -z "$1" ]] && return $FALSE
  238. return $TRUE
  239. }
  240. # Detects operation mode and also runs the adaptive mode
  241. getPageSize() {
  242. if isNotAdaptiveMode; then
  243. vprint " Get Page Size: Adaptive Disabled"
  244. if [[ $MODE = "CATGREP" ]]; then
  245. vprint " Method: Cat + Grep"
  246. getPageSizeCatGrep
  247. elif [[ $MODE = "MDLS" ]]; then
  248. vprint " Method: Mac Quartz mdls"
  249. getPageSizeMdls
  250. elif [[ $MODE = "PDFINFO" ]]; then
  251. vprint " Method: PDFInfo"
  252. getPageSizePdfInfo
  253. elif [[ $MODE = "IDENTIFY" ]]; then
  254. vprint " Method: ImageMagick's Identify"
  255. getPageSizeImagemagick
  256. else
  257. printError "Error! Invalid Mode: $MODE"
  258. printError "Aborting execution..."
  259. exit $EXIT_INVALID_OPTION
  260. fi
  261. return $TRUE
  262. fi
  263. vprint " Get Page Size: Adaptive Enabled"
  264. vprint " Method: Cat + Grep"
  265. getPageSizeCatGrep
  266. if pageSizeIsInvalid && [[ $OSNAME = "Darwin" ]]; then
  267. vprint " Failed"
  268. vprint " Method: Mac Quartz mdls"
  269. getPageSizeMdls
  270. fi
  271. if pageSizeIsInvalid; then
  272. vprint " Failed"
  273. vprint " Method: PDFInfo"
  274. getPageSizePdfInfo
  275. fi
  276. if pageSizeIsInvalid; then
  277. vprint " Failed"
  278. vprint " Method: ImageMagick's Identify"
  279. getPageSizeImagemagick
  280. fi
  281. if pageSizeIsInvalid; then
  282. vprint " Failed"
  283. printError "Error when detecting PDF paper size!"
  284. printError "All methods of detection failed"
  285. printError "You may want to install pdfinfo or imagemagick"
  286. exit $EXIT_INVALID_PAGE_SIZE_DETECTED
  287. fi
  288. return $TRUE
  289. }
  290. vPrintSourcePageSizes() {
  291. vprint " $1 Width: $PGWIDTH postscript-points"
  292. vprint "$1 Height: $PGHEIGHT postscript-points"
  293. }
  294. # Returns $TRUE if $PGWIDTH OR $PGWIDTH are empty or NOT an Integer, false otherwise
  295. pageSizeIsInvalid() {
  296. if isNotAnInteger "$PGWIDTH" || isNotAnInteger "$PGHEIGHT"; then
  297. return $TRUE
  298. fi
  299. return $FALSE
  300. }
  301. isAnInteger() {
  302. case $1 in
  303. ''|*[!0-9]*) return $FALSE ;;
  304. *) return $TRUE ;;
  305. esac
  306. }
  307. isNotAnInteger() {
  308. case $1 in
  309. ''|*[!0-9]*) return $TRUE ;;
  310. *) return $FALSE ;;
  311. esac
  312. }
  313. # Prints usage info
  314. usage() {
  315. [[ "$2" != 'nobanner' ]] && printVersion 2
  316. [[ ! -z "$1" ]] && printError "$1"
  317. printError "Usage: $PDFSCALE_NAME [-v] [-s <factor>] [-m <mode>] <inFile.pdf> [outfile.pdf]"
  318. printError "Try: $PDFSCALE_NAME -h # for help"
  319. }
  320. # Prints Verbose information
  321. vprint() {
  322. [[ $VERBOSE -eq 0 ]] && return 0
  323. timestamp=""
  324. [[ $VERBOSE -gt 1 ]] && timestamp="$(date +%Y-%m-%d:%H:%M:%S) | "
  325. echo "$timestamp$1"
  326. }
  327. # Prints dependency information and aborts execution
  328. printDependency() {
  329. #printVersion 2
  330. local brewName="$1"
  331. [[ "$1" = 'pdfinfo' && "$OSNAME" = "Darwin" ]] && brewName="xpdf"
  332. printError $'\n'"ERROR! You need to install the package '$1'"$'\n'
  333. printError "Linux apt-get.: sudo apt-get install $1"
  334. printError "Linux yum.....: sudo yum install $1"
  335. printError "MacOS homebrew: brew install $brewName"
  336. printError $'\n'"Aborting..."
  337. exit $EXIT_MISSING_DEPENDENCY
  338. }
  339. # Prints initialization errors and aborts execution
  340. initError() {
  341. local errStr="$1"
  342. local exitStat=$2
  343. [[ -z "$exitStat" ]] && exitStat=$EXIT_ERROR
  344. usage "ERROR! $errStr" "$3"
  345. exit $exitStat
  346. }
  347. # Prints to stderr
  348. printError() {
  349. echo >&2 "$@"
  350. }
  351. # Returns $TRUE if $1 has a .pdf extension, false otherwsie
  352. isPDF() {
  353. [[ "$1" =~ ^..*\.pdf$ ]] && return $TRUE
  354. return $FALSE
  355. }
  356. # Returns $TRUE if $1 is a file, false otherwsie
  357. isFile() {
  358. [[ -f "$1" ]] && return $TRUE
  359. return $FALSE
  360. }
  361. # Returns $TRUE if $1 is NOT a file, false otherwsie
  362. notIsFile() {
  363. [[ -f "$1" ]] && return $FALSE
  364. return $TRUE
  365. }
  366. # Returns $TRUE if $1 is executable, false otherwsie
  367. isExecutable() {
  368. [[ -x "$1" ]] && return $TRUE
  369. return $FALSE
  370. }
  371. # Returns $TRUE if $1 is NOT executable, false otherwsie
  372. notIsExecutable() {
  373. [[ -x "$1" ]] && return $FALSE
  374. return $TRUE
  375. }
  376. # Returns $TRUE if $1 is a file and executable, false otherwsie
  377. isAvailable() {
  378. if isFile "$1" && isExecutable "$1"; then
  379. return $TRUE
  380. fi
  381. return $FALSE
  382. }
  383. # Returns $TRUE if $1 is NOT a file or NOT executable, false otherwsie
  384. notIsAvailable() {
  385. if notIsFile "$1" || notIsExecutable "$1"; then
  386. return $TRUE
  387. fi
  388. return $FALSE
  389. }
  390. # Loads external dependencies and checks for errors
  391. loadDeps() {
  392. GSBIN="$(which gs 2>/dev/null)"
  393. BCBIN="$(which bc 2>/dev/null)"
  394. IDBIN=$(which identify 2>/dev/null)
  395. MDLSBIN="$(which mdls 2>/dev/null)"
  396. PDFINFOBIN="$(which pdfinfo 2>/dev/null)"
  397. vprint "Checking for ghostscript and bcmath"
  398. if notIsAvailable "$GSBIN"; then printDependency 'ghostscript'; fi
  399. if notIsAvailable "$BCBIN"; then printDependency 'bc'; fi
  400. if [[ $MODE = "IDENTIFY" ]]; then
  401. vprint "Checking for imagemagick's identify"
  402. if notIsAvailable "$IDBIN"; then printDependency 'imagemagick'; fi
  403. fi
  404. if [[ $MODE = "PDFINFO" ]]; then
  405. vprint "Checking for pdfinfo"
  406. if notIsAvailable "$PDFINFOBIN"; then printDependency 'pdfinfo'; fi
  407. fi
  408. if [[ $MODE = "MDLS" ]]; then
  409. vprint "Checking for MacOS mdls"
  410. if notIsAvailable "$MDLSBIN"; then
  411. initError 'mdls executable was not found! Is this even MacOS?' $EXIT_MAC_MDLS_NOT_FOUND 'nobanner'
  412. fi
  413. fi
  414. }
  415. # Main execution
  416. main() {
  417. printVersion 1 'verbose'
  418. #getScaledOutputName
  419. #Intro message
  420. #vprint "$(basename $0) v$VERSION - Verbose execution"
  421. loadDeps
  422. vprint " Input file: $INFILEPDF"
  423. vprint " Output file: $OUTFILEPDF"
  424. getPageSize
  425. if isMixedMode; then
  426. vprint " Mixed Tasks: Resize & Scale"
  427. vprint " Scale factor: $SCALE"
  428. vPrintSourcePageSizes ' Source'
  429. outputFile="$OUTFILEPDF" # backup outFile name
  430. tempFile="${OUTFILEPDF%.pdf}.__TEMP__.pdf" # set a temp file name
  431. OUTFILEPDF="$tempFile" # set output to tmp file
  432. pageResize # resize to tmp file
  433. INFILEPDF="$tempFile" # get tmp file as input
  434. OUTFILEPDF="$outputFile" # reset final target
  435. PGWIDTH=$RESIZE_WIDTH # we already know the new page size
  436. PGHEIGHT=$RESIZE_HEIGHT # from the last command (Resize)
  437. vPrintSourcePageSizes ' New'
  438. pageScale # scale the resized pdf
  439. # remove tmp file
  440. rm "$tempFile" >/dev/null 2>&1 || printError "Error when removing temporary file: $tempFile"
  441. elif isResizeMode; then
  442. vprint " Single Task: Resize PDF Paper"
  443. vprint " Scale factor: Disabled (resize only)"
  444. vPrintSourcePageSizes ' Source'
  445. pageResize
  446. else
  447. local scaleMode=""
  448. vprint " Single Task: Scale PDF Contents"
  449. isManualScaledMode && scaleMode='(manual)' || scaleMode='(auto)'
  450. vprint " Scale factor: $SCALE $scaleMode"
  451. vPrintSourcePageSizes ' Source'
  452. pageScale
  453. fi
  454. #pageScale
  455. #pageResize
  456. }
  457. # Parse options
  458. getOptions() {
  459. while getopts ":vhVs:m:r:p" o; do
  460. case "${o}" in
  461. v)
  462. ((VERBOSE++))
  463. ;;
  464. h)
  465. printHelp
  466. exit $EXIT_SUCCESS
  467. ;;
  468. V)
  469. printVersion
  470. exit $EXIT_SUCCESS
  471. ;;
  472. s)
  473. parseScale ${OPTARG}
  474. ;;
  475. m)
  476. parseMode ${OPTARG}
  477. ;;
  478. r)
  479. parsePaperResize ${OPTARG}
  480. ;;
  481. p)
  482. printPaperInfo
  483. exit $EXIT_SUCCESS
  484. ;;
  485. *)
  486. initError "Invalid Option: -$OPTARG" $EXIT_INVALID_OPTION
  487. ;;
  488. esac
  489. done
  490. shift $((OPTIND-1))
  491. # Validate input PDF file
  492. INFILEPDF="$1"
  493. isEmpty "$INFILEPDF" && initError "Input file is empty!" $EXIT_NO_INPUT_FILE
  494. isPDF "$INFILEPDF" || initError "Input file is not a PDF file: $INFILEPDF" $EXIT_INPUT_NOT_PDF
  495. isFile "$INFILEPDF" || initError "Input file not found: $INFILEPDF" $EXIT_FILE_NOT_FOUND
  496. if isEmpty "$2"; then
  497. if isMixedMode; then
  498. OUTFILEPDF="${INFILEPDF%.pdf}.$(uppercase $RESIZE_PAPER_TYPE).SCALED.pdf"
  499. elif isResizeMode; then
  500. OUTFILEPDF="${INFILEPDF%.pdf}.$(uppercase $RESIZE_PAPER_TYPE).pdf"
  501. else
  502. OUTFILEPDF="${INFILEPDF%.pdf}.SCALED.pdf"
  503. fi
  504. else
  505. OUTFILEPDF="${2%.pdf}.pdf"
  506. fi
  507. }
  508. # Runs the ghostscript scaling script
  509. pageScale() {
  510. # Compute translation factors (to center page).
  511. XTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGWIDTH" | "$BCBIN")
  512. YTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGHEIGHT" | "$BCBIN")
  513. vprint " Translation X: $XTRANS"
  514. vprint " Translation Y: $YTRANS"
  515. # Do it.
  516. "$GSBIN" \
  517. -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \
  518. -dCompatibilityLevel="1.5" -dPDFSETTINGS="/printer" \
  519. -dColorConversionStrategy=/LeaveColorUnchanged \
  520. -dSubsetFonts=true -dEmbedAllFonts=true \
  521. -dDEVICEWIDTHPOINTS=$PGWIDTH -dDEVICEHEIGHTPOINTS=$PGHEIGHT \
  522. -sOutputFile="$OUTFILEPDF" \
  523. -c "<</BeginPage{$SCALE $SCALE scale $XTRANS $YTRANS translate}>> setpagedevice" \
  524. -f "$INFILEPDF" &
  525. wait ${!}
  526. }
  527. pageResize() {
  528. getGSPaperSize "$RESIZE_PAPER_TYPE"
  529. local tmpInverter=""
  530. if [[ $PGWIDTH -gt $PGHEIGHT && $RESIZE_WIDTH -lt $RESIZE_HEIGHT ]]; then
  531. vprint " Flip Detect: Wrong orientation!"
  532. vprint " Inverting Width <-> Height"
  533. tmpInverter=$RESIZE_HEIGHT
  534. RESIZE_HEIGHT=$RESIZE_WIDTH
  535. RESIZE_WIDTH=$tmpInverter
  536. fi
  537. vprint " Resizing to: $(uppercase $RESIZE_PAPER_TYPE) ( $RESIZE_WIDTH x $RESIZE_HEIGHT )"
  538. # Change page size
  539. "$GSBIN" \
  540. -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \
  541. -dCompatibilityLevel="1.5" -dPDFSETTINGS="/printer" \
  542. -dColorConversionStrategy=/LeaveColorUnchanged \
  543. -dSubsetFonts=true -dEmbedAllFonts=true \
  544. -dDEVICEWIDTHPOINTS=$RESIZE_WIDTH -dDEVICEHEIGHTPOINTS=$RESIZE_HEIGHT \
  545. -dFIXEDMEDIA -dPDFFitPage \
  546. -sOutputFile="$OUTFILEPDF" \
  547. -f "$INFILEPDF" &
  548. wait ${!}
  549. }
  550. getPaperInfo() {
  551. # name inchesW inchesH mmW mmH pointsW pointsH
  552. sizesUS="\
  553. 11x17 11.0 17.0 279 432 792 1224
  554. ledger 17.0 11.0 432 279 1224 792
  555. legal 8.5 14.0 216 356 612 1008
  556. letter 8.5 11.0 216 279 612 792
  557. lettersmall 8.5 11.0 216 279 612 792
  558. archE 36.0 48.0 914 1219 2592 3456
  559. archD 24.0 36.0 610 914 1728 2592
  560. archC 18.0 24.0 457 610 1296 1728
  561. archB 12.0 18.0 305 457 864 1296
  562. archA 9.0 12.0 229 305 648 864"
  563. sizesISO="\
  564. a0 33.1 46.8 841 1189 2384 3370
  565. a1 23.4 33.1 594 841 1684 2384
  566. a2 16.5 23.4 420 594 1191 1684
  567. a3 11.7 16.5 297 420 842 1191
  568. a4 8.3 11.7 210 297 595 842
  569. a4small 8.3 11.7 210 297 595 842
  570. a5 5.8 8.3 148 210 420 595
  571. a6 4.1 5.8 105 148 297 420
  572. a7 2.9 4.1 74 105 210 297
  573. a8 2.1 2.9 52 74 148 210
  574. a9 1.5 2.1 37 52 105 148
  575. a10 1.0 1.5 26 37 73 105
  576. isob0 39.4 55.7 1000 1414 2835 4008
  577. isob1 27.8 39.4 707 1000 2004 2835
  578. isob2 19.7 27.8 500 707 1417 2004
  579. isob3 13.9 19.7 353 500 1001 1417
  580. isob4 9.8 13.9 250 353 709 1001
  581. isob5 6.9 9.8 176 250 499 709
  582. isob6 4.9 6.9 125 176 354 499
  583. c0 36.1 51.1 917 1297 2599 3677
  584. c1 25.5 36.1 648 917 1837 2599
  585. c2 18.0 25.5 458 648 1298 1837
  586. c3 12.8 18.0 324 458 918 1298
  587. c4 9.0 12.8 229 324 649 918
  588. c5 6.4 9.0 162 229 459 649
  589. c6 4.5 6.4 114 162 323 459"
  590. sizesJIS="\
  591. jisb0 NA NA 1030 1456 NA NA
  592. jisb1 NA NA 728 1030 NA NA
  593. jisb2 NA NA 515 728 NA NA
  594. jisb3 NA NA 364 515 NA NA
  595. jisb4 NA NA 257 364 NA NA
  596. jisb5 NA NA 182 257 NA NA
  597. jisb6 NA NA 128 182 NA NA"
  598. sizesOther="\
  599. flsa 8.5 13.0 216 330 612 936
  600. flse 8.5 13.0 216 330 612 936
  601. halfletter 5.5 8.5 140 216 396 612
  602. hagaki 3.9 5.8 100 148 283 420"
  603. sizesAll="\
  604. $sizesUS
  605. $sizesISO
  606. $sizesJIS
  607. $sizesOther"
  608. }
  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. getPaperNames() {
  621. 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 \
  622. 11x17 ledger legal letter lettersmall archE archD archC archB archA \
  623. jisb0 jisb1 jisb2 jisb3 jisb4 jisb5 jisb6 \
  624. flsa flse halfletter hagaki)
  625. }
  626. printPaperNames() {
  627. isEmpty "$paperNames" && getPaperNames
  628. for i in "${!paperNames[@]}"; do
  629. [[ $i -ne 0 && $((i % 5)) -eq 0 ]] && echo ""
  630. ppN="$(uppercase ${paperNames[i]})"
  631. printf "%-14s" "$ppN"
  632. done
  633. echo ""
  634. }
  635. isPaperName() {
  636. isEmpty "$1" && return $FALSE
  637. isEmpty "$paperNames" && getPaperNames
  638. for i in "${paperNames[@]}"; do
  639. [[ "$i" = "$1" ]] && return $TRUE
  640. done
  641. return $FALSE
  642. }
  643. printPaperInfo() {
  644. printVersion
  645. echo $'\n'"Valid Ghostscript Paper Sizes accepted"$'\n'
  646. getPaperInfo
  647. printPaperTable "ISO STANDARD" "$sizesISO"; echo
  648. printPaperTable "US STANDARD" "$sizesUS"; echo
  649. printPaperTable "JIS STANDARD" "$sizesJIS"; echo
  650. printPaperTable "OTHERS" "$sizesOther"; echo
  651. }
  652. printTableLine() {
  653. echo '+-----------------------------------------------------------------+'
  654. }
  655. printTableDivider() {
  656. echo '+-----------------+-------+-------+-------+-------+-------+-------+'
  657. }
  658. printTableHeader() {
  659. echo '| Name | inchW | inchH | mm W | mm H | pts W | pts H |'
  660. }
  661. printTableTitle() {
  662. printf "| %-64s%s\n" "$1" '|'
  663. }
  664. printPaperTable() {
  665. printTableLine
  666. printTableTitle "$1"
  667. printTableLine
  668. printTableHeader
  669. printTableDivider
  670. while read l; do
  671. local cols=($l)
  672. printf "| %-15s | %+5s | %+5s | %+5s | %+5s | %+5s | %+5s |\n" ${cols[*]};
  673. done <<< "$2"
  674. printTableDivider
  675. }
  676. parsePaperResize() {
  677. isEmpty "$1" && initError 'Invalid Paper Type: (empty)' $EXIT_INVALID_PAPER_SIZE
  678. local lowercasePaper="$(lowercase $1)"
  679. ! isPaperName "$lowercasePaper" && initError "Invalid Paper Type: $1" $EXIT_INVALID_PAPER_SIZE
  680. RESIZE_PAPER_TYPE="$lowercasePaper"
  681. }
  682. isManualScaledMode() {
  683. [[ $AUTOMATIC_SCALING -eq $TRUE ]] && return $FALSE
  684. return $TRUE
  685. }
  686. isResizeMode() {
  687. isEmpty $RESIZE_PAPER_TYPE && return $FALSE
  688. return $TRUE
  689. }
  690. isMixedMode() {
  691. isResizeMode && isManualScaledMode && return $TRUE
  692. return $FALSE
  693. }
  694. lowercaseChar() {
  695. case "$1" in
  696. [A-Z])
  697. n=$(printf "%d" "'$1")
  698. n=$((n+32))
  699. printf \\$(printf "%o" "$n")
  700. ;;
  701. *)
  702. printf "%s" "$1"
  703. ;;
  704. esac
  705. }
  706. lowercase() {
  707. word="$@"
  708. for((i=0;i<${#word};i++))
  709. do
  710. ch="${word:$i:1}"
  711. lowercaseChar "$ch"
  712. done
  713. }
  714. uppercaseChar(){
  715. case "$1" in
  716. [a-z])
  717. n=$(printf "%d" "'$1")
  718. n=$((n-32))
  719. printf \\$(printf "%o" "$n")
  720. ;;
  721. *)
  722. printf "%s" "$1"
  723. ;;
  724. esac
  725. }
  726. uppercase() {
  727. word="$@"
  728. for((i=0;i<${#word};i++))
  729. do
  730. ch="${word:$i:1}"
  731. uppercaseChar "$ch"
  732. done
  733. }
  734. #printPaperInfo
  735. #printPaperNames
  736. #echo "----"
  737. #isPaperName a4s; echo $?
  738. ####----------Print-Program-Information----------####
  739. # Prints version
  740. printVersion() {
  741. local vStr=""
  742. [[ "$2" = 'verbose' ]] && vStr=" - Verbose Execution"
  743. if [[ $1 -eq 2 ]]; then
  744. printError "$PDFSCALE_NAME v$VERSION$vStr"
  745. else
  746. echo "$PDFSCALE_NAME v$VERSION$vStr"
  747. fi
  748. }
  749. # Prints help info
  750. printHelp() {
  751. printVersion
  752. local paperList="$(printPaperNames)"
  753. echo "
  754. Usage: $PDFSCALE_NAME [-v] [-s <factor>] [-m <mode>] [-r <paper>] <inFile.pdf> [outfile.pdf]
  755. $PDFSCALE_NAME -p
  756. $PDFSCALE_NAME -h
  757. $PDFSCALE_NAME -V
  758. Parameters:
  759. -v Verbose mode, prints extra information
  760. Use twice for timestamp
  761. -h Print this help to screen and exits
  762. -V Prints version to screen and exits
  763. -m <mode> Page size Detection mode
  764. May disable the Adaptive Mode
  765. -s <factor> Changes the scaling factor or forces scaling
  766. Defaults: $SCALE / no scaling (resize mode)
  767. MUST be a number bigger than zero
  768. Eg. -s 0.8 for 80% of the original size
  769. -r <paper> Triggers the Resize Paper Mode
  770. Resize PDF paper proportionally
  771. Must be a valid Ghostscript paper name
  772. -p Prints Ghostscript paper info tables to screen
  773. Scaling Mode:
  774. The default mode of operation is scaling mode with fixed paper
  775. size and scaling pre-set to $SCALE. By not using the resize mode
  776. you are using scaling mode.
  777. Resize Paper Mode:
  778. Disables the default scaling factor! ($SCALE)
  779. Alternative mode of operation to change the PDF paper
  780. proportionally. Will fit-to-page.
  781. Mixed Mode:
  782. In mixed mode both the -s option and -r option must be specified.
  783. The PDF will be both scaled and have the paper type changed.
  784. Output filename:
  785. The output filename is optional. If no file name is passed
  786. the output file will have the same name/destination of the
  787. input file with added suffixes:
  788. .SCALED.pdf is added to scaled files
  789. .<PAPERSIZE>.pdf is added to resized files
  790. .<PAPERSIZE>.SCALED.pdf is added in mixed mode
  791. Page Detection Modes:
  792. a, adaptive Default mode, tries all the methods below
  793. c, cat+grep Forces the use of the cat + grep method
  794. m, mdls Forces the use of MacOS Quartz mdls
  795. p, pdfinfo Forces the use of PDFInfo
  796. i, identify Forces the use of ImageMagick's Identify
  797. Valid Ghostscript Paper Names:
  798. $paperList
  799. Notes:
  800. - Adaptive Page size detection will try different modes until
  801. it gets a page size. You can force a mode with -m 'mode'.
  802. - Options must be passed before the file names to be parsed.
  803. - Having the extension .pdf on the output file name is optional,
  804. it will be added if not present.
  805. - File and folder names with spaces should be quoted or escaped.
  806. - The scaling is centered and using a scale bigger than 1 may
  807. result on cropping parts of the pdf.
  808. Examples:
  809. $PDFSCALE_NAME myPdfFile.pdf
  810. $PDFSCALE_NAME myPdfFile.pdf myScaledPdf
  811. $PDFSCALE_NAME -v -v myPdfFile.pdf
  812. $PDFSCALE_NAME -s 0.85 myPdfFile.pdf myScaledPdf.pdf
  813. $PDFSCALE_NAME -m pdfinfo -s 0.80 -v myPdfFile.pdf
  814. $PDFSCALE_NAME -v -v -m i -s 0.7 myPdfFile.pdf
  815. $PDFSCALE_NAME -h
  816. "
  817. }
  818. ######### START EXECUTION
  819. getOptions "${@}"
  820. main
  821. exit $?