From 9d65332ec7392202ca749c7bd08350bc3b957f78 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sat, 13 May 2017 20:07:52 -0300 Subject: [PATCH 01/59] V2.0.0-beta-final; Complete Code refactoring, still needs some cleaning, but all working; Add option to page resize; Option for mixed tasks (resize + scale); Better validation all around; Option to print Valid GS Paper sizes tables; Main and GetOpt functions; All error messages should be going to stderr now; Just need some more testing and some code cleaning, organisation, documentation. --- .gitignore | 9 + pdfScale.sh | 1038 ++++++++++++++++++++++++++++++++++++++------------- 2 files changed, 790 insertions(+), 257 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8bfaac4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +# OS generated files # +###################### +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db diff --git a/pdfScale.sh b/pdfScale.sh index 4627cd0..d3cf6fa 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -14,7 +14,6 @@ ################################################### # PAGESIZE LOGIC # 1- Try to get Mediabox with CAT/GREP -# Remove /BBox search as it is unreliable # 2- MacOS => try to use mdls # Linux => try to use pdfinfo # 3- Try to use identify (imagemagick) @@ -24,12 +23,12 @@ ################################################### -VERSION="1.4.9" +VERSION="2.0.0" SCALE="0.95" # scaling factor (0.95 = 95%, e.g.) VERBOSE=0 # verbosity Level -BASENAME="$(basename $0)" # simplified name of this script +PDFSCALE_NAME="$(basename $0)" # simplified name of this script -# Set with which after we check dependencies +# Set with which later GSBIN="" # GhostScript Binary BCBIN="" # BC Math Binary IDBIN="" # Identify Binary @@ -47,107 +46,43 @@ TRUE=0 # Silly stuff FALSE=1 ADAPTIVEMODE=$TRUE # Automatically try to guess best mode +AUTOMATIC_SCALING=$TRUE # Default scaling in $SCALE, override by resize mode MODE="" +RESIZE_PAPER_TYPE="" +PGWIDTH="" +PGHEIGHT="" +RESIZE_WIDTH="" +RESIZE_HEIGHT="" -# Prints version -printVersion() { - if [[ $1 -eq 2 ]]; then - echo >&2 "$BASENAME v$VERSION" - else - echo "$BASENAME v$VERSION" - fi -} +# Exit flags +EXIT_SUCCESS=0 +EXIT_ERROR=1 +EXIT_INVALID_PAGE_SIZE_DETECTED=10 +EXIT_FILE_NOT_FOUND=20 +EXIT_INPUT_NOT_PDF=21 +EXIT_INVALID_OPTION=22 +EXIT_NO_INPUT_FILE=23 +EXIT_INVALID_SCALE=24 +EXIT_MISSING_DEPENDENCY=25 +EXIT_IMAGEMAGIK_NOT_FOUND=26 +EXIT_MAC_MDLS_NOT_FOUND=27 +EXIT_PDFINFO_NOT_FOUND=28 +EXIT_INVALID_PAPER_SIZE=50 -# Prints help info -printHelp() { - printVersion - echo " -Usage: $BASENAME [-v] [-s ] [-m ] [outfile.pdf] - $BASENAME -h - $BASENAME -V -Parameters: - -v Verbose mode, prints extra information - Use twice for even more information - -h Print this help to screen and exits - -V Prints version to screen and exits - -m Force a mode of page size detection - May disable the Adaptive Mode - -s Changes the scaling factor, defaults to 0.95 - MUST be a number bigger than zero - Eg. -s 0.8 for 80% of the original size -Modes: - a, adaptive Default mode, tries all the methods below - c, cat+grep Forces the use of the cat + grep method - m, mdls Forces the use of MacOS Quartz mdls - p, pdfinfo Forces the use of Linux PdfInfo - i, identify Forces the use of ImageMagick's Identify - -Notes: - - Adaptive Page size detection will try different modes until - it gets a page size. You can force a mode with -m 'mode'. - - Options must be passed before the file names to be parsed. - - The output filename is optional. If no file name is passed - the output file will have the same name/destination of the - input file, with .SCALED.pdf at the end (instead of just .pdf). - - Having the extension .pdf on the output file name is optional, - it will be added if not present. - - Should handle file names with spaces without problems. - - The scaling is centered and using a scale bigger than 1 may - result on cropping parts of the pdf. - -Examples: - $BASENAME myPdfFile.pdf - $BASENAME myPdfFile.pdf myScaledPdf - $BASENAME -v -v myPdfFile.pdf - $BASENAME -s 0.85 myPdfFile.pdf myScaledPdf.pdf - $BASENAME -m pdfinfo -s 0.80 -v myPdfFile.pdf - $BASENAME -v -v -m i -s 0.7 myPdfFile.pdf - $BASENAME -h -" -} - - -# Prints usage info -usage() { - printVersion 2 - echo >&2 "Usage: $BASENAME [-v] [-s ] [-m ] [outfile.pdf]" - echo >&2 "Try: $BASENAME -h # for help" - exit 1 -} - - -# Prints Verbose information -vprint() { - [[ $VERBOSE -eq 0 ]] && return 0 - timestamp="" - [[ $VERBOSE -gt 1 ]] && timestamp="$(date +%Y-%m-%d:%H:%M:%S) | " - echo "$timestamp$1" -} - - -# Prints dependency information and aborts execution -printDependency() { - printVersion 2 - echo >&2 $'\n'"ERROR! You need to install the package '$1'"$'\n' - echo >&2 "Linux apt-get.: sudo apt-get install $1" - echo >&2 "Linux yum.....: sudo yum install $1" - echo >&2 "MacOS homebrew: brew install $1" - echo >&2 $'\n'"Aborting..." - exit 3 -} # Parses and validates the scaling factor parseScale() { + AUTOMATIC_SCALING=$FALSE if ! [[ -n "$1" && "$1" =~ ^-?[0-9]*([.][0-9]+)?$ && (($1 > 0 )) ]] ; then - echo >&2 "Invalid factor: $1" - echo >&2 "The factor must be a floating point number greater than 0" - echo >&2 "Example: for 80% use 0.8" - exit 2 + printError "Invalid factor: $1" + printError "The factor must be a floating point number greater than 0" + printError "Example: for 80% use 0.8" + exit $EXIT_INVALID_SCALE fi SCALE=$1 } @@ -156,8 +91,8 @@ parseScale() { # Parse a forced mode of operation parseMode() { if [[ -z $1 ]]; then - echo "Mode is empty, please specify the desired mode" - echo "Falling back to adaptive mode!" + printError "Mode is empty, please specify the desired mode" + printError "Falling back to adaptive mode!" ADAPTIVEMODE=$TRUE MODE="" return $FALSE @@ -184,8 +119,8 @@ parseMode() { MODE="" return $TRUE else - echo "Invalid mode: $1" - echo "Falling back to adaptive mode!" + printError "Invalid mode: $1" + printError "Falling back to adaptive mode!" ADAPTIVEMODE=$TRUE MODE="" return $FALSE @@ -197,27 +132,19 @@ parseMode() { # Gets page size using imagemagick's identify getPageSizeImagemagick() { - # Sanity - if [[ ! -f $IDBIN && $ADAPTIVEMODE = $FALSE ]]; then - echo "Error! ImageMagick's Identify was not found!" - echo "Make sure you installed ImageMagick and have identify on your \$PATH" - echo "Aborting! You may want to try the adaptive mode." - exit 15 - elif [[ ! -f $IDBIN && $ADAPTIVEMODE = $TRUE ]]; then + # Sanity and Adaptive together + if notIsFile "$IDBIN" && isNotAdaptiveMode; then + notAdaptiveFailed "Make sure you installed ImageMagick and have identify on your \$PATH" "ImageMagick's Identify" + elif notIsFile "$IDBIN" && isAdaptiveMode; then return $FALSE fi - + # get data from image magick local identify="$("$IDBIN" -format '%[fx:w] %[fx:h]BREAKME' "$INFILEPDF" 2>/dev/null)" - # No page size data available - if [[ -z $identify && $ADAPTIVEMODE = $FALSE ]]; then - echo "Error when reading input file!" - echo "Could not determine the page size!" - echo "ImageMagicks's Identify returned an empty string!" - echo "Aborting! You may want to try the adaptive mode." - exit 15 - elif [[ -z $identify && $ADAPTIVEMODE = $TRUE ]]; then + if isEmpty "$identify" && isNotAdaptiveMode; then + notAdaptiveFailed "ImageMagicks's Identify returned an empty string!" + elif isEmpty "$identify" && isAdaptiveMode; then return $FALSE fi @@ -225,65 +152,59 @@ getPageSizeImagemagick() { identify=($identify) # make it an array PGWIDTH=$(printf '%.0f' "${identify[0]}") # assign PGHEIGHT=$(printf '%.0f' "${identify[1]}") # assign + + return $TRUE } # Gets page size using Mac Quarts mdls getPageSizeMdls() { - # Sanity - if [[ ! -f $MDLSBIN && $ADAPTIVEMODE = $FALSE ]]; then - echo "Error! Mac Quartz mdls was not found!" - echo "Are you even trying this on a Mac?" - echo "Aborting! You may want to try the adaptive mode." - exit 15 - elif [[ ! -f $MDLSBIN && $ADAPTIVEMODE = $TRUE ]]; then + # Sanity and Adaptive together + if notIsFile "$MDLSBIN" && isNotAdaptiveMode; then + notAdaptiveFailed "Are you even trying this on a Mac?" "Mac Quartz mdls" + elif notIsFile "$MDLSBIN" && isAdaptiveMode; then return $FALSE fi - - # get data from mdls + local identify="$("$MDLSBIN" -mdls -name kMDItemPageHeight -name kMDItemPageWidth "$INFILEPDF" 2>/dev/null)" - - if [[ -z $identify && $ADAPTIVEMODE = $FALSE ]]; then - echo "Error when reading input file!" - echo "Could not determine the page size!" - echo "Mac Quartz mdls returned an empty string!" - echo "Aborting! You may want to try the adaptive mode." - exit 15 - elif [[ -z $identify && $ADAPTIVEMODE = $TRUE ]]; then + + if isEmpty "$identify" && isNotAdaptiveMode; then + notAdaptiveFailed "Mac Quartz mdls returned an empty string!" + elif isEmpty "$identify" && isAdaptiveMode; then return $FALSE fi - identify=${identify//$'\t'/ } # change tab to space identify=($identify) # make it an array - + + if [[ "${identify[5]}" = "(null)" || "${identify[5]}" = "(null)" ]] && isNotAdaptiveMode; then + notAdaptiveFailed "There was no metadata to read from the file! Is Spotlight OFF?" + elif [[ "${identify[5]}" = "(null)" || "${identify[5]}" = "(null)" ]] && isAdaptiveMode; then + return $FALSE + fi + PGWIDTH=$(printf '%.0f' "${identify[5]}") # assign PGHEIGHT=$(printf '%.0f' "${identify[2]}") # assign + + return $TRUE } # Gets page size using Linux PdfInfo getPageSizePdfInfo() { - # Sanity - if [[ ! -f $PDFINFOBIN && $ADAPTIVEMODE = $FALSE ]]; then - echo "Error! Linux pdfinfo was not found!" - echo "Do you have pdfinfo installed and available on your \$PATH?" - echo "Aborting! You may want to try the adaptive mode." - exit 15 - elif [[ ! -f $PDFINFOBIN && $ADAPTIVEMODE = $TRUE ]]; then + # Sanity and Adaptive together + if notIsFile "$PDFINFOBIN" && isNotAdaptiveMode; then + notAdaptiveFailed "Do you have pdfinfo installed and available on your \$PATH?" "Linux pdfinfo" + elif notIsFile "$PDFINFOBIN" && isAdaptiveMode; then return $FALSE fi - + # get data from image magick local identify="$("$PDFINFOBIN" "$INFILEPDF" 2>/dev/null | grep -i 'Page size:' )" - if [[ -z $identify && $ADAPTIVEMODE = $FALSE ]]; then - echo "Error when reading input file!" - echo "Could not determine the page size!" - echo "Linux PdfInfo returned an empty string!" - echo "Aborting! You may want to try the adaptive mode." - exit 15 - elif [[ -z $identify && $ADAPTIVEMODE = $TRUE ]]; then + if isEmpty "$identify" && isNotAdaptiveMode; then + notAdaptiveFailed "Linux PdfInfo returned an empty string!" + elif isEmpty "$identify" && isAdaptiveMode; then return $FALSE fi @@ -292,6 +213,8 @@ getPageSizePdfInfo() { PGWIDTH=$(printf '%.0f' "${identify[0]}") # assign PGHEIGHT=$(printf '%.0f' "${identify[2]}") # assign + + return $TRUE } @@ -307,13 +230,9 @@ getPageSizeCatGrep() { mediaBox="${mediaBox##*/MediaBox}" # No page size data available - if [[ -z $mediaBox && $ADAPTIVEMODE = $FALSE ]]; then - echo "Error when reading input file!" - echo "Could not determine the page size!" - echo "There is no MediaBox in the pdf document!" - echo "Aborting! You may want to try the adaptive mode." - exit 15 - elif [[ -z $mediaBox && $ADAPTIVEMODE = $TRUE ]]; then + if isEmpty "$mediaBox" && isNotAdaptiveMode; then + notAdaptiveFailed "There is no MediaBox in the pdf document!" + elif isEmpty "$mediaBox" && isAdaptiveMode; then return $FALSE fi @@ -326,9 +245,9 @@ getPageSizeCatGrep() { # sanity if [[ $mbCount -lt 4 ]]; then - echo "Error when reading the page size!" - echo "The page size information is invalid!" - exit 16 + printError "Error when reading the page size!" + printError "The page size information is invalid!" + exit $EXIT_INVALID_PAGE_SIZE_DETECTED fi # we are done @@ -338,11 +257,48 @@ getPageSizeCatGrep() { return $TRUE } +# Prints error message and exits execution +notAdaptiveFailed() { + local errProgram="$2" + local errStr="$1" + if isEmpty "$2"; then + printError "Error when reading input file!" + printError "Could not determine the page size!" + else + printError "Error! $2 was not found!" + fi + isNotEmpty "$errStr" && printError "$errStr" + printError "Aborting! You may want to try the adaptive mode." + exit $EXIT_INVALID_PAGE_SIZE_DETECTED +} + +# Return $TRUE if adaptive mode is enabled, false otherwise +isAdaptiveMode() { + return $ADAPTIVEMODE +} + +# Return $TRUE if adaptive mode is disabled, false otherwise +isNotAdaptiveMode() { + isAdaptiveMode && return $FALSE + return $TRUE +} + +# Return $TRUE if $1 is empty, false otherwise +isEmpty() { + [[ -z "$1" ]] && return $TRUE + return $FALSE +} + +# Return $TRUE if $1 is NOT empty, false otherwise +isNotEmpty() { + [[ -z "$1" ]] && return $FALSE + return $TRUE +} # Detects operation mode and also runs the adaptive mode getPageSize() { - if [[ $ADAPTIVEMODE = $FALSE ]]; then - vprint " Adaptive mode: Disabled" + if isNotAdaptiveMode; then + vprint " Get Page Size: Adaptive Disabled" if [[ $MODE = "CATGREP" ]]; then vprint " Method: Cat + Grep" getPageSizeCatGrep @@ -350,149 +306,717 @@ getPageSize() { vprint " Method: Mac Quartz mdls" getPageSizeMdls elif [[ $MODE = "PDFINFO" ]]; then - vprint " Method: Linux PdfInfo" + vprint " Method: PDFInfo" getPageSizePdfInfo elif [[ $MODE = "IDENTIFY" ]]; then vprint " Method: ImageMagick's Identify" getPageSizeImagemagick else - echo "Error! Invalid Mode: $MODE" - echo "Aborting execution..." - exit 20 + printError "Error! Invalid Mode: $MODE" + printError "Aborting execution..." + exit $EXIT_INVALID_OPTION fi return $TRUE fi - vprint " Adaptive mode: Enabled" + vprint " Get Page Size: Adaptive Enabled" vprint " Method: Cat + Grep" getPageSizeCatGrep - if [[ -z $PGWIDTH && -z $PGHEIGHT ]]; then + if pageSizeIsInvalid && [[ $OSNAME = "Darwin" ]]; then vprint " Failed" - if [[ $OSNAME = "Darwin" ]]; then - vprint " Method: Mac Quartz mdls" - getPageSizeMdls - else - vprint " Method: Linux PdfInfo" - getPageSizePdfInfo - fi + vprint " Method: Mac Quartz mdls" + getPageSizeMdls fi - - if [[ -z $PGWIDTH && -z $PGHEIGHT ]]; then + + if pageSizeIsInvalid; then + vprint " Failed" + vprint " Method: PDFInfo" + getPageSizePdfInfo + fi + + if pageSizeIsInvalid; then vprint " Failed" vprint " Method: ImageMagick's Identify" getPageSizeImagemagick fi - - if [[ -z $PGWIDTH && -z $PGHEIGHT ]]; then + + if pageSizeIsInvalid; then vprint " Failed" - echo "Error when detecting PDF paper size!" - echo "All methods of detection failed" - echo "You may want to install pdfinfo or imagemagick" - exit 17 + printError "Error when detecting PDF paper size!" + printError "All methods of detection failed" + printError "You may want to install pdfinfo or imagemagick" + exit $EXIT_INVALID_PAGE_SIZE_DETECTED fi + + return $TRUE } +vPrintSourcePageSizes() { + vprint " $1 Width: $PGWIDTH postscript-points" + vprint "$1 Height: $PGHEIGHT postscript-points" +} -# Parse options -while getopts ":vhVs:m:" o; do - case "${o}" in - v) - ((VERBOSE++)) - ;; - h) - printHelp - exit 0 - ;; - V) - printVersion - exit 0 - ;; - s) - parseScale ${OPTARG} - ;; - m) - parseMode ${OPTARG} - ;; - *) - usage - ;; - esac -done -shift $((OPTIND-1)) +# Returns $TRUE if $PGWIDTH OR $PGWIDTH are empty or NOT an Integer, false otherwise +pageSizeIsInvalid() { + if isNotAnInteger "$PGWIDTH" || isNotAnInteger "$PGHEIGHT"; then + return $TRUE + fi + return $FALSE +} +isAnInteger() { + case $1 in + ''|*[!0-9]*) return $FALSE ;; + *) return $TRUE ;; + esac +} +isNotAnInteger() { + case $1 in + ''|*[!0-9]*) return $TRUE ;; + *) return $FALSE ;; + esac +} -######### START EXECUTION -#Intro message -vprint "$(basename $0) v$VERSION - Verbose execution" +# Prints usage info +usage() { + [[ "$2" != 'nobanner' ]] && printVersion 2 + [[ ! -z "$1" ]] && printError "$1" + printError "Usage: $PDFSCALE_NAME [-v] [-s ] [-m ] [outfile.pdf]" + printError "Try: $PDFSCALE_NAME -h # for help" +} + + +# Prints Verbose information +vprint() { + [[ $VERBOSE -eq 0 ]] && return 0 + timestamp="" + [[ $VERBOSE -gt 1 ]] && timestamp="$(date +%Y-%m-%d:%H:%M:%S) | " + echo "$timestamp$1" +} + + +# Prints dependency information and aborts execution +printDependency() { + #printVersion 2 + local brewName="$1" + [[ "$1" = 'pdfinfo' && "$OSNAME" = "Darwin" ]] && brewName="xpdf" + printError $'\n'"ERROR! You need to install the package '$1'"$'\n' + printError "Linux apt-get.: sudo apt-get install $1" + printError "Linux yum.....: sudo yum install $1" + printError "MacOS homebrew: brew install $brewName" + printError $'\n'"Aborting..." + exit $EXIT_MISSING_DEPENDENCY +} + +# Prints initialization errors and aborts execution +initError() { + local errStr="$1" + local exitStat=$2 + [[ -z "$exitStat" ]] && exitStat=$EXIT_ERROR + usage "ERROR! $errStr" "$3" + exit $exitStat +} +# Prints to stderr +printError() { + echo >&2 "$@" +} -# Dependencies -vprint "Checking for ghostscript and bcmath" -command -v gs >/dev/null 2>&1 || printDependency 'ghostscript' -command -v bc >/dev/null 2>&1 || printDependency 'bc' -if [[ $MODE = "IDENTIFY" ]]; then - vprint "Checking for imagemagick's identify" - command -v identify >/dev/null 2>&1 || printDependency 'imagemagick' -fi -if [[ $MODE = "PDFINFO" ]]; then - vprint "Checking for pdfinfo" - command -v pdfinfo >/dev/null 2>&1 || printDependency 'pdfinfo' -fi +# Returns $TRUE if $1 has a .pdf extension, false otherwsie +isPDF() { + [[ "$1" =~ ^..*\.pdf$ ]] && return $TRUE + return $FALSE +} -# Get dependency binaries -GSBIN="$(which gs 2>/dev/null)" -BCBIN="$(which bc 2>/dev/null)" -IDBIN=$(which identify 2>/dev/null) -if [[ $OSNAME = "Darwin" ]]; then - MDLSBIN="$(which mdls 2>/dev/null)" -else - PDFINFOBIN="$(which pdfinfo 2>/dev/null)" -fi +# Returns $TRUE if $1 is a file, false otherwsie +isFile() { + [[ -f "$1" ]] && return $TRUE + return $FALSE +} +# Returns $TRUE if $1 is NOT a file, false otherwsie +notIsFile() { + [[ -f "$1" ]] && return $FALSE + return $TRUE +} -# Verbose scale info -vprint " Scale factor: $SCALE" +# Returns $TRUE if $1 is executable, false otherwsie +isExecutable() { + [[ -x "$1" ]] && return $TRUE + return $FALSE +} +# Returns $TRUE if $1 is NOT executable, false otherwsie +notIsExecutable() { + [[ -x "$1" ]] && return $FALSE + return $TRUE +} -# Validate args -[[ $# -lt 1 ]] && { usage; exit 1; } -INFILEPDF="$1" -[[ "$INFILEPDF" =~ ^..*\.pdf$ ]] || { usage; exit 2; } -[[ -f "$INFILEPDF" ]] || { echo "Error! File not found: $INFILEPDF"; exit 3; } -vprint " Input file: $INFILEPDF" +# Returns $TRUE if $1 is a file and executable, false otherwsie +isAvailable() { + if isFile "$1" && isExecutable "$1"; then + return $TRUE + fi + return $FALSE +} +# Returns $TRUE if $1 is NOT a file or NOT executable, false otherwsie +notIsAvailable() { + if notIsFile "$1" || notIsExecutable "$1"; then + return $TRUE + fi + return $FALSE +} -# Parse output filename -if [[ -z $2 ]]; then - OUTFILEPDF="${INFILEPDF%.pdf}.SCALED.pdf" -else - OUTFILEPDF="${2%.pdf}.pdf" -fi -vprint " Output file: $OUTFILEPDF" +# Loads external dependencies and checks for errors +loadDeps() { + GSBIN="$(which gs 2>/dev/null)" + BCBIN="$(which bc 2>/dev/null)" + IDBIN=$(which identify 2>/dev/null) + MDLSBIN="$(which mdls 2>/dev/null)" + PDFINFOBIN="$(which pdfinfo 2>/dev/null)" + + vprint "Checking for ghostscript and bcmath" + if notIsAvailable "$GSBIN"; then printDependency 'ghostscript'; fi + if notIsAvailable "$BCBIN"; then printDependency 'bc'; fi + + if [[ $MODE = "IDENTIFY" ]]; then + vprint "Checking for imagemagick's identify" + if notIsAvailable "$IDBIN"; then printDependency 'imagemagick'; fi + fi + if [[ $MODE = "PDFINFO" ]]; then + vprint "Checking for pdfinfo" + if notIsAvailable "$PDFINFOBIN"; then printDependency 'pdfinfo'; fi + fi + if [[ $MODE = "MDLS" ]]; then + vprint "Checking for MacOS mdls" + if notIsAvailable "$MDLSBIN"; then + initError 'mdls executable was not found! Is this even MacOS?' $EXIT_MAC_MDLS_NOT_FOUND 'nobanner' + fi + fi +} +# Main execution +main() { + printVersion 1 'verbose' + + #getScaledOutputName + + #Intro message + #vprint "$(basename $0) v$VERSION - Verbose execution" + + loadDeps + vprint " Input file: $INFILEPDF" + vprint " Output file: $OUTFILEPDF" + getPageSize + + + if isMixedMode; then + vprint " Mixed Tasks: Resize & Scale" + vprint " Scale factor: $SCALE" + vPrintSourcePageSizes ' Source' + outputFile="$OUTFILEPDF" # backup outFile name + tempFile="${OUTFILEPDF%.pdf}.__TEMP__.pdf" # set a temp file name + OUTFILEPDF="$tempFile" # set output to tmp file + pageResize # resize to tmp file + INFILEPDF="$tempFile" # get tmp file as input + OUTFILEPDF="$outputFile" # reset final target + PGWIDTH=$RESIZE_WIDTH # we already know the new page size + PGHEIGHT=$RESIZE_HEIGHT # from the last command (Resize) + vPrintSourcePageSizes ' New' + pageScale # scale the resized pdf + # remove tmp file + rm "$tempFile" >/dev/null 2>&1 || printError "Error when removing temporary file: $tempFile" + elif isResizeMode; then + vprint " Single Task: Resize PDF Paper" + vprint " Scale factor: Disabled (resize only)" + vPrintSourcePageSizes ' Source' + pageResize + else + local scaleMode="" + vprint " Single Task: Scale PDF Contents" + isManualScaledMode && scaleMode='(manual)' || scaleMode='(auto)' + vprint " Scale factor: $SCALE $scaleMode" + vPrintSourcePageSizes ' Source' + pageScale + fi + + #pageScale + #pageResize +} -getPageSize -vprint " Width: $PGWIDTH postscript-points" -vprint " Height: $PGHEIGHT postscript-points" +# Parse options +getOptions() { + while getopts ":vhVs:m:r:p" o; do + case "${o}" in + v) + ((VERBOSE++)) + ;; + h) + printHelp + exit $EXIT_SUCCESS + ;; + V) + printVersion + exit $EXIT_SUCCESS + ;; + s) + parseScale ${OPTARG} + ;; + m) + parseMode ${OPTARG} + ;; + r) + parsePaperResize ${OPTARG} + ;; + p) + printPaperInfo + exit $EXIT_SUCCESS + ;; + *) + initError "Invalid Option: -$OPTARG" $EXIT_INVALID_OPTION + ;; + esac + done + shift $((OPTIND-1)) + + # Validate input PDF file + INFILEPDF="$1" + isEmpty "$INFILEPDF" && initError "Input file is empty!" $EXIT_NO_INPUT_FILE + isPDF "$INFILEPDF" || initError "Input file is not a PDF file: $INFILEPDF" $EXIT_INPUT_NOT_PDF + isFile "$INFILEPDF" || initError "Input file not found: $INFILEPDF" $EXIT_FILE_NOT_FOUND + + if isEmpty "$2"; then + if isMixedMode; then + OUTFILEPDF="${INFILEPDF%.pdf}.$(uppercase $RESIZE_PAPER_TYPE).SCALED.pdf" + elif isResizeMode; then + OUTFILEPDF="${INFILEPDF%.pdf}.$(uppercase $RESIZE_PAPER_TYPE).pdf" + else + OUTFILEPDF="${INFILEPDF%.pdf}.SCALED.pdf" + fi + else + OUTFILEPDF="${2%.pdf}.pdf" + fi +} -# Compute translation factors (to center page. -XTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGWIDTH" | "$BCBIN") -YTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGHEIGHT" | "$BCBIN") -vprint " Translation X: $XTRANS" -vprint " Translation Y: $YTRANS" +# Runs the ghostscript scaling script +pageScale() { + # Compute translation factors (to center page). + XTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGWIDTH" | "$BCBIN") + YTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGHEIGHT" | "$BCBIN") + vprint " Translation X: $XTRANS" + vprint " Translation Y: $YTRANS" -# Do it. -"$GSBIN" \ + # Do it. + "$GSBIN" \ -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \ -dCompatibilityLevel="1.5" -dPDFSETTINGS="/printer" \ -dColorConversionStrategy=/LeaveColorUnchanged \ -dSubsetFonts=true -dEmbedAllFonts=true \ --dDEVICEWIDTH=$PGWIDTH -dDEVICEHEIGHT=$PGHEIGHT \ +-dDEVICEWIDTHPOINTS=$PGWIDTH -dDEVICEHEIGHTPOINTS=$PGHEIGHT \ -sOutputFile="$OUTFILEPDF" \ -c "<> setpagedevice" \ --f "$INFILEPDF" +-f "$INFILEPDF" & + wait ${!} +} + + +pageResize() { + getGSPaperSize "$RESIZE_PAPER_TYPE" + local tmpInverter="" + if [[ $PGWIDTH -gt $PGHEIGHT && $RESIZE_WIDTH -lt $RESIZE_HEIGHT ]]; then + vprint " Flip Detect: Wrong orientation!" + vprint " Inverting Width <-> Height" + tmpInverter=$RESIZE_HEIGHT + RESIZE_HEIGHT=$RESIZE_WIDTH + RESIZE_WIDTH=$tmpInverter + fi + vprint " Resizing to: $(uppercase $RESIZE_PAPER_TYPE) ( $RESIZE_WIDTH x $RESIZE_HEIGHT )" + + # Change page size + "$GSBIN" \ +-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \ +-dCompatibilityLevel="1.5" -dPDFSETTINGS="/printer" \ +-dColorConversionStrategy=/LeaveColorUnchanged \ +-dSubsetFonts=true -dEmbedAllFonts=true \ +-dDEVICEWIDTHPOINTS=$RESIZE_WIDTH -dDEVICEHEIGHTPOINTS=$RESIZE_HEIGHT \ +-dFIXEDMEDIA -dPDFFitPage \ +-sOutputFile="$OUTFILEPDF" \ +-f "$INFILEPDF" & + wait ${!} + +} + + +# Automatic name for SCALED pdf +getOutputName() { + + # Parse output filename for scaled files + if [[ -z $OUTFILEPDF ]]; then + OUTFILEPDF="${INFILEPDF%.pdf}.SCALED.pdf" + else + OUTFILEPDF="${OUTFILEPDF%.pdf}.pdf" + fi +} + +# Automatic name for SCALED pdf +getScaledOutputName() { + # Parse output filename for scaled files + if [[ -z $OUTFILEPDF ]]; then + OUTFILEPDF="${INFILEPDF%.pdf}.SCALED.pdf" + else + OUTFILEPDF="${OUTFILEPDF%.pdf}.pdf" + fi +} + +# Automatica name for RESIZED pdf +getResizedOutputName() { + # Parse output filename for scaled files + if [[ -z $OUTFILEPDF ]]; then + OUTFILEPDF="${INFILEPDF%.pdf}.$PAPER_RESIZE.pdf" + else + OUTFILEPDF="${OUTFILEPDF%.pdf}.pdf" + fi +} + + + + + +getPaperInfo() { + # name inchesW inchesH mmW mmH pointsW pointsH + sizesUS="\ +11x17 11.0 17.0 279 432 792 1224 +ledger 17.0 11.0 432 279 1224 792 +legal 8.5 14.0 216 356 612 1008 +letter 8.5 11.0 216 279 612 792 +lettersmall 8.5 11.0 216 279 612 792 +archE 36.0 48.0 914 1219 2592 3456 +archD 24.0 36.0 610 914 1728 2592 +archC 18.0 24.0 457 610 1296 1728 +archB 12.0 18.0 305 457 864 1296 +archA 9.0 12.0 229 305 648 864" + + sizesISO="\ +a0 33.1 46.8 841 1189 2384 3370 +a1 23.4 33.1 594 841 1684 2384 +a2 16.5 23.4 420 594 1191 1684 +a3 11.7 16.5 297 420 842 1191 +a4 8.3 11.7 210 297 595 842 +a4small 8.3 11.7 210 297 595 842 +a5 5.8 8.3 148 210 420 595 +a6 4.1 5.8 105 148 297 420 +a7 2.9 4.1 74 105 210 297 +a8 2.1 2.9 52 74 148 210 +a9 1.5 2.1 37 52 105 148 +a10 1.0 1.5 26 37 73 105 +isob0 39.4 55.7 1000 1414 2835 4008 +isob1 27.8 39.4 707 1000 2004 2835 +isob2 19.7 27.8 500 707 1417 2004 +isob3 13.9 19.7 353 500 1001 1417 +isob4 9.8 13.9 250 353 709 1001 +isob5 6.9 9.8 176 250 499 709 +isob6 4.9 6.9 125 176 354 499 +c0 36.1 51.1 917 1297 2599 3677 +c1 25.5 36.1 648 917 1837 2599 +c2 18.0 25.5 458 648 1298 1837 +c3 12.8 18.0 324 458 918 1298 +c4 9.0 12.8 229 324 649 918 +c5 6.4 9.0 162 229 459 649 +c6 4.5 6.4 114 162 323 459" + + sizesJIS="\ +jisb0 NA NA 1030 1456 NA NA +jisb1 NA NA 728 1030 NA NA +jisb2 NA NA 515 728 NA NA +jisb3 NA NA 364 515 NA NA +jisb4 NA NA 257 364 NA NA +jisb5 NA NA 182 257 NA NA +jisb6 NA NA 128 182 NA NA" + + sizesOther="\ +flsa 8.5 13.0 216 330 612 936 +flse 8.5 13.0 216 330 612 936 +halfletter 5.5 8.5 140 216 396 612 +hagaki 3.9 5.8 100 148 283 420" + + sizesAll="\ +$sizesUS +$sizesISO +$sizesJIS +$sizesOther" + +} + +getGSPaperSize() { + isEmpty "$sizesall" && getPaperInfo + while read l; do + local cols=($l) + if [[ "$1" == ${cols[0]} ]]; then + RESIZE_WIDTH=${cols[5]} + RESIZE_HEIGHT=${cols[6]} + return $TRUE + fi + done <<< "$sizesAll" +} + +getPaperNames() { + 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 \ +11x17 ledger legal letter lettersmall archE archD archC archB archA \ +jisb0 jisb1 jisb2 jisb3 jisb4 jisb5 jisb6 \ +flsa flse halfletter hagaki) +} + +printPaperNames() { + isEmpty "$paperNames" && getPaperNames + for i in "${!paperNames[@]}"; do + [[ $i -ne 0 && $((i % 5)) -eq 0 ]] && echo "" + ppN="$(uppercase ${paperNames[i]})" + printf "%-14s" "$ppN" + done + echo "" +} + +isPaperName() { + isEmpty "$1" && return $FALSE + isEmpty "$paperNames" && getPaperNames + for i in "${paperNames[@]}"; do + [[ "$i" = "$1" ]] && return $TRUE + done + return $FALSE +} + +printPaperInfo() { + printVersion + echo $'\n'"Valid Ghostscript Paper Sizes accepted"$'\n' + getPaperInfo + printPaperTable "ISO STANDARD" "$sizesISO"; echo + printPaperTable "US STANDARD" "$sizesUS"; echo + printPaperTable "JIS STANDARD" "$sizesJIS"; echo + printPaperTable "OTHERS" "$sizesOther"; echo +} + +printTableLine() { + echo '+-----------------------------------------------------------------+' +} + +printTableDivider() { + echo '+-----------------+-------+-------+-------+-------+-------+-------+' +} + +printTableHeader() { + echo '| Name | inchW | inchH | mm W | mm H | pts W | pts H |' +} + +printTableTitle() { + printf "| %-64s%s\n" "$1" '|' +} + +printPaperTable() { + printTableLine + printTableTitle "$1" + printTableLine + printTableHeader + printTableDivider + while read l; do + local cols=($l) + printf "| %-15s | %+5s | %+5s | %+5s | %+5s | %+5s | %+5s |\n" ${cols[*]}; + done <<< "$2" + printTableDivider +} + +parsePaperResize() { + isEmpty "$1" && initError 'Invalid Paper Type: (empty)' $EXIT_INVALID_PAPER_SIZE + local lowercasePaper="$(lowercase $1)" + ! isPaperName "$lowercasePaper" && initError "Invalid Paper Type: $1" $EXIT_INVALID_PAPER_SIZE + RESIZE_PAPER_TYPE="$lowercasePaper" +} + +isManualScaledMode() { + [[ $AUTOMATIC_SCALING -eq $TRUE ]] && return $FALSE + return $TRUE +} + +isResizeMode() { + isEmpty $RESIZE_PAPER_TYPE && return $FALSE + return $TRUE +} + +isMixedMode() { + isResizeMode && isManualScaledMode && return $TRUE + return $FALSE +} + + + +lowercaseChar() { + case "$1" in + [A-Z]) + n=$(printf "%d" "'$1") + n=$((n+32)) + printf \\$(printf "%o" "$n") + ;; + *) + printf "%s" "$1" + ;; + esac +} + +lowercase() { + word="$@" + for((i=0;i<${#word};i++)) + do + ch="${word:$i:1}" + lowercaseChar "$ch" + done +} + + + +uppercaseChar(){ + case "$1" in + [a-z]) + n=$(printf "%d" "'$1") + n=$((n-32)) + printf \\$(printf "%o" "$n") + ;; + *) + printf "%s" "$1" + ;; + esac +} + +uppercase() { + word="$@" + for((i=0;i<${#word};i++)) + do + ch="${word:$i:1}" + uppercaseChar "$ch" + done +} + + + +#printPaperInfo +#printPaperNames + +#echo "----" +#isPaperName a4s; echo $? + + + + + +####----------Print-Program-Information----------#### + +# Prints version +printVersion() { + local vStr="" + [[ "$2" = 'verbose' ]] && vStr=" - Verbose Execution" + if [[ $1 -eq 2 ]]; then + printError "$PDFSCALE_NAME v$VERSION$vStr" + else + echo "$PDFSCALE_NAME v$VERSION$vStr" + fi +} + + +# Prints help info +printHelp() { + printVersion + local paperList="$(printPaperNames)" + echo " +Usage: $PDFSCALE_NAME [-v] [-s ] [-m ] [-r ] [outfile.pdf] + $PDFSCALE_NAME -p + $PDFSCALE_NAME -h + $PDFSCALE_NAME -V + +Parameters: + -v Verbose mode, prints extra information + Use twice for timestamp + -h Print this help to screen and exits + -V Prints version to screen and exits + -m Page size Detection mode + May disable the Adaptive Mode + -s Changes the scaling factor or forces scaling + Defaults: $SCALE / no scaling (resize mode) + MUST be a number bigger than zero + Eg. -s 0.8 for 80% of the original size + -r Triggers the Resize Paper Mode + Resize PDF paper proportionally + Must be a valid Ghostscript paper name + -p Prints Ghostscript paper info tables to screen + +Scaling Mode: +The default mode of operation is scaling mode with fixed paper +size and scaling pre-set to $SCALE. By not using the resize mode +you are using scaling mode. + +Resize Paper Mode: +Disables the default scaling factor! ($SCALE) +Alternative mode of operation to change the PDF paper +proportionally. Will fit-to-page. + +Mixed Mode: +In mixed mode both the -s option and -r option must be specified. +The PDF will be both scaled and have the paper type changed. + +Output filename: +The output filename is optional. If no file name is passed +the output file will have the same name/destination of the +input file with added suffixes: + .SCALED.pdf is added to scaled files + ..pdf is added to resized files + ..SCALED.pdf is added in mixed mode + +Page Detection Modes: + a, adaptive Default mode, tries all the methods below + c, cat+grep Forces the use of the cat + grep method + m, mdls Forces the use of MacOS Quartz mdls + p, pdfinfo Forces the use of PDFInfo + i, identify Forces the use of ImageMagick's Identify + +Valid Ghostscript Paper Names: +$paperList + +Notes: + - Adaptive Page size detection will try different modes until + it gets a page size. You can force a mode with -m 'mode'. + - Options must be passed before the file names to be parsed. + - Having the extension .pdf on the output file name is optional, + it will be added if not present. + - File and folder names with spaces should be quoted or escaped. + - The scaling is centered and using a scale bigger than 1 may + result on cropping parts of the pdf. + +Examples: + $PDFSCALE_NAME myPdfFile.pdf + $PDFSCALE_NAME myPdfFile.pdf myScaledPdf + $PDFSCALE_NAME -v -v myPdfFile.pdf + $PDFSCALE_NAME -s 0.85 myPdfFile.pdf myScaledPdf.pdf + $PDFSCALE_NAME -m pdfinfo -s 0.80 -v myPdfFile.pdf + $PDFSCALE_NAME -v -v -m i -s 0.7 myPdfFile.pdf + $PDFSCALE_NAME -h +" +} + + + + + + + + + + +######### START EXECUTION + +getOptions "${@}" +main +exit $? + From fa59438ac1b8e443265ed884292a113b255e6ad2 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sat, 13 May 2017 20:33:31 -0300 Subject: [PATCH 02/59] First readme for v2.0.0 --- README.md | 173 +++++++++++++++++++++++++++++++++++++--------------- pdfScale.sh | 33 ---------- 2 files changed, 125 insertions(+), 81 deletions(-) diff --git a/README.md b/README.md index a54b296..5de6ebb 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,16 @@ # pdfScale.sh -Bash Script to scale PDFs from the command line. -Uses ghostscript to create a scaled version of the pdf input. -The "paper" size does not change, just the elements are resized. +Bash Script to scale and resize PDFs from the command line. +Uses ghostscript to create a scaled and or resized version of the pdf input. +In `scaling mode`, the PDF paper size does not change, just the elements are scaled. +In `resize mode`, the PDF paper will be changed and fit-to-page will be applied. +In `mixed mode`, the PDF will first be `resized` then `scaled` with two Ghostscript calls. +A temporary file is used in `mixed mode`, at the target location. ## Dependencies The script uses `basename`, `cat`, `grep`, `bc`, `head` and `gs` (ghostscript). You probably have everything installed already, except for ghostscript. -Optional dependencies are `imagemagick`, `pdfinfo` and `mdls` (Mac). +Optional dependencies are `imagemagick`, `pdfinfo` and `mdls` (Mac). +This app is focused in `Bash`, so it will probably not run on other Shells. ##### apt-get ``` @@ -21,56 +25,107 @@ sudo yum install ghostscript bc brew install ghostscript ``` ##### Optionals -From version 1.4.x I decided to create an adaptive method of getting the pagesize. It will try different methods if the previous one fails. People can also force a specific mode of operation with the `-m` parameter. +Page Size detection is by default in Adaptive Mode. +It will try the following methods in sequence: The order of operation is as follows: 1. Try to get `/MediaBox` with `cat` + `grep` 2. Failed AND MacOS ? Try `mdls` - 3. Failed AND NOT MacOS ? Try `pdfinfo` + 3. Failed ? Try `pdfinfo` 4. Failed ? Try ImageMagick's `identify` 5. Failed ? `Exit` with error message The `cat`+`grep` method will fail on PDFs without a `/MediaBox`. - -You may install any of the above to be used in that case. +You may install any of the optionals to be used in that case. + +##### apt-get +``` +sudo apt-get install imagemagick pdfinfo +``` +##### yum +``` +sudo yum install imagemagick pdfinfo +``` +##### homebrew MacOS +``` +brew install imagemagick xpdf +``` + ## Help info ``` $ pdfscale -h -pdfscale v1.4.9 +pdfscale v2.0.0 -Usage: pdfscale [-v] [-s ] [-m ] [outfile.pdf] +Usage: pdfscale [-v] [-s ] [-m ] [-r ] [outfile.pdf] + pdfscale -p pdfscale -h pdfscale -V Parameters: -v Verbose mode, prints extra information - Use twice for even more information + Use twice for timestamp -h Print this help to screen and exits -V Prints version to screen and exits - -m Force a mode of page size detection + -m Page size Detection mode May disable the Adaptive Mode - -s Changes the scaling factor, defaults to 0.95 + -s Changes the scaling factor or forces scaling + Defaults: 0.95 / no scaling (resize mode) MUST be a number bigger than zero - Eg. -s 0.8 for 80% of the original size + Eg. -s 0.8 for 80% of the original size + -r Triggers the Resize Paper Mode + Resize PDF paper proportionally + Must be a valid Ghostscript paper name + -p Prints Ghostscript paper info tables to screen + +Scaling Mode: +The default mode of operation is scaling mode with fixed paper +size and scaling pre-set to 0.95. By not using the resize mode +you are using scaling mode. + +Resize Paper Mode: +Disables the default scaling factor! (0.95) +Alternative mode of operation to change the PDF paper +proportionally. Will fit-to-page. -Modes: +Mixed Mode: +In mixed mode both the -s option and -r option must be specified. +The PDF will be both scaled and have the paper type changed. + +Output filename: +The output filename is optional. If no file name is passed +the output file will have the same name/destination of the +input file with added suffixes: + .SCALED.pdf is added to scaled files + ..pdf is added to resized files + ..SCALED.pdf is added in mixed mode + +Page Detection Modes: a, adaptive Default mode, tries all the methods below c, cat+grep Forces the use of the cat + grep method m, mdls Forces the use of MacOS Quartz mdls - p, pdfinfo Forces the use of Linux PdfInfo + p, pdfinfo Forces the use of PDFInfo i, identify Forces the use of ImageMagick's Identify +Valid Ghostscript Paper Names: +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 11X17 LEDGER LEGAL LETTER +LETTERSMALL ARCHE ARCHD ARCHC ARCHB +ARCHA JISB0 JISB1 JISB2 JISB3 +JISB4 JISB5 JISB6 FLSA FLSE +HALFLETTER HAGAKI + Notes: - Adaptive Page size detection will try different modes until it gets a page size. You can force a mode with -m 'mode'. - Options must be passed before the file names to be parsed. - - The output filename is optional. If no file name is passed - the output file will have the same name/destination of the - input file, with .SCALED.pdf at the end (instead of just .pdf). - Having the extension .pdf on the output file name is optional, it will be added if not present. - - Should handle file names with spaces without problems. + - File and folder names with spaces should be quoted or escaped. - The scaling is centered and using a scale bigger than 1 may result on cropping parts of the pdf. @@ -86,35 +141,57 @@ Examples: ## Example runs ``` -$ pdfscale -m i -v -s 0.9 ../input.pdf -pdfscale v1.4.9 - Verbose execution +$ pdfscale -v -r a0 -s 1.05 ../mixsync\ manual\ v1-2-3.pdf +pdfscale v2.0.0 - Verbose Execution +Checking for ghostscript and bcmath + Input file: ../mixsync manual v1-2-3.pdf + Output file: ../mixsync manual v1-2-3.A0.SCALED.pdf + Get Page Size: Adaptive Enabled + Method: Cat + Grep + Mixed Tasks: Resize & Scale + Scale factor: 1.05 + Source Width: 842 postscript-points + Source Height: 595 postscript-points + Flip Detect: Wrong orientation! + Inverting Width <-> Height + Resizing to: A0 ( 3370 x 2384 ) + New Width: 3370 postscript-points + New Height: 2384 postscript-points + Translation X: -80.236330 + Translation Y: -56.760656 +``` +``` +$ pdfscale -v -v -s 0.9 ../input-nup.pdf "../my glorius PDF" +pdfscale v2.0.0 - Verbose Execution +2017-05-13:20:22:18 | Checking for ghostscript and bcmath +2017-05-13:20:22:18 | Input file: ../input-nup.pdf +2017-05-13:20:22:18 | Output file: ../my glorius PDF.pdf +2017-05-13:20:22:18 | Get Page Size: Adaptive Enabled +2017-05-13:20:22:18 | Method: Cat + Grep +2017-05-13:20:22:18 | Failed +2017-05-13:20:22:18 | Method: Mac Quartz mdls +2017-05-13:20:22:18 | Single Task: Scale PDF Contents +2017-05-13:20:22:18 | Scale factor: 0.9 (manual) +2017-05-13:20:22:18 | Source Width: 842 postscript-points +2017-05-13:20:22:18 | Source Height: 595 postscript-points +2017-05-13:20:22:18 | Translation X: 46.777310 +2017-05-13:20:22:18 | Translation Y: 33.055225 +``` +``` +$ pdfscale -v -r a2 "../mixsync manual v1-2-3.pdf" +pdfscale v2.0.0 - Verbose Execution Checking for ghostscript and bcmath -Checking for imagemagick's identify - Scale factor: 0.9 - Input file: ../input.pdf - Output file: ../input.SCALED.pdf - Adaptive mode: Disabled - Method: ImageMagick's Identify - Width: 595 postscript-points - Height: 842 postscript-points - Translation X: 33.055225 - Translation Y: 46.777310 -``` -``` -$ pdfscale -v -v -s 0.5 ../input-nup.pdf ../nuptest -2017-02-22:07:56:38 | pdfscale v1.4.9 - Verbose execution -2017-02-22:07:56:38 | Checking for ghostscript and bcmath -2017-02-22:07:56:38 | Scale factor: 0.5 -2017-02-22:07:56:38 | Input file: ../input-nup.pdf -2017-02-22:07:56:39 | Output file: ../nuptest.pdf -2017-02-22:07:56:39 | Adaptive mode: Enabled -2017-02-22:07:56:39 | Method: Cat + Grep -2017-02-22:07:56:39 | Failed -2017-02-22:07:56:39 | Method: Mac Quartz mdls -2017-02-22:07:56:39 | Width: 842 postscript-points -2017-02-22:07:56:39 | Height: 595 postscript-points -2017-02-22:07:56:39 | Translation X: 421.000000 -2017-02-22:07:56:39 | Translation Y: 297.500000 + Input file: ../mixsync manual v1-2-3.pdf + Output file: ../mixsync manual v1-2-3.A2.pdf + Get Page Size: Adaptive Enabled + Method: Cat + Grep + Single Task: Resize PDF Paper + Scale factor: Disabled (resize only) + Source Width: 842 postscript-points + Source Height: 595 postscript-points + Flip Detect: Wrong orientation! + Inverting Width <-> Height + Resizing to: A2 ( 1684 x 1191 ) ``` ## System Install diff --git a/pdfScale.sh b/pdfScale.sh index d3cf6fa..2537b3b 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -653,39 +653,6 @@ pageResize() { } -# Automatic name for SCALED pdf -getOutputName() { - - # Parse output filename for scaled files - if [[ -z $OUTFILEPDF ]]; then - OUTFILEPDF="${INFILEPDF%.pdf}.SCALED.pdf" - else - OUTFILEPDF="${OUTFILEPDF%.pdf}.pdf" - fi -} - -# Automatic name for SCALED pdf -getScaledOutputName() { - # Parse output filename for scaled files - if [[ -z $OUTFILEPDF ]]; then - OUTFILEPDF="${INFILEPDF%.pdf}.SCALED.pdf" - else - OUTFILEPDF="${OUTFILEPDF%.pdf}.pdf" - fi -} - -# Automatica name for RESIZED pdf -getResizedOutputName() { - # Parse output filename for scaled files - if [[ -z $OUTFILEPDF ]]; then - OUTFILEPDF="${INFILEPDF%.pdf}.$PAPER_RESIZE.pdf" - else - OUTFILEPDF="${OUTFILEPDF%.pdf}.pdf" - fi -} - - - getPaperInfo() { From e5af08ffe69bfba2051927ccfe103389778861ed Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sat, 13 May 2017 20:34:26 -0300 Subject: [PATCH 03/59] Readme v2.0.0 tunning --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 5de6ebb..df516a1 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # pdfScale.sh Bash Script to scale and resize PDFs from the command line. Uses ghostscript to create a scaled and or resized version of the pdf input. + In `scaling mode`, the PDF paper size does not change, just the elements are scaled. In `resize mode`, the PDF paper will be changed and fit-to-page will be applied. In `mixed mode`, the PDF will first be `resized` then `scaled` with two Ghostscript calls. From b30d058a02fd79b89802937b573e8598603d449d Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sat, 13 May 2017 20:35:51 -0300 Subject: [PATCH 04/59] Readme v2.0.0 tunning --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index df516a1..8b7cfd3 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,6 @@ brew install ghostscript ##### Optionals Page Size detection is by default in Adaptive Mode. It will try the following methods in sequence: - -The order of operation is as follows: 1. Try to get `/MediaBox` with `cat` + `grep` 2. Failed AND MacOS ? Try `mdls` 3. Failed ? Try `pdfinfo` From bc8354de95ecc09a9b7de749371471d12f830369 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 01:13:12 -0300 Subject: [PATCH 05/59] Readme v2.0.0 tunning --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8b7cfd3..88d04f0 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,10 @@ It will try the following methods in sequence: 5. Failed ? `Exit` with error message The `cat`+`grep` method will fail on PDFs without a `/MediaBox`. -You may install any of the optionals to be used in that case. +You may install any of the optionals to be used in that case. + +MacOS is fine using `mdls` if the metadata of the file is accurate. +The metadata is generated automatically by the OS (SpolLight) ##### apt-get ``` From ed77bf53bfae5b1f341ddf13cfd688278e9ca6ec Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 01:13:58 -0300 Subject: [PATCH 06/59] Readme v2.0.0 tunning --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 88d04f0..1e47754 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ The `cat`+`grep` method will fail on PDFs without a `/MediaBox`. You may install any of the optionals to be used in that case. MacOS is fine using `mdls` if the metadata of the file is accurate. -The metadata is generated automatically by the OS (SpolLight) +The metadata is generated automatically by the OS (Spotlight) ##### apt-get ``` From 32569b8dc1c1ffbbd10d0dc67d2a61501c067385 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 01:27:31 -0300 Subject: [PATCH 07/59] Readme v2.0.0 tunning --- README.md | 82 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/README.md b/README.md index 1e47754..fffcec1 100644 --- a/README.md +++ b/README.md @@ -195,6 +195,88 @@ Checking for ghostscript and bcmath Inverting Width <-> Height Resizing to: A2 ( 1684 x 1191 ) ``` +## GhostScript Paper Tables +``` +$ pdfscale -p +pdfscale v2.0.0 + +Valid Ghostscript Paper Sizes accepted + ++-----------------------------------------------------------------+ +| ISO STANDARD | ++-----------------------------------------------------------------+ +| Name | inchW | inchH | mm W | mm H | pts W | pts H | ++-----------------+-------+-------+-------+-------+-------+-------+ +| a0 | 33.1 | 46.8 | 841 | 1189 | 2384 | 3370 | +| a1 | 23.4 | 33.1 | 594 | 841 | 1684 | 2384 | +| a2 | 16.5 | 23.4 | 420 | 594 | 1191 | 1684 | +| a3 | 11.7 | 16.5 | 297 | 420 | 842 | 1191 | +| a4 | 8.3 | 11.7 | 210 | 297 | 595 | 842 | +| a4small | 8.3 | 11.7 | 210 | 297 | 595 | 842 | +| a5 | 5.8 | 8.3 | 148 | 210 | 420 | 595 | +| a6 | 4.1 | 5.8 | 105 | 148 | 297 | 420 | +| a7 | 2.9 | 4.1 | 74 | 105 | 210 | 297 | +| a8 | 2.1 | 2.9 | 52 | 74 | 148 | 210 | +| a9 | 1.5 | 2.1 | 37 | 52 | 105 | 148 | +| a10 | 1.0 | 1.5 | 26 | 37 | 73 | 105 | +| isob0 | 39.4 | 55.7 | 1000 | 1414 | 2835 | 4008 | +| isob1 | 27.8 | 39.4 | 707 | 1000 | 2004 | 2835 | +| isob2 | 19.7 | 27.8 | 500 | 707 | 1417 | 2004 | +| isob3 | 13.9 | 19.7 | 353 | 500 | 1001 | 1417 | +| isob4 | 9.8 | 13.9 | 250 | 353 | 709 | 1001 | +| isob5 | 6.9 | 9.8 | 176 | 250 | 499 | 709 | +| isob6 | 4.9 | 6.9 | 125 | 176 | 354 | 499 | +| c0 | 36.1 | 51.1 | 917 | 1297 | 2599 | 3677 | +| c1 | 25.5 | 36.1 | 648 | 917 | 1837 | 2599 | +| c2 | 18.0 | 25.5 | 458 | 648 | 1298 | 1837 | +| c3 | 12.8 | 18.0 | 324 | 458 | 918 | 1298 | +| c4 | 9.0 | 12.8 | 229 | 324 | 649 | 918 | +| c5 | 6.4 | 9.0 | 162 | 229 | 459 | 649 | +| c6 | 4.5 | 6.4 | 114 | 162 | 323 | 459 | ++-----------------+-------+-------+-------+-------+-------+-------+ + ++-----------------------------------------------------------------+ +| US STANDARD | ++-----------------------------------------------------------------+ +| Name | inchW | inchH | mm W | mm H | pts W | pts H | ++-----------------+-------+-------+-------+-------+-------+-------+ +| 11x17 | 11.0 | 17.0 | 279 | 432 | 792 | 1224 | +| ledger | 17.0 | 11.0 | 432 | 279 | 1224 | 792 | +| legal | 8.5 | 14.0 | 216 | 356 | 612 | 1008 | +| letter | 8.5 | 11.0 | 216 | 279 | 612 | 792 | +| lettersmall | 8.5 | 11.0 | 216 | 279 | 612 | 792 | +| archE | 36.0 | 48.0 | 914 | 1219 | 2592 | 3456 | +| archD | 24.0 | 36.0 | 610 | 914 | 1728 | 2592 | +| archC | 18.0 | 24.0 | 457 | 610 | 1296 | 1728 | +| archB | 12.0 | 18.0 | 305 | 457 | 864 | 1296 | +| archA | 9.0 | 12.0 | 229 | 305 | 648 | 864 | ++-----------------+-------+-------+-------+-------+-------+-------+ + ++-----------------------------------------------------------------+ +| JIS STANDARD | ++-----------------------------------------------------------------+ +| Name | inchW | inchH | mm W | mm H | pts W | pts H | ++-----------------+-------+-------+-------+-------+-------+-------+ +| jisb0 | NA | NA | 1030 | 1456 | NA | NA | +| jisb1 | NA | NA | 728 | 1030 | NA | NA | +| jisb2 | NA | NA | 515 | 728 | NA | NA | +| jisb3 | NA | NA | 364 | 515 | NA | NA | +| jisb4 | NA | NA | 257 | 364 | NA | NA | +| jisb5 | NA | NA | 182 | 257 | NA | NA | +| jisb6 | NA | NA | 128 | 182 | NA | NA | ++-----------------+-------+-------+-------+-------+-------+-------+ + ++-----------------------------------------------------------------+ +| OTHERS | ++-----------------------------------------------------------------+ +| Name | inchW | inchH | mm W | mm H | pts W | pts H | ++-----------------+-------+-------+-------+-------+-------+-------+ +| flsa | 8.5 | 13.0 | 216 | 330 | 612 | 936 | +| flse | 8.5 | 13.0 | 216 | 330 | 612 | 936 | +| halfletter | 5.5 | 8.5 | 140 | 216 | 396 | 612 | +| hagaki | 3.9 | 5.8 | 100 | 148 | 283 | 420 | ++-----------------+-------+-------+-------+-------+-------+-------+ +``` ## System Install The installer will name the executable as `pdfscale` with no uppercase chars and without the `.sh` extension. From 267d4702dea55cc65a7ac36c7aeed666c3fea226 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 02:00:13 -0300 Subject: [PATCH 08/59] Adding aprox points for JIS papers --- README.md | 2 +- pdfScale.sh | 19 +++++++++++-------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index fffcec1..220cd04 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Uses ghostscript to create a scaled and or resized version of the pdf input. In `scaling mode`, the PDF paper size does not change, just the elements are scaled. In `resize mode`, the PDF paper will be changed and fit-to-page will be applied. In `mixed mode`, the PDF will first be `resized` then `scaled` with two Ghostscript calls. -A temporary file is used in `mixed mode`, at the target location. +A temporary file is used in `mixed mode`, at the target location. ## Dependencies The script uses `basename`, `cat`, `grep`, `bc`, `head` and `gs` (ghostscript). diff --git a/pdfScale.sh b/pdfScale.sh index 2537b3b..77aff15 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -698,13 +698,13 @@ c5 6.4 9.0 162 229 459 649 c6 4.5 6.4 114 162 323 459" sizesJIS="\ -jisb0 NA NA 1030 1456 NA NA -jisb1 NA NA 728 1030 NA NA -jisb2 NA NA 515 728 NA NA -jisb3 NA NA 364 515 NA NA -jisb4 NA NA 257 364 NA NA -jisb5 NA NA 182 257 NA NA -jisb6 NA NA 128 182 NA NA" +jisb0 NA NA 1030 1456 2920 4127 +jisb1 NA NA 728 1030 2064 2920 +jisb2 NA NA 515 728 1460 2064 +jisb3 NA NA 364 515 1032 1460 +jisb4 NA NA 257 364 729 1032 +jisb5 NA NA 182 257 516 729 +jisb6 NA NA 128 182 363 516" sizesOther="\ flsa 8.5 13.0 216 330 612 936 @@ -764,7 +764,7 @@ printPaperInfo() { getPaperInfo printPaperTable "ISO STANDARD" "$sizesISO"; echo printPaperTable "US STANDARD" "$sizesUS"; echo - printPaperTable "JIS STANDARD" "$sizesJIS"; echo + printPaperTable "JIS STANDARD *Aproximated Points" "$sizesJIS"; echo printPaperTable "OTHERS" "$sizesOther"; echo } @@ -819,6 +819,9 @@ isMixedMode() { return $FALSE } +mmToPoints() { + local calc=$(($1)) +} lowercaseChar() { From 56b8003f25ce600108357160dec200bcab1ca6e0 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 02:01:21 -0300 Subject: [PATCH 09/59] Readme v2.0.0 tunning --- README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 220cd04..366dec9 100644 --- a/README.md +++ b/README.md @@ -197,8 +197,8 @@ Checking for ghostscript and bcmath ``` ## GhostScript Paper Tables ``` -$ pdfscale -p -pdfscale v2.0.0 +$ ./pdfScale.sh -p +pdfScale.sh v2.0.0 Valid Ghostscript Paper Sizes accepted @@ -253,17 +253,17 @@ Valid Ghostscript Paper Sizes accepted +-----------------+-------+-------+-------+-------+-------+-------+ +-----------------------------------------------------------------+ -| JIS STANDARD | +| JIS STANDARD *Aproximated Points | +-----------------------------------------------------------------+ | Name | inchW | inchH | mm W | mm H | pts W | pts H | +-----------------+-------+-------+-------+-------+-------+-------+ -| jisb0 | NA | NA | 1030 | 1456 | NA | NA | -| jisb1 | NA | NA | 728 | 1030 | NA | NA | -| jisb2 | NA | NA | 515 | 728 | NA | NA | -| jisb3 | NA | NA | 364 | 515 | NA | NA | -| jisb4 | NA | NA | 257 | 364 | NA | NA | -| jisb5 | NA | NA | 182 | 257 | NA | NA | -| jisb6 | NA | NA | 128 | 182 | NA | NA | +| jisb0 | NA | NA | 1030 | 1456 | 2920 | 4127 | +| jisb1 | NA | NA | 728 | 1030 | 2064 | 2920 | +| jisb2 | NA | NA | 515 | 728 | 1460 | 2064 | +| jisb3 | NA | NA | 364 | 515 | 1032 | 1460 | +| jisb4 | NA | NA | 257 | 364 | 729 | 1032 | +| jisb5 | NA | NA | 182 | 257 | 516 | 729 | +| jisb6 | NA | NA | 128 | 182 | 363 | 516 | +-----------------+-------+-------+-------+-------+-------+-------+ +-----------------------------------------------------------------+ From 62eaba1ad44fd538bf03b35f38718c89b04d50f6 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 14:24:25 -0300 Subject: [PATCH 10/59] Cleanning some comments --- pdfScale.sh | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/pdfScale.sh b/pdfScale.sh index 77aff15..5ffd14f 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -15,11 +15,9 @@ # PAGESIZE LOGIC # 1- Try to get Mediabox with CAT/GREP # 2- MacOS => try to use mdls -# Linux => try to use pdfinfo -# 3- Try to use identify (imagemagick) -# 4- Fail -# Remove postscript method, -# may have licensing problems +# 3- Try to use pdfinfo +# 4- Try to use identify (imagemagick) +# 5- Fail ################################################### From c26863f33e7ccd7edc699c2e5d2f04005f84cf73 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 14:32:23 -0300 Subject: [PATCH 11/59] small fix to mdls fail detection --- pdfScale.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pdfScale.sh b/pdfScale.sh index 5ffd14f..dd2128d 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -175,9 +175,9 @@ getPageSizeMdls() { identify=${identify//$'\t'/ } # change tab to space identify=($identify) # make it an array - if [[ "${identify[5]}" = "(null)" || "${identify[5]}" = "(null)" ]] && isNotAdaptiveMode; then + if [[ "${identify[5]}" = "(null)" || "${identify[2]}" = "(null)" ]] && isNotAdaptiveMode; then notAdaptiveFailed "There was no metadata to read from the file! Is Spotlight OFF?" - elif [[ "${identify[5]}" = "(null)" || "${identify[5]}" = "(null)" ]] && isAdaptiveMode; then + elif [[ "${identify[5]}" = "(null)" || "${identify[2]}" = "(null)" ]] && isAdaptiveMode; then return $FALSE fi From 12598cbc20ae3e93f80c91b724802bfb02dcca9e Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 19:15:45 -0300 Subject: [PATCH 12/59] Code cleanup, moved functions to organize a bit better, added some comments, tabs to spaces. Seems almost ready to release --- pdfScale.sh | 933 ++++++++++++++++++++++++++-------------------------- 1 file changed, 475 insertions(+), 458 deletions(-) diff --git a/pdfScale.sh b/pdfScale.sh index dd2128d..b2f66c1 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -5,6 +5,7 @@ # Scale PDF to specified percentage of original size. # # Gustavo Arnosti Neves - 2016 / 07 / 10 +# Latest Version - 2017 / 05 / 14 # # This script: https://github.com/tavinus/pdfScale # Based on: http://ma.juii.net/blog/scale-page-content-of-pdf-files @@ -22,18 +23,18 @@ VERSION="2.0.0" -SCALE="0.95" # scaling factor (0.95 = 95%, e.g.) -VERBOSE=0 # verbosity Level +SCALE="0.95" # scaling factor (0.95 = 95%, e.g.) +VERBOSE=0 # verbosity Level PDFSCALE_NAME="$(basename $0)" # simplified name of this script -# Set with which later -GSBIN="" # GhostScript Binary -BCBIN="" # BC Math Binary -IDBIN="" # Identify Binary -PDFINFOBIN="" # PDF Info Binary -MDLSBIN="" # MacOS mdls Binary +# SET AND VALIDATED LATER +GSBIN="" # GhostScript Binary +BCBIN="" # BC Math Binary +IDBIN="" # Identify Binary +PDFINFOBIN="" # PDF Info Binary +MDLSBIN="" # MacOS mdls Binary -OSNAME="$(uname 2>/dev/null)" # Check where we are running +OSNAME="$(uname 2>/dev/null)" # Check where we are running LC_MEASUREMENT="C" # To make sure our numbers have .decimals LC_ALL="C" # Some languages use , as decimal token @@ -52,8 +53,7 @@ PGHEIGHT="" RESIZE_WIDTH="" RESIZE_HEIGHT="" - -# Exit flags +### EXIT FLAGS EXIT_SUCCESS=0 EXIT_ERROR=1 EXIT_INVALID_PAGE_SIZE_DETECTED=10 @@ -71,11 +71,141 @@ EXIT_INVALID_PAPER_SIZE=50 +############################# MAIN ############################# + +# Main function called at the end +main() { + printVersion 1 'verbose' + loadDeps + vprint " Input file: $INFILEPDF" + vprint " Output file: $OUTFILEPDF" + getPageSize + + if isMixedMode; then + vprint " Mixed Tasks: Resize & Scale" + vprint " Scale factor: $SCALE" + vPrintSourcePageSizes ' Source' + outputFile="$OUTFILEPDF" # backup outFile name + tempFile="${OUTFILEPDF%.pdf}.__TEMP__.pdf" # set a temp file name + OUTFILEPDF="$tempFile" # set output to tmp file + pageResize # resize to tmp file + INFILEPDF="$tempFile" # get tmp file as input + OUTFILEPDF="$outputFile" # reset final target + PGWIDTH=$RESIZE_WIDTH # we already know the new page size + PGHEIGHT=$RESIZE_HEIGHT # from the last command (Resize) + vPrintSourcePageSizes ' New' + pageScale # scale the resized pdf + # remove tmp file + rm "$tempFile" >/dev/null 2>&1 || printError "Error when removing temporary file: $tempFile" + elif isResizeMode; then + vprint " Single Task: Resize PDF Paper" + vprint " Scale factor: Disabled (resize only)" + vPrintSourcePageSizes ' Source' + pageResize + else + local scaleMode="" + vprint " Single Task: Scale PDF Contents" + isManualScaledMode && scaleMode='(manual)' || scaleMode='(auto)' + vprint " Scale factor: $SCALE $scaleMode" + vPrintSourcePageSizes ' Source' + pageScale + fi + + return $EXIT_SUCCESS +} + + +########################## INITIALIZER ########################## + +# Loads external dependencies and checks for errors +loadDeps() { + GSBIN="$(which gs 2>/dev/null)" + BCBIN="$(which bc 2>/dev/null)" + IDBIN=$(which identify 2>/dev/null) + MDLSBIN="$(which mdls 2>/dev/null)" + PDFINFOBIN="$(which pdfinfo 2>/dev/null)" + + vprint "Checking for ghostscript and bcmath" + if notIsAvailable "$GSBIN"; then printDependency 'ghostscript'; fi + if notIsAvailable "$BCBIN"; then printDependency 'bc'; fi + + if [[ $MODE = "IDENTIFY" ]]; then + vprint "Checking for imagemagick's identify" + if notIsAvailable "$IDBIN"; then printDependency 'imagemagick'; fi + fi + if [[ $MODE = "PDFINFO" ]]; then + vprint "Checking for pdfinfo" + if notIsAvailable "$PDFINFOBIN"; then printDependency 'pdfinfo'; fi + fi + if [[ $MODE = "MDLS" ]]; then + vprint "Checking for MacOS mdls" + if notIsAvailable "$MDLSBIN"; then + initError 'mdls executable was not found! Is this even MacOS?' $EXIT_MAC_MDLS_NOT_FOUND 'nobanner' + fi + fi +} + + +######################### CLI OPTIONS ########################## + +# Parse options +getOptions() { + while getopts ":vhVs:m:r:p" o; do + case "${o}" in + v) + ((VERBOSE++)) + ;; + h) + printHelp + exit $EXIT_SUCCESS + ;; + V) + printVersion + exit $EXIT_SUCCESS + ;; + s) + parseScale ${OPTARG} + ;; + m) + parseMode ${OPTARG} + ;; + r) + parsePaperResize ${OPTARG} + ;; + p) + printPaperInfo + exit $EXIT_SUCCESS + ;; + *) + initError "Invalid Option: -$OPTARG" $EXIT_INVALID_OPTION + ;; + esac + done + shift $((OPTIND-1)) + + # Validate input PDF file + INFILEPDF="$1" + isEmpty "$INFILEPDF" && initError "Input file is empty!" $EXIT_NO_INPUT_FILE + isPDF "$INFILEPDF" || initError "Input file is not a PDF file: $INFILEPDF" $EXIT_INPUT_NOT_PDF + isFile "$INFILEPDF" || initError "Input file not found: $INFILEPDF" $EXIT_FILE_NOT_FOUND + + if isEmpty "$2"; then + if isMixedMode; then + OUTFILEPDF="${INFILEPDF%.pdf}.$(uppercase $RESIZE_PAPER_TYPE).SCALED.pdf" + elif isResizeMode; then + OUTFILEPDF="${INFILEPDF%.pdf}.$(uppercase $RESIZE_PAPER_TYPE).pdf" + else + OUTFILEPDF="${INFILEPDF%.pdf}.SCALED.pdf" + fi + else + OUTFILEPDF="${2%.pdf}.pdf" + fi +} # Parses and validates the scaling factor parseScale() { - AUTOMATIC_SCALING=$FALSE + AUTOMATIC_SCALING=$FALSE if ! [[ -n "$1" && "$1" =~ ^-?[0-9]*([.][0-9]+)?$ && (($1 > 0 )) ]] ; then printError "Invalid factor: $1" printError "The factor must be a floating point number greater than 0" @@ -85,6 +215,60 @@ parseScale() { SCALE=$1 } +###################### GHOSTSCRIPT CALLS ####################### + +# Runs the ghostscript scaling script +pageScale() { + # Compute translation factors (to center page). + XTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGWIDTH" | "$BCBIN") + YTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGHEIGHT" | "$BCBIN") + vprint " Translation X: $XTRANS" + vprint " Translation Y: $YTRANS" + + # Do it. + "$GSBIN" \ +-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \ +-dCompatibilityLevel="1.5" -dPDFSETTINGS="/printer" \ +-dColorConversionStrategy=/LeaveColorUnchanged \ +-dSubsetFonts=true -dEmbedAllFonts=true \ +-dDEVICEWIDTHPOINTS=$PGWIDTH -dDEVICEHEIGHTPOINTS=$PGHEIGHT \ +-sOutputFile="$OUTFILEPDF" \ +-c "<> setpagedevice" \ +-f "$INFILEPDF" & + wait ${!} +} + + +# Runs the ghostscript paper resize script +pageResize() { + getGSPaperSize "$RESIZE_PAPER_TYPE" + local tmpInverter="" + if [[ $PGWIDTH -gt $PGHEIGHT && $RESIZE_WIDTH -lt $RESIZE_HEIGHT ]]; then + vprint " Flip Detect: Wrong orientation!" + vprint " Inverting Width <-> Height" + tmpInverter=$RESIZE_HEIGHT + RESIZE_HEIGHT=$RESIZE_WIDTH + RESIZE_WIDTH=$tmpInverter + fi + vprint " Resizing to: $(uppercase $RESIZE_PAPER_TYPE) ( $RESIZE_WIDTH x $RESIZE_HEIGHT )" + + # Change page size + "$GSBIN" \ +-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \ +-dCompatibilityLevel="1.5" -dPDFSETTINGS="/printer" \ +-dColorConversionStrategy=/LeaveColorUnchanged \ +-dSubsetFonts=true -dEmbedAllFonts=true \ +-dDEVICEWIDTHPOINTS=$RESIZE_WIDTH -dDEVICEHEIGHTPOINTS=$RESIZE_HEIGHT \ +-dFIXEDMEDIA -dPDFFitPage \ +-sOutputFile="$OUTFILEPDF" \ +-f "$INFILEPDF" & + wait ${!} + +} + + + +################### PDF PAGE SIZE DETECTION #################### # Parse a forced mode of operation parseMode() { @@ -132,7 +316,7 @@ parseMode() { getPageSizeImagemagick() { # Sanity and Adaptive together if notIsFile "$IDBIN" && isNotAdaptiveMode; then - notAdaptiveFailed "Make sure you installed ImageMagick and have identify on your \$PATH" "ImageMagick's Identify" + notAdaptiveFailed "Make sure you installed ImageMagick and have identify on your \$PATH" "ImageMagick's Identify" elif notIsFile "$IDBIN" && isAdaptiveMode; then return $FALSE fi @@ -141,7 +325,7 @@ getPageSizeImagemagick() { local identify="$("$IDBIN" -format '%[fx:w] %[fx:h]BREAKME' "$INFILEPDF" 2>/dev/null)" if isEmpty "$identify" && isNotAdaptiveMode; then - notAdaptiveFailed "ImageMagicks's Identify returned an empty string!" + notAdaptiveFailed "ImageMagicks's Identify returned an empty string!" elif isEmpty "$identify" && isAdaptiveMode; then return $FALSE fi @@ -151,7 +335,7 @@ getPageSizeImagemagick() { PGWIDTH=$(printf '%.0f' "${identify[0]}") # assign PGHEIGHT=$(printf '%.0f' "${identify[1]}") # assign - return $TRUE + return $TRUE } @@ -159,7 +343,7 @@ getPageSizeImagemagick() { getPageSizeMdls() { # Sanity and Adaptive together if notIsFile "$MDLSBIN" && isNotAdaptiveMode; then - notAdaptiveFailed "Are you even trying this on a Mac?" "Mac Quartz mdls" + notAdaptiveFailed "Are you even trying this on a Mac?" "Mac Quartz mdls" elif notIsFile "$MDLSBIN" && isAdaptiveMode; then return $FALSE fi @@ -167,7 +351,7 @@ getPageSizeMdls() { local identify="$("$MDLSBIN" -mdls -name kMDItemPageHeight -name kMDItemPageWidth "$INFILEPDF" 2>/dev/null)" if isEmpty "$identify" && isNotAdaptiveMode; then - notAdaptiveFailed "Mac Quartz mdls returned an empty string!" + notAdaptiveFailed "Mac Quartz mdls returned an empty string!" elif isEmpty "$identify" && isAdaptiveMode; then return $FALSE fi @@ -175,8 +359,8 @@ getPageSizeMdls() { identify=${identify//$'\t'/ } # change tab to space identify=($identify) # make it an array - if [[ "${identify[5]}" = "(null)" || "${identify[2]}" = "(null)" ]] && isNotAdaptiveMode; then - notAdaptiveFailed "There was no metadata to read from the file! Is Spotlight OFF?" + if [[ "${identify[5]}" = "(null)" || "${identify[2]}" = "(null)" ]] && isNotAdaptiveMode; then + notAdaptiveFailed "There was no metadata to read from the file! Is Spotlight OFF?" elif [[ "${identify[5]}" = "(null)" || "${identify[2]}" = "(null)" ]] && isAdaptiveMode; then return $FALSE fi @@ -184,7 +368,7 @@ getPageSizeMdls() { PGWIDTH=$(printf '%.0f' "${identify[5]}") # assign PGHEIGHT=$(printf '%.0f' "${identify[2]}") # assign - return $TRUE + return $TRUE } @@ -192,7 +376,7 @@ getPageSizeMdls() { getPageSizePdfInfo() { # Sanity and Adaptive together if notIsFile "$PDFINFOBIN" && isNotAdaptiveMode; then - notAdaptiveFailed "Do you have pdfinfo installed and available on your \$PATH?" "Linux pdfinfo" + notAdaptiveFailed "Do you have pdfinfo installed and available on your \$PATH?" "Linux pdfinfo" elif notIsFile "$PDFINFOBIN" && isAdaptiveMode; then return $FALSE fi @@ -201,7 +385,7 @@ getPageSizePdfInfo() { local identify="$("$PDFINFOBIN" "$INFILEPDF" 2>/dev/null | grep -i 'Page size:' )" if isEmpty "$identify" && isNotAdaptiveMode; then - notAdaptiveFailed "Linux PdfInfo returned an empty string!" + notAdaptiveFailed "Linux PdfInfo returned an empty string!" elif isEmpty "$identify" && isAdaptiveMode; then return $FALSE fi @@ -212,7 +396,7 @@ getPageSizePdfInfo() { PGWIDTH=$(printf '%.0f' "${identify[0]}") # assign PGHEIGHT=$(printf '%.0f' "${identify[2]}") # assign - return $TRUE + return $TRUE } @@ -229,7 +413,7 @@ getPageSizeCatGrep() { # No page size data available if isEmpty "$mediaBox" && isNotAdaptiveMode; then - notAdaptiveFailed "There is no MediaBox in the pdf document!" + notAdaptiveFailed "There is no MediaBox in the pdf document!" elif isEmpty "$mediaBox" && isAdaptiveMode; then return $FALSE fi @@ -255,43 +439,6 @@ getPageSizeCatGrep() { return $TRUE } -# Prints error message and exits execution -notAdaptiveFailed() { - local errProgram="$2" - local errStr="$1" - if isEmpty "$2"; then - printError "Error when reading input file!" - printError "Could not determine the page size!" - else - printError "Error! $2 was not found!" - fi - isNotEmpty "$errStr" && printError "$errStr" - printError "Aborting! You may want to try the adaptive mode." - exit $EXIT_INVALID_PAGE_SIZE_DETECTED -} - -# Return $TRUE if adaptive mode is enabled, false otherwise -isAdaptiveMode() { - return $ADAPTIVEMODE -} - -# Return $TRUE if adaptive mode is disabled, false otherwise -isNotAdaptiveMode() { - isAdaptiveMode && return $FALSE - return $TRUE -} - -# Return $TRUE if $1 is empty, false otherwise -isEmpty() { - [[ -z "$1" ]] && return $TRUE - return $FALSE -} - -# Return $TRUE if $1 is NOT empty, false otherwise -isNotEmpty() { - [[ -z "$1" ]] && return $FALSE - return $TRUE -} # Detects operation mode and also runs the adaptive mode getPageSize() { @@ -304,7 +451,7 @@ getPageSize() { vprint " Method: Mac Quartz mdls" getPageSizeMdls elif [[ $MODE = "PDFINFO" ]]; then - vprint " Method: PDFInfo" + vprint " Method: PDFInfo" getPageSizePdfInfo elif [[ $MODE = "IDENTIFY" ]]; then vprint " Method: ImageMagick's Identify" @@ -326,7 +473,7 @@ getPageSize() { getPageSizeMdls fi - if pageSizeIsInvalid; then + if pageSizeIsInvalid; then vprint " Failed" vprint " Method: PDFInfo" getPageSizePdfInfo @@ -346,316 +493,37 @@ getPageSize() { exit $EXIT_INVALID_PAGE_SIZE_DETECTED fi - return $TRUE -} - -vPrintSourcePageSizes() { - vprint " $1 Width: $PGWIDTH postscript-points" - vprint "$1 Height: $PGHEIGHT postscript-points" + return $TRUE } -# Returns $TRUE if $PGWIDTH OR $PGWIDTH are empty or NOT an Integer, false otherwise -pageSizeIsInvalid() { - if isNotAnInteger "$PGWIDTH" || isNotAnInteger "$PGHEIGHT"; then - return $TRUE +# Prints error message and exits execution +notAdaptiveFailed() { + local errProgram="$2" + local errStr="$1" + if isEmpty "$2"; then + printError "Error when reading input file!" + printError "Could not determine the page size!" + else + printError "Error! $2 was not found!" fi - return $FALSE -} - -isAnInteger() { - case $1 in - ''|*[!0-9]*) return $FALSE ;; - *) return $TRUE ;; - esac -} - -isNotAnInteger() { - case $1 in - ''|*[!0-9]*) return $TRUE ;; - *) return $FALSE ;; - esac -} - - -# Prints usage info -usage() { - [[ "$2" != 'nobanner' ]] && printVersion 2 - [[ ! -z "$1" ]] && printError "$1" - printError "Usage: $PDFSCALE_NAME [-v] [-s ] [-m ] [outfile.pdf]" - printError "Try: $PDFSCALE_NAME -h # for help" -} - - -# Prints Verbose information -vprint() { - [[ $VERBOSE -eq 0 ]] && return 0 - timestamp="" - [[ $VERBOSE -gt 1 ]] && timestamp="$(date +%Y-%m-%d:%H:%M:%S) | " - echo "$timestamp$1" -} - - -# Prints dependency information and aborts execution -printDependency() { - #printVersion 2 - local brewName="$1" - [[ "$1" = 'pdfinfo' && "$OSNAME" = "Darwin" ]] && brewName="xpdf" - printError $'\n'"ERROR! You need to install the package '$1'"$'\n' - printError "Linux apt-get.: sudo apt-get install $1" - printError "Linux yum.....: sudo yum install $1" - printError "MacOS homebrew: brew install $brewName" - printError $'\n'"Aborting..." - exit $EXIT_MISSING_DEPENDENCY -} - -# Prints initialization errors and aborts execution -initError() { - local errStr="$1" - local exitStat=$2 - [[ -z "$exitStat" ]] && exitStat=$EXIT_ERROR - usage "ERROR! $errStr" "$3" - exit $exitStat -} - -# Prints to stderr -printError() { - echo >&2 "$@" -} - -# Returns $TRUE if $1 has a .pdf extension, false otherwsie -isPDF() { - [[ "$1" =~ ^..*\.pdf$ ]] && return $TRUE - return $FALSE -} - - -# Returns $TRUE if $1 is a file, false otherwsie -isFile() { - [[ -f "$1" ]] && return $TRUE - return $FALSE -} - -# Returns $TRUE if $1 is NOT a file, false otherwsie -notIsFile() { - [[ -f "$1" ]] && return $FALSE - return $TRUE -} - -# Returns $TRUE if $1 is executable, false otherwsie -isExecutable() { - [[ -x "$1" ]] && return $TRUE - return $FALSE -} - -# Returns $TRUE if $1 is NOT executable, false otherwsie -notIsExecutable() { - [[ -x "$1" ]] && return $FALSE - return $TRUE -} - -# Returns $TRUE if $1 is a file and executable, false otherwsie -isAvailable() { - if isFile "$1" && isExecutable "$1"; then - return $TRUE - fi - return $FALSE -} - -# Returns $TRUE if $1 is NOT a file or NOT executable, false otherwsie -notIsAvailable() { - if notIsFile "$1" || notIsExecutable "$1"; then - return $TRUE - fi - return $FALSE -} - -# Loads external dependencies and checks for errors -loadDeps() { - GSBIN="$(which gs 2>/dev/null)" - BCBIN="$(which bc 2>/dev/null)" - IDBIN=$(which identify 2>/dev/null) - MDLSBIN="$(which mdls 2>/dev/null)" - PDFINFOBIN="$(which pdfinfo 2>/dev/null)" - - vprint "Checking for ghostscript and bcmath" - if notIsAvailable "$GSBIN"; then printDependency 'ghostscript'; fi - if notIsAvailable "$BCBIN"; then printDependency 'bc'; fi - - if [[ $MODE = "IDENTIFY" ]]; then - vprint "Checking for imagemagick's identify" - if notIsAvailable "$IDBIN"; then printDependency 'imagemagick'; fi - fi - if [[ $MODE = "PDFINFO" ]]; then - vprint "Checking for pdfinfo" - if notIsAvailable "$PDFINFOBIN"; then printDependency 'pdfinfo'; fi - fi - if [[ $MODE = "MDLS" ]]; then - vprint "Checking for MacOS mdls" - if notIsAvailable "$MDLSBIN"; then - initError 'mdls executable was not found! Is this even MacOS?' $EXIT_MAC_MDLS_NOT_FOUND 'nobanner' - fi - fi -} - -# Main execution -main() { - printVersion 1 'verbose' - - #getScaledOutputName - - #Intro message - #vprint "$(basename $0) v$VERSION - Verbose execution" - - loadDeps - vprint " Input file: $INFILEPDF" - vprint " Output file: $OUTFILEPDF" - getPageSize - - - if isMixedMode; then - vprint " Mixed Tasks: Resize & Scale" - vprint " Scale factor: $SCALE" - vPrintSourcePageSizes ' Source' - outputFile="$OUTFILEPDF" # backup outFile name - tempFile="${OUTFILEPDF%.pdf}.__TEMP__.pdf" # set a temp file name - OUTFILEPDF="$tempFile" # set output to tmp file - pageResize # resize to tmp file - INFILEPDF="$tempFile" # get tmp file as input - OUTFILEPDF="$outputFile" # reset final target - PGWIDTH=$RESIZE_WIDTH # we already know the new page size - PGHEIGHT=$RESIZE_HEIGHT # from the last command (Resize) - vPrintSourcePageSizes ' New' - pageScale # scale the resized pdf - # remove tmp file - rm "$tempFile" >/dev/null 2>&1 || printError "Error when removing temporary file: $tempFile" - elif isResizeMode; then - vprint " Single Task: Resize PDF Paper" - vprint " Scale factor: Disabled (resize only)" - vPrintSourcePageSizes ' Source' - pageResize - else - local scaleMode="" - vprint " Single Task: Scale PDF Contents" - isManualScaledMode && scaleMode='(manual)' || scaleMode='(auto)' - vprint " Scale factor: $SCALE $scaleMode" - vPrintSourcePageSizes ' Source' - pageScale - fi - - #pageScale - #pageResize -} - - -# Parse options -getOptions() { - while getopts ":vhVs:m:r:p" o; do - case "${o}" in - v) - ((VERBOSE++)) - ;; - h) - printHelp - exit $EXIT_SUCCESS - ;; - V) - printVersion - exit $EXIT_SUCCESS - ;; - s) - parseScale ${OPTARG} - ;; - m) - parseMode ${OPTARG} - ;; - r) - parsePaperResize ${OPTARG} - ;; - p) - printPaperInfo - exit $EXIT_SUCCESS - ;; - *) - initError "Invalid Option: -$OPTARG" $EXIT_INVALID_OPTION - ;; - esac - done - shift $((OPTIND-1)) - - # Validate input PDF file - INFILEPDF="$1" - isEmpty "$INFILEPDF" && initError "Input file is empty!" $EXIT_NO_INPUT_FILE - isPDF "$INFILEPDF" || initError "Input file is not a PDF file: $INFILEPDF" $EXIT_INPUT_NOT_PDF - isFile "$INFILEPDF" || initError "Input file not found: $INFILEPDF" $EXIT_FILE_NOT_FOUND - - if isEmpty "$2"; then - if isMixedMode; then - OUTFILEPDF="${INFILEPDF%.pdf}.$(uppercase $RESIZE_PAPER_TYPE).SCALED.pdf" - elif isResizeMode; then - OUTFILEPDF="${INFILEPDF%.pdf}.$(uppercase $RESIZE_PAPER_TYPE).pdf" - else - OUTFILEPDF="${INFILEPDF%.pdf}.SCALED.pdf" - fi - else - OUTFILEPDF="${2%.pdf}.pdf" - fi -} - - -# Runs the ghostscript scaling script -pageScale() { - # Compute translation factors (to center page). - XTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGWIDTH" | "$BCBIN") - YTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGHEIGHT" | "$BCBIN") - vprint " Translation X: $XTRANS" - vprint " Translation Y: $YTRANS" - - # Do it. - "$GSBIN" \ --q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \ --dCompatibilityLevel="1.5" -dPDFSETTINGS="/printer" \ --dColorConversionStrategy=/LeaveColorUnchanged \ --dSubsetFonts=true -dEmbedAllFonts=true \ --dDEVICEWIDTHPOINTS=$PGWIDTH -dDEVICEHEIGHTPOINTS=$PGHEIGHT \ --sOutputFile="$OUTFILEPDF" \ --c "<> setpagedevice" \ --f "$INFILEPDF" & - wait ${!} + isNotEmpty "$errStr" && printError "$errStr" + printError "Aborting! You may want to try the adaptive mode." + exit $EXIT_INVALID_PAGE_SIZE_DETECTED } - -pageResize() { - getGSPaperSize "$RESIZE_PAPER_TYPE" - local tmpInverter="" - if [[ $PGWIDTH -gt $PGHEIGHT && $RESIZE_WIDTH -lt $RESIZE_HEIGHT ]]; then - vprint " Flip Detect: Wrong orientation!" - vprint " Inverting Width <-> Height" - tmpInverter=$RESIZE_HEIGHT - RESIZE_HEIGHT=$RESIZE_WIDTH - RESIZE_WIDTH=$tmpInverter - fi - vprint " Resizing to: $(uppercase $RESIZE_PAPER_TYPE) ( $RESIZE_WIDTH x $RESIZE_HEIGHT )" - - # Change page size - "$GSBIN" \ --q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \ --dCompatibilityLevel="1.5" -dPDFSETTINGS="/printer" \ --dColorConversionStrategy=/LeaveColorUnchanged \ --dSubsetFonts=true -dEmbedAllFonts=true \ --dDEVICEWIDTHPOINTS=$RESIZE_WIDTH -dDEVICEHEIGHTPOINTS=$RESIZE_HEIGHT \ --dFIXEDMEDIA -dPDFFitPage \ --sOutputFile="$OUTFILEPDF" \ --f "$INFILEPDF" & - wait ${!} - +# Verbose print of the Width and Height (Source or New) to screen +vPrintSourcePageSizes() { + vprint " $1 Width: $PGWIDTH postscript-points" + vprint "$1 Height: $PGHEIGHT postscript-points" } +#################### GHOSTSCRIPT PAPER INFO #################### - +# Loads GS paper info to memory getPaperInfo() { - # name inchesW inchesH mmW mmH pointsW pointsH - sizesUS="\ + # name inchesW inchesH mmW mmH pointsW pointsH + sizesUS="\ 11x17 11.0 17.0 279 432 792 1224 ledger 17.0 11.0 432 279 1224 792 legal 8.5 14.0 216 356 612 1008 @@ -667,7 +535,7 @@ archC 18.0 24.0 457 610 1296 1728 archB 12.0 18.0 305 457 864 1296 archA 9.0 12.0 229 305 648 864" - sizesISO="\ + sizesISO="\ a0 33.1 46.8 841 1189 2384 3370 a1 23.4 33.1 594 841 1684 2384 a2 16.5 23.4 420 594 1191 1684 @@ -695,7 +563,7 @@ c4 9.0 12.8 229 324 649 918 c5 6.4 9.0 162 229 459 649 c6 4.5 6.4 114 162 323 459" - sizesJIS="\ + sizesJIS="\ jisb0 NA NA 1030 1456 2920 4127 jisb1 NA NA 728 1030 2064 2920 jisb2 NA NA 515 728 1460 2064 @@ -704,13 +572,13 @@ jisb4 NA NA 257 364 729 1032 jisb5 NA NA 182 257 516 729 jisb6 NA NA 128 182 363 516" - sizesOther="\ + sizesOther="\ flsa 8.5 13.0 216 330 612 936 flse 8.5 13.0 216 330 612 936 halfletter 5.5 8.5 140 216 396 612 hagaki 3.9 5.8 100 148 283 420" - - sizesAll="\ + + sizesAll="\ $sizesUS $sizesISO $sizesJIS @@ -718,174 +586,281 @@ $sizesOther" } +# Gets a paper size in points and sets it to RESIZE_WIDTH and RESIZE_HEIGHT getGSPaperSize() { - isEmpty "$sizesall" && getPaperInfo - while read l; do - local cols=($l) - if [[ "$1" == ${cols[0]} ]]; then - RESIZE_WIDTH=${cols[5]} - RESIZE_HEIGHT=${cols[6]} - return $TRUE - fi - done <<< "$sizesAll" + isEmpty "$sizesall" && getPaperInfo + while read l; do + local cols=($l) + if [[ "$1" == ${cols[0]} ]]; then + RESIZE_WIDTH=${cols[5]} + RESIZE_HEIGHT=${cols[6]} + return $TRUE + fi + done <<< "$sizesAll" } +# Loads an array with paper names to memory getPaperNames() { - 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 \ + 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 \ 11x17 ledger legal letter lettersmall archE archD archC archB archA \ jisb0 jisb1 jisb2 jisb3 jisb4 jisb5 jisb6 \ flsa flse halfletter hagaki) } +# Prints uppercase paper names to screen (used in help) printPaperNames() { - isEmpty "$paperNames" && getPaperNames - for i in "${!paperNames[@]}"; do - [[ $i -ne 0 && $((i % 5)) -eq 0 ]] && echo "" - ppN="$(uppercase ${paperNames[i]})" - printf "%-14s" "$ppN" - done - echo "" + isEmpty "$paperNames" && getPaperNames + for i in "${!paperNames[@]}"; do + [[ $i -ne 0 && $((i % 5)) -eq 0 ]] && echo "" + ppN="$(uppercase ${paperNames[i]})" + printf "%-14s" "$ppN" + done + echo "" } +# Returns $TRUE if $! is a valid paper name, $FALSE otherwise isPaperName() { - isEmpty "$1" && return $FALSE - isEmpty "$paperNames" && getPaperNames - for i in "${paperNames[@]}"; do - [[ "$i" = "$1" ]] && return $TRUE - done - return $FALSE + isEmpty "$1" && return $FALSE + isEmpty "$paperNames" && getPaperNames + for i in "${paperNames[@]}"; do + [[ "$i" = "$1" ]] && return $TRUE + done + return $FALSE } +# Prints all tables with ghostscript paper information printPaperInfo() { - printVersion - echo $'\n'"Valid Ghostscript Paper Sizes accepted"$'\n' - getPaperInfo - printPaperTable "ISO STANDARD" "$sizesISO"; echo - printPaperTable "US STANDARD" "$sizesUS"; echo - printPaperTable "JIS STANDARD *Aproximated Points" "$sizesJIS"; echo - printPaperTable "OTHERS" "$sizesOther"; echo + printVersion + echo $'\n'"Valid Ghostscript Paper Sizes accepted"$'\n' + getPaperInfo + printPaperTable "ISO STANDARD" "$sizesISO"; echo + printPaperTable "US STANDARD" "$sizesUS"; echo + printPaperTable "JIS STANDARD *Aproximated Points" "$sizesJIS"; echo + printPaperTable "OTHERS" "$sizesOther"; echo } +# GS paper table helper, prints a full line printTableLine() { - echo '+-----------------------------------------------------------------+' + echo '+-----------------------------------------------------------------+' } +# GS paper table helper, prints a line with dividers printTableDivider() { - echo '+-----------------+-------+-------+-------+-------+-------+-------+' + echo '+-----------------+-------+-------+-------+-------+-------+-------+' } +# GS paper table helper, prints a table header printTableHeader() { - echo '| Name | inchW | inchH | mm W | mm H | pts W | pts H |' + echo '| Name | inchW | inchH | mm W | mm H | pts W | pts H |' } +# GS paper table helper, prints a table title printTableTitle() { - printf "| %-64s%s\n" "$1" '|' + printf "| %-64s%s\n" "$1" '|' } +# GS paper table printer, prints a table for a paper variable printPaperTable() { - printTableLine - printTableTitle "$1" - printTableLine - printTableHeader - printTableDivider - while read l; do - local cols=($l) - printf "| %-15s | %+5s | %+5s | %+5s | %+5s | %+5s | %+5s |\n" ${cols[*]}; - done <<< "$2" - printTableDivider -} - + printTableLine + printTableTitle "$1" + printTableLine + printTableHeader + printTableDivider + while read l; do + local cols=($l) + printf "| %-15s | %+5s | %+5s | %+5s | %+5s | %+5s | %+5s |\n" ${cols[*]}; + done <<< "$2" + printTableDivider +} + +# Validades the a paper resize CLI option and sets the paper to $RESIZE_PAPER_TYPE parsePaperResize() { - isEmpty "$1" && initError 'Invalid Paper Type: (empty)' $EXIT_INVALID_PAPER_SIZE - local lowercasePaper="$(lowercase $1)" - ! isPaperName "$lowercasePaper" && initError "Invalid Paper Type: $1" $EXIT_INVALID_PAPER_SIZE - RESIZE_PAPER_TYPE="$lowercasePaper" + isEmpty "$1" && initError 'Invalid Paper Type: (empty)' $EXIT_INVALID_PAPER_SIZE + local lowercasePaper="$(lowercase $1)" + isPaperName "$lowercasePaper" || initError "Invalid Paper Type: $1" $EXIT_INVALID_PAPER_SIZE + RESIZE_PAPER_TYPE="$lowercasePaper" } +# Returns $TRUE if the scale was set manually, $FALSE if we are using automatic scaling isManualScaledMode() { - [[ $AUTOMATIC_SCALING -eq $TRUE ]] && return $FALSE - return $TRUE + [[ $AUTOMATIC_SCALING -eq $TRUE ]] && return $FALSE + return $TRUE } +# Returns true if we are resizing a paper (ignores scaling), false otherwise isResizeMode() { - isEmpty $RESIZE_PAPER_TYPE && return $FALSE - return $TRUE + isEmpty $RESIZE_PAPER_TYPE && return $FALSE + return $TRUE } +# Returns true if we are resizing a paper and the scale was manually set isMixedMode() { - isResizeMode && isManualScaledMode && return $TRUE - return $FALSE -} - -mmToPoints() { - local calc=$(($1)) + isResizeMode && isManualScaledMode && return $TRUE + return $FALSE } - +# Prints the lowercase char value for $1 lowercaseChar() { case "$1" in [A-Z]) n=$(printf "%d" "'$1") n=$((n+32)) printf \\$(printf "%o" "$n") - ;; + ;; *) - printf "%s" "$1" - ;; + printf "%s" "$1" + ;; esac } +# Prints the lowercase version of a string lowercase() { - word="$@" - for((i=0;i<${#word};i++)) - do - ch="${word:$i:1}" - lowercaseChar "$ch" - done + word="$@" + for((i=0;i<${#word};i++)) + do + ch="${word:$i:1}" + lowercaseChar "$ch" + done } - - +# Prints the uppercase char value for $1 uppercaseChar(){ case "$1" in [a-z]) n=$(printf "%d" "'$1") n=$((n-32)) printf \\$(printf "%o" "$n") - ;; + ;; *) - printf "%s" "$1" - ;; + printf "%s" "$1" + ;; esac } +# Prints the uppercase version of a string uppercase() { - word="$@" - for((i=0;i<${#word};i++)) - do - ch="${word:$i:1}" - uppercaseChar "$ch" - done + word="$@" + for((i=0;i<${#word};i++)) + do + ch="${word:$i:1}" + uppercaseChar "$ch" + done +} + + +########################## VALIDATORS ########################## + +# Returns $TRUE if $PGWIDTH OR $PGWIDTH are empty or NOT an Integer, false otherwise +pageSizeIsInvalid() { + if isNotAnInteger "$PGWIDTH" || isNotAnInteger "$PGHEIGHT"; then + return $TRUE + fi + return $FALSE +} + + +# Return $TRUE if adaptive mode is enabled, false otherwise +isAdaptiveMode() { + return $ADAPTIVEMODE +} + + +# Return $TRUE if adaptive mode is disabled, false otherwise +isNotAdaptiveMode() { + isAdaptiveMode && return $FALSE + return $TRUE +} + + +# Return $TRUE if $1 is empty, false otherwise +isEmpty() { + [[ -z "$1" ]] && return $TRUE + return $FALSE +} + + +# Return $TRUE if $1 is NOT empty, false otherwise +isNotEmpty() { + [[ -z "$1" ]] && return $FALSE + return $TRUE +} + + +isAnInteger() { + case $1 in + ''|*[!0-9]*) return $FALSE ;; + *) return $TRUE ;; + esac +} + + +isNotAnInteger() { + case $1 in + ''|*[!0-9]*) return $TRUE ;; + *) return $FALSE ;; + esac +} + + +# Returns $TRUE if $1 has a .pdf extension, false otherwsie +isPDF() { + [[ "$1" =~ ^..*\.pdf$ ]] && return $TRUE + return $FALSE +} + + +# Returns $TRUE if $1 is a file, false otherwsie +isFile() { + [[ -f "$1" ]] && return $TRUE + return $FALSE } +# Returns $TRUE if $1 is NOT a file, false otherwsie +notIsFile() { + [[ -f "$1" ]] && return $FALSE + return $TRUE +} -#printPaperInfo -#printPaperNames -#echo "----" -#isPaperName a4s; echo $? +# Returns $TRUE if $1 is executable, false otherwsie +isExecutable() { + [[ -x "$1" ]] && return $TRUE + return $FALSE +} +# Returns $TRUE if $1 is NOT executable, false otherwsie +notIsExecutable() { + [[ -x "$1" ]] && return $FALSE + return $TRUE +} + + +# Returns $TRUE if $1 is a file and executable, false otherwsie +isAvailable() { + if isFile "$1" && isExecutable "$1"; then + return $TRUE + fi + return $FALSE +} + +# Returns $TRUE if $1 is NOT a file or NOT executable, false otherwsie +notIsAvailable() { + if notIsFile "$1" || notIsExecutable "$1"; then + return $TRUE + fi + return $FALSE +} -####----------Print-Program-Information----------#### +###################### PRINTING TO SCREEN ###################### # Prints version printVersion() { - local vStr="" - [[ "$2" = 'verbose' ]] && vStr=" - Verbose Execution" + local vStr="" + [[ "$2" = 'verbose' ]] && vStr=" - Verbose Execution" if [[ $1 -eq 2 ]]; then printError "$PDFSCALE_NAME v$VERSION$vStr" else @@ -897,7 +872,7 @@ printVersion() { # Prints help info printHelp() { printVersion - local paperList="$(printPaperNames)" + local paperList="$(printPaperNames)" echo " Usage: $PDFSCALE_NAME [-v] [-s ] [-m ] [-r ] [outfile.pdf] $PDFSCALE_NAME -p @@ -974,15 +949,57 @@ Examples: } +# Prints usage info +usage() { + [[ "$2" != 'nobanner' ]] && printVersion 2 + [[ ! -z "$1" ]] && printError "$1" + printError "Usage: $PDFSCALE_NAME [-v] [-s ] [-m ] [outfile.pdf]" + printError "Try: $PDFSCALE_NAME -h # for help" +} + + +# Prints Verbose information +vprint() { + [[ $VERBOSE -eq 0 ]] && return 0 + timestamp="" + [[ $VERBOSE -gt 1 ]] && timestamp="$(date +%Y-%m-%d:%H:%M:%S) | " + echo "$timestamp$1" +} + + +# Prints dependency information and aborts execution +printDependency() { + #printVersion 2 + local brewName="$1" + [[ "$1" = 'pdfinfo' && "$OSNAME" = "Darwin" ]] && brewName="xpdf" + printError $'\n'"ERROR! You need to install the package '$1'"$'\n' + printError "Linux apt-get.: sudo apt-get install $1" + printError "Linux yum.....: sudo yum install $1" + printError "MacOS homebrew: brew install $brewName" + printError $'\n'"Aborting..." + exit $EXIT_MISSING_DEPENDENCY +} +# Prints initialization errors and aborts execution +initError() { + local errStr="$1" + local exitStat=$2 + [[ -z "$exitStat" ]] && exitStat=$EXIT_ERROR + usage "ERROR! $errStr" "$3" + exit $exitStat +} +# Prints to stderr +printError() { + echo >&2 "$@" +} -######### START EXECUTION +########################## EXECUTION ########################### getOptions "${@}" main From 442579b87f7f502fa57d388321f81c1f6baf8d6b Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 19:21:01 -0300 Subject: [PATCH 13/59] Checked all exit calls use exit flags, changed some -z, etc to my isEmpty or isNotEmpy functions --- pdfScale.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pdfScale.sh b/pdfScale.sh index b2f66c1..5a1ec3c 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -272,7 +272,7 @@ pageResize() { # Parse a forced mode of operation parseMode() { - if [[ -z $1 ]]; then + if isEmpty "$1"; then printError "Mode is empty, please specify the desired mode" printError "Falling back to adaptive mode!" ADAPTIVEMODE=$TRUE @@ -952,7 +952,7 @@ Examples: # Prints usage info usage() { [[ "$2" != 'nobanner' ]] && printVersion 2 - [[ ! -z "$1" ]] && printError "$1" + isNotEmpty "$1" && printError "$1" printError "Usage: $PDFSCALE_NAME [-v] [-s ] [-m ] [outfile.pdf]" printError "Try: $PDFSCALE_NAME -h # for help" } @@ -960,7 +960,7 @@ usage() { # Prints Verbose information vprint() { - [[ $VERBOSE -eq 0 ]] && return 0 + [[ $VERBOSE -eq 0 ]] && return $TRUE timestamp="" [[ $VERBOSE -gt 1 ]] && timestamp="$(date +%Y-%m-%d:%H:%M:%S) | " echo "$timestamp$1" @@ -985,7 +985,7 @@ printDependency() { initError() { local errStr="$1" local exitStat=$2 - [[ -z "$exitStat" ]] && exitStat=$EXIT_ERROR + isEmpty "$exitStat" && exitStat=$EXIT_ERROR usage "ERROR! $errStr" "$3" exit $exitStat } From 75c948ce2e83c26f6c62c0b3e4e187cf022ac1f9 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 19:26:57 -0300 Subject: [PATCH 14/59] program name was printing even when not verbose, fixed --- pdfScale.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pdfScale.sh b/pdfScale.sh index 5a1ec3c..1c4d5ba 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -864,7 +864,7 @@ printVersion() { if [[ $1 -eq 2 ]]; then printError "$PDFSCALE_NAME v$VERSION$vStr" else - echo "$PDFSCALE_NAME v$VERSION$vStr" + vprint "$PDFSCALE_NAME v$VERSION$vStr" fi } From 9a3b6a2f53d5ee78c8c49da8807fc5b710ddb4b5 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 21:44:00 -0300 Subject: [PATCH 15/59] Added custom paper resizing functionality; more updates to help messages --- pdfScale.sh | 175 ++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 137 insertions(+), 38 deletions(-) diff --git a/pdfScale.sh b/pdfScale.sh index 1c4d5ba..d8ea3c4 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -48,6 +48,8 @@ ADAPTIVEMODE=$TRUE # Automatically try to guess best mode AUTOMATIC_SCALING=$TRUE # Default scaling in $SCALE, override by resize mode MODE="" RESIZE_PAPER_TYPE="" +CUSTOM_RESIZE_PAPER=$FALSE +FLIP_DETECTION=$TRUE PGWIDTH="" PGHEIGHT="" RESIZE_WIDTH="" @@ -76,7 +78,7 @@ EXIT_INVALID_PAPER_SIZE=50 # Main function called at the end main() { printVersion 1 'verbose' - loadDeps + checkDeps vprint " Input file: $INFILEPDF" vprint " Output file: $OUTFILEPDF" getPageSize @@ -118,7 +120,7 @@ main() { ########################## INITIALIZER ########################## # Loads external dependencies and checks for errors -loadDeps() { +initDeps() { GSBIN="$(which gs 2>/dev/null)" BCBIN="$(which bc 2>/dev/null)" IDBIN=$(which identify 2>/dev/null) @@ -128,8 +130,11 @@ loadDeps() { vprint "Checking for ghostscript and bcmath" if notIsAvailable "$GSBIN"; then printDependency 'ghostscript'; fi if notIsAvailable "$BCBIN"; then printDependency 'bc'; fi - - if [[ $MODE = "IDENTIFY" ]]; then +} + +# Checks for dependencies errors, run after getting options +checkDeps() { + if [[ $MODE = "IDENTIFY" ]]; then vprint "Checking for imagemagick's identify" if notIsAvailable "$IDBIN"; then printDependency 'imagemagick'; fi fi @@ -150,7 +155,7 @@ loadDeps() { # Parse options getOptions() { - while getopts ":vhVs:m:r:p" o; do + while getopts ":vhVs:m:r:pf" o; do case "${o}" in v) ((VERBOSE++)) @@ -176,6 +181,9 @@ getOptions() { printPaperInfo exit $EXIT_SUCCESS ;; + f) + FLIP_DETECTION=$FALSE + ;; *) initError "Invalid Option: -$OPTARG" $EXIT_INVALID_OPTION ;; @@ -206,15 +214,16 @@ getOptions() { # Parses and validates the scaling factor parseScale() { AUTOMATIC_SCALING=$FALSE - if ! [[ -n "$1" && "$1" =~ ^-?[0-9]*([.][0-9]+)?$ && (($1 > 0 )) ]] ; then + if ! isFloatBiggerThanZero "$1"; then printError "Invalid factor: $1" printError "The factor must be a floating point number greater than 0" printError "Example: for 80% use 0.8" exit $EXIT_INVALID_SCALE fi - SCALE=$1 + SCALE="$1" } + ###################### GHOSTSCRIPT CALLS ####################### # Runs the ghostscript scaling script @@ -241,16 +250,16 @@ pageScale() { # Runs the ghostscript paper resize script pageResize() { - getGSPaperSize "$RESIZE_PAPER_TYPE" + isNotCustomPaper && getGSPaperSize "$RESIZE_PAPER_TYPE" local tmpInverter="" - if [[ $PGWIDTH -gt $PGHEIGHT && $RESIZE_WIDTH -lt $RESIZE_HEIGHT ]]; then + if [[ $FLIP_DETECTION -eq $TRUE && $PGWIDTH -gt $PGHEIGHT && $RESIZE_WIDTH -lt $RESIZE_HEIGHT ]]; then vprint " Flip Detect: Wrong orientation!" vprint " Inverting Width <-> Height" tmpInverter=$RESIZE_HEIGHT RESIZE_HEIGHT=$RESIZE_WIDTH RESIZE_WIDTH=$tmpInverter fi - vprint " Resizing to: $(uppercase $RESIZE_PAPER_TYPE) ( $RESIZE_WIDTH x $RESIZE_HEIGHT )" + vprint " Resizing to: $(uppercase $RESIZE_PAPER_TYPE) ( $RESIZE_WIDTH x $RESIZE_HEIGHT ) pts" # Change page size "$GSBIN" \ @@ -267,7 +276,6 @@ pageResize() { } - ################### PDF PAGE SIZE DETECTION #################### # Parse a forced mode of operation @@ -611,7 +619,8 @@ flsa flse halfletter hagaki) printPaperNames() { isEmpty "$paperNames" && getPaperNames for i in "${!paperNames[@]}"; do - [[ $i -ne 0 && $((i % 5)) -eq 0 ]] && echo "" + [[ $i -eq 0 ]] && echo -n -e ' ' + [[ $i -ne 0 && $((i % 5)) -eq 0 ]] && echo -n -e $'\n ' ppN="$(uppercase ${paperNames[i]})" printf "%-14s" "$ppN" done @@ -677,8 +686,62 @@ printPaperTable() { parsePaperResize() { isEmpty "$1" && initError 'Invalid Paper Type: (empty)' $EXIT_INVALID_PAPER_SIZE local lowercasePaper="$(lowercase $1)" - isPaperName "$lowercasePaper" || initError "Invalid Paper Type: $1" $EXIT_INVALID_PAPER_SIZE - RESIZE_PAPER_TYPE="$lowercasePaper" + if [[ "$1" = 'custom' ]]; then + if isNotValidMeasure "$2" || ! isFloatBiggerThanZero "$3" || ! isFloatBiggerThanZero "$4"; then + initError "Invalid Custom Paper Definition!"$'\n'"Use: -r 'custom '"$'\n'"Measurements: mm, in, pts" $EXIT_INVALID_OPTION + fi + RESIZE_PAPER_TYPE="custom" + CUSTOM_RESIZE_PAPER=$TRUE + if isMilimeter "$2"; then + RESIZE_WIDTH="$(milimetersToPoints "$3")" + RESIZE_HEIGHT="$(milimetersToPoints "$4")" + elif isInch "$2"; then + RESIZE_WIDTH="$(inchesToPoints "$3")" + RESIZE_HEIGHT="$(inchesToPoints "$4")" + elif isPoint "$2"; then + RESIZE_WIDTH="$3" + RESIZE_HEIGHT="$4" + else + initError "Invalid Custom Paper Definition!"$'\n'"Use: -r 'custom '"$'\n'"Measurements: mm, in, pts" $EXIT_INVALID_OPTION + fi + else + isPaperName "$lowercasePaper" || initError "Invalid Paper Type: $1" $EXIT_INVALID_PAPER_SIZE + RESIZE_PAPER_TYPE="$lowercasePaper" + fi +} + +# Returns $TRUE if $1 is a valid measurement for a custom paper, $FALSE otherwise +isNotValidMeasure() { + isMilimeter "$1" || isInch "$1" || isPoint "$1" && return $FALSE + return $TRUE +} + +# Returns $TRUE if $1 is a valid milimeter string, $FALSE otherwise +isMilimeter() { + [[ "$1" = 'mm' || "$1" = 'milimeters' || "$1" = 'milimeter' ]] && return $TRUE + return $FALSE +} + +# Returns $TRUE if $1 is a valid inch string, $FALSE otherwise +isInch() { + [[ "$1" = 'in' || "$1" = 'inch' || "$1" = 'inches' ]] && return $TRUE + return $FALSE +} + +# Returns $TRUE if $1 is a valid point string, $FALSE otherwise +isPoint() { + [[ "$1" = 'pt' || "$1" = 'pts' || "$1" = 'point' || "$1" = 'points' ]] && return $TRUE + return $FALSE +} + +# Returns $TRUE if a custom paper is being used, $FALSE otherwise +isCustomPaper() { + return $CUSTOM_RESIZE_PAPER +} + +isNotCustomPaper() { + isCustomPaper && return $FALSE + return $TRUE } # Returns $TRUE if the scale was set manually, $FALSE if we are using automatic scaling @@ -747,10 +810,22 @@ uppercase() { done } +# Prints the postscript points rounded equivalent from $1 mm +milimetersToPoints() { + local pts=$(echo "scale=6; $1 * 72 / 25.4" | "$BCBIN") + printf '%.0f' "$pts" # Print rounded conversion +} + +# Prints the postscript points rounded equivalent from $1 mm +inchesToPoints() { + local pts=$(echo "scale=6; $1 * 72" | "$BCBIN") + printf '%.0f' "$pts" # Print rounded conversion +} + ########################## VALIDATORS ########################## -# Returns $TRUE if $PGWIDTH OR $PGWIDTH are empty or NOT an Integer, false otherwise +# Returns $TRUE if $PGWIDTH OR $PGWIDTH are empty or NOT an Integer, $FALSE otherwise pageSizeIsInvalid() { if isNotAnInteger "$PGWIDTH" || isNotAnInteger "$PGHEIGHT"; then return $TRUE @@ -759,33 +834,33 @@ pageSizeIsInvalid() { } -# Return $TRUE if adaptive mode is enabled, false otherwise +# Return $TRUE if adaptive mode is enabled, $FALSE otherwise isAdaptiveMode() { return $ADAPTIVEMODE } -# Return $TRUE if adaptive mode is disabled, false otherwise +# Return $TRUE if adaptive mode is disabled, $FALSE otherwise isNotAdaptiveMode() { isAdaptiveMode && return $FALSE return $TRUE } -# Return $TRUE if $1 is empty, false otherwise +# Return $TRUE if $1 is empty, $FALSE otherwise isEmpty() { [[ -z "$1" ]] && return $TRUE return $FALSE } -# Return $TRUE if $1 is NOT empty, false otherwise +# Return $TRUE if $1 is NOT empty, $FALSE otherwise isNotEmpty() { [[ -z "$1" ]] && return $FALSE return $TRUE } - +# Returns $TRUE if $1 is an integer, $FALSE otherwise isAnInteger() { case $1 in ''|*[!0-9]*) return $FALSE ;; @@ -793,7 +868,7 @@ isAnInteger() { esac } - +# Returns $TRUE if $1 is NOT an integer, $FALSE otherwise isNotAnInteger() { case $1 in ''|*[!0-9]*) return $TRUE ;; @@ -801,6 +876,17 @@ isNotAnInteger() { esac } +# Returns $TRUE if $1 is a floating point number (or an integer), $FALSE otherwise +isFloat() { + [[ -n "$1" && "$1" =~ ^-?[0-9]*([.][0-9]+)?$ ]] && return $TRUE + return $FALSE +} + +# Returns $TRUE if $1 is a floating point number bigger than zero, $FALSE otherwise +isFloatBiggerThanZero() { + isFloat "$1" && [[ (( $1 > 0 )) ]] && return $TRUE + return $FALSE +} # Returns $TRUE if $1 has a .pdf extension, false otherwsie isPDF() { @@ -892,30 +978,32 @@ Parameters: Eg. -s 0.8 for 80% of the original size -r Triggers the Resize Paper Mode Resize PDF paper proportionally - Must be a valid Ghostscript paper name + A valid paper name or a custom defined paper + -f Disables the flip detection, paper will not be + rotated to landscape when needed (resize-only) -p Prints Ghostscript paper info tables to screen Scaling Mode: -The default mode of operation is scaling mode with fixed paper -size and scaling pre-set to $SCALE. By not using the resize mode -you are using scaling mode. + The default mode of operation is scaling mode with fixed paper + size and scaling pre-set to $SCALE. By not using the resize mode + you are using scaling mode. Resize Paper Mode: -Disables the default scaling factor! ($SCALE) -Alternative mode of operation to change the PDF paper -proportionally. Will fit-to-page. + Disables the default scaling factor! ($SCALE) + Alternative mode of operation to change the PDF paper + proportionally. Will fit-to-page. Mixed Mode: -In mixed mode both the -s option and -r option must be specified. -The PDF will be both scaled and have the paper type changed. + In mixed mode both the -s option and -r option must be specified. + The PDF will be first resized then scaled. Output filename: -The output filename is optional. If no file name is passed -the output file will have the same name/destination of the -input file with added suffixes: - .SCALED.pdf is added to scaled files - ..pdf is added to resized files - ..SCALED.pdf is added in mixed mode + The output filename is optional. If no file name is passed + the output file will have the same name/destination of the + input file with added suffixes: + .SCALED.pdf is added to scaled files + ..pdf is added to resized files + ..SCALED.pdf is added in mixed mode Page Detection Modes: a, adaptive Default mode, tries all the methods below @@ -927,6 +1015,14 @@ Page Detection Modes: Valid Ghostscript Paper Names: $paperList +Custom Paper Size: + Paper size can be set manually in Milimeters, Inches or Points. + Use: $PDFSCALE_NAME -r 'custom ' + Ex: $PDFSCALE_NAME -r 'custom mm 210 297' + Measurements can be: mm, inch, pts. + Custom paper definition MUST be quoted into a single parameter. + Actual size is applied in points (mms and inches are transformed). + Notes: - Adaptive Page size detection will try different modes until it gets a page size. You can force a mode with -m 'mode'. @@ -939,11 +1035,13 @@ Notes: Examples: $PDFSCALE_NAME myPdfFile.pdf - $PDFSCALE_NAME myPdfFile.pdf myScaledPdf + $PDFSCALE_NAME myPdfFile.pdf \"My Scaled Pdf\" $PDFSCALE_NAME -v -v myPdfFile.pdf - $PDFSCALE_NAME -s 0.85 myPdfFile.pdf myScaledPdf.pdf + $PDFSCALE_NAME -s 0.85 myPdfFile.pdf My\\ Scaled\\ Pdf.pdf $PDFSCALE_NAME -m pdfinfo -s 0.80 -v myPdfFile.pdf $PDFSCALE_NAME -v -v -m i -s 0.7 myPdfFile.pdf + $PDFSCALE_NAME -r A4 myPdfFile.pdf + $PDFSCALE_NAME -v -v -r \"custom mm 252 356\" -s 0.9 -f \"../input file.pdf\" \"../my new pdf\" $PDFSCALE_NAME -h " } @@ -1001,6 +1099,7 @@ printError() { ########################## EXECUTION ########################### +initDeps getOptions "${@}" main exit $? From 9bf5629a4631d2ea2e385dd43970fd5c79bad868 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 21:45:49 -0300 Subject: [PATCH 16/59] Update readme help info, last commit also added option -f to disable Flip Detection --- README.md | 85 +++++++++++++++++++++++++++++++------------------------ 1 file changed, 48 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 366dec9..1aeadfe 100644 --- a/README.md +++ b/README.md @@ -57,12 +57,11 @@ brew install imagemagick xpdf ## Help info ``` $ pdfscale -h -pdfscale v2.0.0 -Usage: pdfscale [-v] [-s ] [-m ] [-r ] [outfile.pdf] - pdfscale -p - pdfscale -h - pdfscale -V +Usage: pdfScale.sh [-v] [-s ] [-m ] [-r ] [outfile.pdf] + pdfScale.sh -p + pdfScale.sh -h + pdfScale.sh -V Parameters: -v Verbose mode, prints extra information @@ -77,30 +76,32 @@ Parameters: Eg. -s 0.8 for 80% of the original size -r Triggers the Resize Paper Mode Resize PDF paper proportionally - Must be a valid Ghostscript paper name + A valid paper name or a custom defined paper + -f Disables the flip detection, paper will not be + rotated to landscape when needed (resize-only) -p Prints Ghostscript paper info tables to screen Scaling Mode: -The default mode of operation is scaling mode with fixed paper -size and scaling pre-set to 0.95. By not using the resize mode -you are using scaling mode. + The default mode of operation is scaling mode with fixed paper + size and scaling pre-set to 0.95. By not using the resize mode + you are using scaling mode. Resize Paper Mode: -Disables the default scaling factor! (0.95) -Alternative mode of operation to change the PDF paper -proportionally. Will fit-to-page. + Disables the default scaling factor! (0.95) + Alternative mode of operation to change the PDF paper + proportionally. Will fit-to-page. Mixed Mode: -In mixed mode both the -s option and -r option must be specified. -The PDF will be both scaled and have the paper type changed. + In mixed mode both the -s option and -r option must be specified. + The PDF will be first resized then scaled. Output filename: -The output filename is optional. If no file name is passed -the output file will have the same name/destination of the -input file with added suffixes: - .SCALED.pdf is added to scaled files - ..pdf is added to resized files - ..SCALED.pdf is added in mixed mode + The output filename is optional. If no file name is passed + the output file will have the same name/destination of the + input file with added suffixes: + .SCALED.pdf is added to scaled files + ..pdf is added to resized files + ..SCALED.pdf is added in mixed mode Page Detection Modes: a, adaptive Default mode, tries all the methods below @@ -110,16 +111,24 @@ Page Detection Modes: i, identify Forces the use of ImageMagick's Identify Valid Ghostscript Paper Names: -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 11X17 LEDGER LEGAL LETTER -LETTERSMALL ARCHE ARCHD ARCHC ARCHB -ARCHA JISB0 JISB1 JISB2 JISB3 -JISB4 JISB5 JISB6 FLSA FLSE -HALFLETTER HAGAKI + 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 11X17 LEDGER LEGAL LETTER + LETTERSMALL ARCHE ARCHD ARCHC ARCHB + ARCHA JISB0 JISB1 JISB2 JISB3 + JISB4 JISB5 JISB6 FLSA FLSE + HALFLETTER HAGAKI + +Custom Paper Size: + Paper size can be set manually in Milimeters, Inches or Points. + Use: pdfScale.sh -r 'custom ' + Ex: pdfScale.sh -r 'custom mm 210 297' + Measurements can be: mm, inch, pts. + Custom paper definition MUST be quoted into a single parameter. + Actual size is applied in points (mms and inches are transformed). Notes: - Adaptive Page size detection will try different modes until @@ -132,13 +141,15 @@ Notes: result on cropping parts of the pdf. Examples: - pdfscale myPdfFile.pdf - pdfscale myPdfFile.pdf myScaledPdf - pdfscale -v -v myPdfFile.pdf - pdfscale -s 0.85 myPdfFile.pdf myScaledPdf.pdf - pdfscale -m pdfinfo -s 0.80 -v myPdfFile.pdf - pdfscale -v -v -m i -s 0.7 myPdfFile.pdf - pdfscale -h + pdfScale.sh myPdfFile.pdf + pdfScale.sh myPdfFile.pdf "My Scaled Pdf" + pdfScale.sh -v -v myPdfFile.pdf + pdfScale.sh -s 0.85 myPdfFile.pdf My\ Scaled\ Pdf.pdf + pdfScale.sh -m pdfinfo -s 0.80 -v myPdfFile.pdf + pdfScale.sh -v -v -m i -s 0.7 myPdfFile.pdf + pdfScale.sh -r A4 myPdfFile.pdf + pdfScale.sh -v -v -r "custom mm 252 356" -s 0.9 -f "../input file.pdf" "../my new pdf" + pdfScale.sh -h ``` ## Example runs From fbfbb3464e78c8870875104344eb6d46f29ca0da Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 21:48:06 -0300 Subject: [PATCH 17/59] changed flip detection help message --- README.md | 2 +- pdfScale.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1aeadfe..a465939 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ Parameters: Resize PDF paper proportionally A valid paper name or a custom defined paper -f Disables the flip detection, paper will not be - rotated to landscape when needed (resize-only) + rotated when inconsistent sizes are detected. -p Prints Ghostscript paper info tables to screen Scaling Mode: diff --git a/pdfScale.sh b/pdfScale.sh index d8ea3c4..51823a7 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -980,7 +980,7 @@ Parameters: Resize PDF paper proportionally A valid paper name or a custom defined paper -f Disables the flip detection, paper will not be - rotated to landscape when needed (resize-only) + rotated when inconsistent sizes are detected. -p Prints Ghostscript paper info tables to screen Scaling Mode: From 2fb57a49c7673c36c3c918377c2d734cdee12654 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 21:49:55 -0300 Subject: [PATCH 18/59] more 2.0 readme --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a465939..3bb5688 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ -# pdfScale.sh -Bash Script to scale and resize PDFs from the command line. +# pdfScale 2 +Bash Script to ***scale*** and ***resize*** PDFs from the command line. Uses ghostscript to create a scaled and or resized version of the pdf input. In `scaling mode`, the PDF paper size does not change, just the elements are scaled. From 92090f4e7ad60a6e4ef0983c04b32f5a1aeac4a6 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 21:50:25 -0300 Subject: [PATCH 19/59] more 2.0 readme --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3bb5688..0f9f41c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # pdfScale 2 -Bash Script to ***scale*** and ***resize*** PDFs from the command line. -Uses ghostscript to create a scaled and or resized version of the pdf input. +Bash Script to ***scale*** and/or ***resize*** PDFs from the command line. +Uses ghostscript to create a scaled and/or resized version of the pdf input. In `scaling mode`, the PDF paper size does not change, just the elements are scaled. In `resize mode`, the PDF paper will be changed and fit-to-page will be applied. From 274b5f5d41c324b33184504c8405aa370360cf6b Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 22:01:12 -0300 Subject: [PATCH 20/59] more 2.0 readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0f9f41c..b0393e6 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ A temporary file is used in `mixed mode`, at the target location. The script uses `basename`, `cat`, `grep`, `bc`, `head` and `gs` (ghostscript). You probably have everything installed already, except for ghostscript. Optional dependencies are `imagemagick`, `pdfinfo` and `mdls` (Mac). -This app is focused in `Bash`, so it will probably not run on other Shells. +This app is focused in `Bash`, so it will probably not run in other Shells. ##### apt-get ``` From 6b44459cba2e1dfd6f09d352eb2f446c10d1a6d3 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 22:11:39 -0300 Subject: [PATCH 21/59] more 2.0 readme --- README.md | 2 +- pdfScale.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b0393e6..cc5d588 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ Parameters: Eg. -s 0.8 for 80% of the original size -r Triggers the Resize Paper Mode Resize PDF paper proportionally - A valid paper name or a custom defined paper + Uses a valid paper name or a custom defined paper -f Disables the flip detection, paper will not be rotated when inconsistent sizes are detected. -p Prints Ghostscript paper info tables to screen diff --git a/pdfScale.sh b/pdfScale.sh index 51823a7..24b6669 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -978,7 +978,7 @@ Parameters: Eg. -s 0.8 for 80% of the original size -r Triggers the Resize Paper Mode Resize PDF paper proportionally - A valid paper name or a custom defined paper + Uses a valid paper name or a custom defined paper -f Disables the flip detection, paper will not be rotated when inconsistent sizes are detected. -p Prints Ghostscript paper info tables to screen From d19b9dbf248152074c5c10e6fc0035923d2768ff Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 22:57:38 -0300 Subject: [PATCH 22/59] adding more verbose messages, changing the order they are shown --- pdfScale.sh | 56 ++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 38 insertions(+), 18 deletions(-) diff --git a/pdfScale.sh b/pdfScale.sh index 24b6669..b2124ef 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -78,42 +78,51 @@ EXIT_INVALID_PAPER_SIZE=50 # Main function called at the end main() { printVersion 1 'verbose' - checkDeps + checkDeps vprint " Input file: $INFILEPDF" vprint " Output file: $OUTFILEPDF" getPageSize + vPrintSourcePageSizes ' Source' + local finalRet=$EXIT_ERROR if isMixedMode; then vprint " Mixed Tasks: Resize & Scale" vprint " Scale factor: $SCALE" - vPrintSourcePageSizes ' Source' outputFile="$OUTFILEPDF" # backup outFile name tempFile="${OUTFILEPDF%.pdf}.__TEMP__.pdf" # set a temp file name OUTFILEPDF="$tempFile" # set output to tmp file pageResize # resize to tmp file + finalRet=$? INFILEPDF="$tempFile" # get tmp file as input OUTFILEPDF="$outputFile" # reset final target PGWIDTH=$RESIZE_WIDTH # we already know the new page size PGHEIGHT=$RESIZE_HEIGHT # from the last command (Resize) vPrintSourcePageSizes ' New' pageScale # scale the resized pdf + finalRet=$(($finalRet+$?)) # remove tmp file rm "$tempFile" >/dev/null 2>&1 || printError "Error when removing temporary file: $tempFile" elif isResizeMode; then vprint " Single Task: Resize PDF Paper" vprint " Scale factor: Disabled (resize only)" - vPrintSourcePageSizes ' Source' pageResize + finalRet=$? else local scaleMode="" vprint " Single Task: Scale PDF Contents" isManualScaledMode && scaleMode='(manual)' || scaleMode='(auto)' vprint " Scale factor: $SCALE $scaleMode" - vPrintSourcePageSizes ' Source' pageScale + finalRet=$? fi - return $EXIT_SUCCESS + if [[ finalRet -eq $EXIT_SUCCESS ]]; then + vprint " Final Status: File created successfully" + else + vprint " Final Status: Errors were detected. Exit status: $finalRet" + fi + + return $finalRet } @@ -134,7 +143,7 @@ initDeps() { # Checks for dependencies errors, run after getting options checkDeps() { - if [[ $MODE = "IDENTIFY" ]]; then + if [[ $MODE = "IDENTIFY" ]]; then vprint "Checking for imagemagick's identify" if notIsAvailable "$IDBIN"; then printDependency 'imagemagick'; fi fi @@ -234,7 +243,7 @@ pageScale() { vprint " Translation X: $XTRANS" vprint " Translation Y: $YTRANS" - # Do it. + # Scale page "$GSBIN" \ -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \ -dCompatibilityLevel="1.5" -dPDFSETTINGS="/printer" \ @@ -243,23 +252,34 @@ pageScale() { -dDEVICEWIDTHPOINTS=$PGWIDTH -dDEVICEHEIGHTPOINTS=$PGHEIGHT \ -sOutputFile="$OUTFILEPDF" \ -c "<> setpagedevice" \ --f "$INFILEPDF" & - wait ${!} +-f "$INFILEPDF" + + return $? } # Runs the ghostscript paper resize script pageResize() { + # Get new paper sizes if not custom paper isNotCustomPaper && getGSPaperSize "$RESIZE_PAPER_TYPE" + + # Flip detect local tmpInverter="" - if [[ $FLIP_DETECTION -eq $TRUE && $PGWIDTH -gt $PGHEIGHT && $RESIZE_WIDTH -lt $RESIZE_HEIGHT ]]; then - vprint " Flip Detect: Wrong orientation!" - vprint " Inverting Width <-> Height" - tmpInverter=$RESIZE_HEIGHT - RESIZE_HEIGHT=$RESIZE_WIDTH - RESIZE_WIDTH=$tmpInverter + if [[ $FLIP_DETECTION -eq $TRUE ]]; then + if [[ $PGWIDTH -gt $PGHEIGHT && $RESIZE_WIDTH -lt $RESIZE_HEIGHT ]]; then + vprint " Flip Detect: Wrong orientation!" + vprint " Inverting Width <-> Height" + tmpInverter=$RESIZE_HEIGHT + RESIZE_HEIGHT=$RESIZE_WIDTH + RESIZE_WIDTH=$tmpInverter + else + vprint " Flip Detect: No change needed" + fi + else + vprint " Flip Detect: Disabled" fi - vprint " Resizing to: $(uppercase $RESIZE_PAPER_TYPE) ( $RESIZE_WIDTH x $RESIZE_HEIGHT ) pts" + + vprint " Resizing to: $(uppercase "$RESIZE_PAPER_TYPE") ( "$RESIZE_WIDTH" x "$RESIZE_HEIGHT" ) pts" # Change page size "$GSBIN" \ @@ -270,9 +290,9 @@ pageResize() { -dDEVICEWIDTHPOINTS=$RESIZE_WIDTH -dDEVICEHEIGHTPOINTS=$RESIZE_HEIGHT \ -dFIXEDMEDIA -dPDFFitPage \ -sOutputFile="$OUTFILEPDF" \ --f "$INFILEPDF" & - wait ${!} +-f "$INFILEPDF" + return $? } From d3fd1191f9378fdcdec55d46a9efc6d6fd1db13b Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 23:12:51 -0300 Subject: [PATCH 23/59] more changes to verbose messages --- pdfScale.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pdfScale.sh b/pdfScale.sh index b2124ef..5ac7360 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -243,6 +243,9 @@ pageScale() { vprint " Translation X: $XTRANS" vprint " Translation Y: $YTRANS" + local increase=$(echo "scale=0; (($SCALE - 1) * 100)/1" | "$BCBIN") + vprint " Run Scaling: $increase %" + # Scale page "$GSBIN" \ -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \ @@ -279,7 +282,7 @@ pageResize() { vprint " Flip Detect: Disabled" fi - vprint " Resizing to: $(uppercase "$RESIZE_PAPER_TYPE") ( "$RESIZE_WIDTH" x "$RESIZE_HEIGHT" ) pts" + vprint " Run Resizing: $(uppercase "$RESIZE_PAPER_TYPE") ( "$RESIZE_WIDTH" x "$RESIZE_HEIGHT" ) pts" # Change page size "$GSBIN" \ From a68c3255448fd4b7970d80f87effac64d1fe281d Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 23:17:55 -0300 Subject: [PATCH 24/59] changing readme run examples --- README.md | 61 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 31 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index cc5d588..73bce57 100644 --- a/README.md +++ b/README.md @@ -152,59 +152,60 @@ Examples: pdfScale.sh -h ``` -## Example runs +## Example Runs ``` -$ pdfscale -v -r a0 -s 1.05 ../mixsync\ manual\ v1-2-3.pdf +pdfscale -v -r a0 -s 1.05 ../mixsync\ manual\ v1-2-3.pdf pdfscale v2.0.0 - Verbose Execution -Checking for ghostscript and bcmath Input file: ../mixsync manual v1-2-3.pdf Output file: ../mixsync manual v1-2-3.A0.SCALED.pdf Get Page Size: Adaptive Enabled Method: Cat + Grep - Mixed Tasks: Resize & Scale - Scale factor: 1.05 Source Width: 842 postscript-points Source Height: 595 postscript-points + Mixed Tasks: Resize & Scale + Scale factor: 1.05 Flip Detect: Wrong orientation! Inverting Width <-> Height - Resizing to: A0 ( 3370 x 2384 ) + Run Resizing: A0 ( 3370 x 2384 ) pts New Width: 3370 postscript-points New Height: 2384 postscript-points Translation X: -80.236330 Translation Y: -56.760656 + Run Scaling: 5 % + Final Status: File created successfully ``` ``` -$ pdfscale -v -v -s 0.9 ../input-nup.pdf "../my glorius PDF" -pdfscale v2.0.0 - Verbose Execution -2017-05-13:20:22:18 | Checking for ghostscript and bcmath -2017-05-13:20:22:18 | Input file: ../input-nup.pdf -2017-05-13:20:22:18 | Output file: ../my glorius PDF.pdf -2017-05-13:20:22:18 | Get Page Size: Adaptive Enabled -2017-05-13:20:22:18 | Method: Cat + Grep -2017-05-13:20:22:18 | Failed -2017-05-13:20:22:18 | Method: Mac Quartz mdls -2017-05-13:20:22:18 | Single Task: Scale PDF Contents -2017-05-13:20:22:18 | Scale factor: 0.9 (manual) -2017-05-13:20:22:18 | Source Width: 842 postscript-points -2017-05-13:20:22:18 | Source Height: 595 postscript-points -2017-05-13:20:22:18 | Translation X: 46.777310 -2017-05-13:20:22:18 | Translation Y: 33.055225 +$ pdfscale -v -v -s 0.9 ../input-nup.pdf "../my glorius PDF" +2017-05-14:23:16:05 | pdfscale v2.0.0 - Verbose Execution +2017-05-14:23:16:05 | Input file: ../input-nup.pdf +2017-05-14:23:16:05 | Output file: ../my glorius PDF.pdf +2017-05-14:23:16:05 | Get Page Size: Adaptive Enabled +2017-05-14:23:16:05 | Method: Cat + Grep +2017-05-14:23:16:05 | Failed +2017-05-14:23:16:05 | Method: Mac Quartz mdls +2017-05-14:23:16:05 | Source Width: 842 postscript-points +2017-05-14:23:16:05 | Source Height: 595 postscript-points +2017-05-14:23:16:05 | Single Task: Scale PDF Contents +2017-05-14:23:16:05 | Scale factor: 0.9 (manual) +2017-05-14:23:16:05 | Translation X: 46.777310 +2017-05-14:23:16:05 | Translation Y: 33.055225 +2017-05-14:23:16:05 | Run Scaling: -10 % +2017-05-14:23:16:05 | Final Status: File created successfully ``` ``` -$ pdfscale -v -r a2 "../mixsync manual v1-2-3.pdf" +pdfscale -v -r a2 ../input.pdf pdfscale v2.0.0 - Verbose Execution -Checking for ghostscript and bcmath - Input file: ../mixsync manual v1-2-3.pdf - Output file: ../mixsync manual v1-2-3.A2.pdf + Input file: ../input.pdf + Output file: ../input.A2.pdf Get Page Size: Adaptive Enabled Method: Cat + Grep + Source Width: 595 postscript-points + Source Height: 842 postscript-points Single Task: Resize PDF Paper Scale factor: Disabled (resize only) - Source Width: 842 postscript-points - Source Height: 595 postscript-points - Flip Detect: Wrong orientation! - Inverting Width <-> Height - Resizing to: A2 ( 1684 x 1191 ) + Flip Detect: No change needed + Run Resizing: A2 ( 1191 x 1684 ) pts + Final Status: File created successfully ``` ## GhostScript Paper Tables ``` From 24ce32fef99f085b23cc00e26e8612b215ccea92 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 23:46:26 -0300 Subject: [PATCH 25/59] more changes to verbose messages, updated run examples on readme --- README.md | 51 +++++++++++++++++++++++++-------------------------- pdfScale.sh | 25 ++++++++++++++++--------- 2 files changed, 41 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 73bce57..1f680c8 100644 --- a/README.md +++ b/README.md @@ -154,55 +154,54 @@ Examples: ## Example Runs ``` -pdfscale -v -r a0 -s 1.05 ../mixsync\ manual\ v1-2-3.pdf +$ pdfscale -v -r a0 -s 1.05 ../mixsync\ manual\ v1-2-3.pdf pdfscale v2.0.0 - Verbose Execution - Input file: ../mixsync manual v1-2-3.pdf - Output file: ../mixsync manual v1-2-3.A0.SCALED.pdf + Mixed Tasks: Resize & Scale + Input File: ../mixsync manual v1-2-3.pdf + Output File: ../mixsync manual v1-2-3.A0.SCALED.pdf Get Page Size: Adaptive Enabled Method: Cat + Grep Source Width: 842 postscript-points Source Height: 595 postscript-points - Mixed Tasks: Resize & Scale - Scale factor: 1.05 Flip Detect: Wrong orientation! Inverting Width <-> Height Run Resizing: A0 ( 3370 x 2384 ) pts New Width: 3370 postscript-points New Height: 2384 postscript-points + Scale Factor: 1.05 Translation X: -80.236330 Translation Y: -56.760656 Run Scaling: 5 % Final Status: File created successfully ``` ``` -$ pdfscale -v -v -s 0.9 ../input-nup.pdf "../my glorius PDF" -2017-05-14:23:16:05 | pdfscale v2.0.0 - Verbose Execution -2017-05-14:23:16:05 | Input file: ../input-nup.pdf -2017-05-14:23:16:05 | Output file: ../my glorius PDF.pdf -2017-05-14:23:16:05 | Get Page Size: Adaptive Enabled -2017-05-14:23:16:05 | Method: Cat + Grep -2017-05-14:23:16:05 | Failed -2017-05-14:23:16:05 | Method: Mac Quartz mdls -2017-05-14:23:16:05 | Source Width: 842 postscript-points -2017-05-14:23:16:05 | Source Height: 595 postscript-points -2017-05-14:23:16:05 | Single Task: Scale PDF Contents -2017-05-14:23:16:05 | Scale factor: 0.9 (manual) -2017-05-14:23:16:05 | Translation X: 46.777310 -2017-05-14:23:16:05 | Translation Y: 33.055225 -2017-05-14:23:16:05 | Run Scaling: -10 % -2017-05-14:23:16:05 | Final Status: File created successfully +$ pdfscale -v -v -s 0.9 ../input-nup.pdf "../My Glorius PDF" +2017-05-14:23:43:46 | pdfscale v2.0.0 - Verbose Execution +2017-05-14:23:43:46 | Input File: ../input-nup.pdf +2017-05-14:23:43:46 | Output File: ../My Glorius PDF.pdf +2017-05-14:23:43:46 | Get Page Size: Adaptive Enabled +2017-05-14:23:43:46 | Method: Cat + Grep +2017-05-14:23:43:46 | Failed +2017-05-14:23:43:46 | Method: Mac Quartz mdls +2017-05-14:23:43:46 | Source Width: 842 postscript-points +2017-05-14:23:43:46 | Source Height: 595 postscript-points +2017-05-14:23:43:46 | Scale Factor: 0.9 (manual) +2017-05-14:23:43:46 | Translation X: 46.777310 +2017-05-14:23:43:46 | Translation Y: 33.055225 +2017-05-14:23:43:46 | Run Scaling: -10 % +2017-05-14:23:43:47 | Final Status: File created successfully ``` ``` -pdfscale -v -r a2 ../input.pdf +$ pdfscale -v -r a2 ../input.pdf pdfscale v2.0.0 - Verbose Execution - Input file: ../input.pdf - Output file: ../input.A2.pdf + Single Task: Resize PDF Paper + Input File: ../input.pdf + Output File: ../input.A2.pdf Get Page Size: Adaptive Enabled Method: Cat + Grep Source Width: 595 postscript-points Source Height: 842 postscript-points - Single Task: Resize PDF Paper - Scale factor: Disabled (resize only) + Scale Factor: Disabled (resize only) Flip Detect: No change needed Run Resizing: A2 ( 1191 x 1684 ) pts Final Status: File created successfully diff --git a/pdfScale.sh b/pdfScale.sh index 5ac7360..15c98aa 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -77,17 +77,14 @@ EXIT_INVALID_PAPER_SIZE=50 # Main function called at the end main() { - printVersion 1 'verbose' checkDeps - vprint " Input file: $INFILEPDF" - vprint " Output file: $OUTFILEPDF" + vprint " Input File: $INFILEPDF" + vprint " Output File: $OUTFILEPDF" getPageSize vPrintSourcePageSizes ' Source' local finalRet=$EXIT_ERROR if isMixedMode; then - vprint " Mixed Tasks: Resize & Scale" - vprint " Scale factor: $SCALE" outputFile="$OUTFILEPDF" # backup outFile name tempFile="${OUTFILEPDF%.pdf}.__TEMP__.pdf" # set a temp file name OUTFILEPDF="$tempFile" # set output to tmp file @@ -98,20 +95,19 @@ main() { PGWIDTH=$RESIZE_WIDTH # we already know the new page size PGHEIGHT=$RESIZE_HEIGHT # from the last command (Resize) vPrintSourcePageSizes ' New' + vPrintScaleFactor pageScale # scale the resized pdf finalRet=$(($finalRet+$?)) # remove tmp file rm "$tempFile" >/dev/null 2>&1 || printError "Error when removing temporary file: $tempFile" elif isResizeMode; then - vprint " Single Task: Resize PDF Paper" - vprint " Scale factor: Disabled (resize only)" + vPrintScaleFactor "Disabled (resize only)" pageResize finalRet=$? else local scaleMode="" - vprint " Single Task: Scale PDF Contents" isManualScaledMode && scaleMode='(manual)' || scaleMode='(auto)' - vprint " Scale factor: $SCALE $scaleMode" + vPrintScaleFactor "$SCALE $scaleMode" pageScale finalRet=$? fi @@ -206,12 +202,16 @@ getOptions() { isPDF "$INFILEPDF" || initError "Input file is not a PDF file: $INFILEPDF" $EXIT_INPUT_NOT_PDF isFile "$INFILEPDF" || initError "Input file not found: $INFILEPDF" $EXIT_FILE_NOT_FOUND + printVersion 1 'verbose' if isEmpty "$2"; then if isMixedMode; then + vprint " Mixed Tasks: Resize & Scale" OUTFILEPDF="${INFILEPDF%.pdf}.$(uppercase $RESIZE_PAPER_TYPE).SCALED.pdf" elif isResizeMode; then + vprint " Single Task: Resize PDF Paper" OUTFILEPDF="${INFILEPDF%.pdf}.$(uppercase $RESIZE_PAPER_TYPE).pdf" else + vprint " Single Task: Scale PDF Contents" OUTFILEPDF="${INFILEPDF%.pdf}.SCALED.pdf" fi else @@ -977,6 +977,13 @@ printVersion() { fi } +# Prints the scale factor to screen, or custom message +vPrintScaleFactor() { + local scaleMsg="$SCALE" + isNotEmpty "$1" && scaleMsg="$1" + vprint " Scale Factor: $scaleMsg" +} + # Prints help info printHelp() { From e895ecf8b26d835d706174701916fa34fbc2ae7f Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Sun, 14 May 2017 23:58:47 -0300 Subject: [PATCH 26/59] fixing task verbose message, simpler output file name detection, readme reflecting it --- README.md | 29 +++++++++++++++-------------- pdfScale.sh | 21 +++++++++------------ 2 files changed, 24 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 1f680c8..31f5eab 100644 --- a/README.md +++ b/README.md @@ -176,20 +176,21 @@ pdfscale v2.0.0 - Verbose Execution ``` ``` $ pdfscale -v -v -s 0.9 ../input-nup.pdf "../My Glorius PDF" -2017-05-14:23:43:46 | pdfscale v2.0.0 - Verbose Execution -2017-05-14:23:43:46 | Input File: ../input-nup.pdf -2017-05-14:23:43:46 | Output File: ../My Glorius PDF.pdf -2017-05-14:23:43:46 | Get Page Size: Adaptive Enabled -2017-05-14:23:43:46 | Method: Cat + Grep -2017-05-14:23:43:46 | Failed -2017-05-14:23:43:46 | Method: Mac Quartz mdls -2017-05-14:23:43:46 | Source Width: 842 postscript-points -2017-05-14:23:43:46 | Source Height: 595 postscript-points -2017-05-14:23:43:46 | Scale Factor: 0.9 (manual) -2017-05-14:23:43:46 | Translation X: 46.777310 -2017-05-14:23:43:46 | Translation Y: 33.055225 -2017-05-14:23:43:46 | Run Scaling: -10 % -2017-05-14:23:43:47 | Final Status: File created successfully +2017-05-14:23:55:33 | pdfscale v2.0.0 - Verbose Execution +2017-05-14:23:55:33 | Single Task: Scale PDF Contents +2017-05-14:23:55:33 | Input File: ../input-nup.pdf +2017-05-14:23:55:33 | Output File: ../My Glorius PDF.pdf +2017-05-14:23:55:33 | Get Page Size: Adaptive Enabled +2017-05-14:23:55:33 | Method: Cat + Grep +2017-05-14:23:55:33 | Failed +2017-05-14:23:55:33 | Method: Mac Quartz mdls +2017-05-14:23:55:33 | Source Width: 842 postscript-points +2017-05-14:23:55:33 | Source Height: 595 postscript-points +2017-05-14:23:55:33 | Scale Factor: 0.9 (manual) +2017-05-14:23:55:33 | Translation X: 46.777310 +2017-05-14:23:55:33 | Translation Y: 33.055225 +2017-05-14:23:55:33 | Run Scaling: -10 % +2017-05-14:23:55:33 | Final Status: File created successfully ``` ``` $ pdfscale -v -r a2 ../input.pdf diff --git a/pdfScale.sh b/pdfScale.sh index 15c98aa..2d8f666 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -203,20 +203,17 @@ getOptions() { isFile "$INFILEPDF" || initError "Input file not found: $INFILEPDF" $EXIT_FILE_NOT_FOUND printVersion 1 'verbose' - if isEmpty "$2"; then - if isMixedMode; then - vprint " Mixed Tasks: Resize & Scale" - OUTFILEPDF="${INFILEPDF%.pdf}.$(uppercase $RESIZE_PAPER_TYPE).SCALED.pdf" - elif isResizeMode; then - vprint " Single Task: Resize PDF Paper" - OUTFILEPDF="${INFILEPDF%.pdf}.$(uppercase $RESIZE_PAPER_TYPE).pdf" - else - vprint " Single Task: Scale PDF Contents" - OUTFILEPDF="${INFILEPDF%.pdf}.SCALED.pdf" - fi + if isMixedMode; then + vprint " Mixed Tasks: Resize & Scale" + isEmpty "$2" && OUTFILEPDF="${INFILEPDF%.pdf}.$(uppercase $RESIZE_PAPER_TYPE).SCALED.pdf" + elif isResizeMode; then + vprint " Single Task: Resize PDF Paper" + isEmpty "$2" && OUTFILEPDF="${INFILEPDF%.pdf}.$(uppercase $RESIZE_PAPER_TYPE).pdf" else - OUTFILEPDF="${2%.pdf}.pdf" + vprint " Single Task: Scale PDF Contents" + isEmpty "$2" && OUTFILEPDF="${INFILEPDF%.pdf}.SCALED.pdf" fi + isNotEmpty "$2" && OUTFILEPDF="${2%.pdf}.pdf" } From 35f926bfa5ea0d83d9ba92c0ec989ddca5f65e91 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 00:04:23 -0300 Subject: [PATCH 27/59] messing with readme --- README.md | 113 +++++++++++++++++++++++++++--------------------------- 1 file changed, 57 insertions(+), 56 deletions(-) diff --git a/README.md b/README.md index 31f5eab..bfd38a7 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,63 @@ sudo yum install imagemagick pdfinfo brew install imagemagick xpdf ``` - +## Example Runs + +``` +$ pdfscale -v -r a0 -s 1.05 ../mixsync\ manual\ v1-2-3.pdf +pdfscale v2.0.0 - Verbose Execution + Mixed Tasks: Resize & Scale + Input File: ../mixsync manual v1-2-3.pdf + Output File: ../mixsync manual v1-2-3.A0.SCALED.pdf + Get Page Size: Adaptive Enabled + Method: Cat + Grep + Source Width: 842 postscript-points + Source Height: 595 postscript-points + Flip Detect: Wrong orientation! + Inverting Width <-> Height + Run Resizing: A0 ( 3370 x 2384 ) pts + New Width: 3370 postscript-points + New Height: 2384 postscript-points + Scale Factor: 1.05 + Translation X: -80.236330 + Translation Y: -56.760656 + Run Scaling: 5 % + Final Status: File created successfully +``` +``` +$ pdfscale -v -v -s 0.9 ../input-nup.pdf "../My Glorius PDF" +2017-05-14:23:55:33 | pdfscale v2.0.0 - Verbose Execution +2017-05-14:23:55:33 | Single Task: Scale PDF Contents +2017-05-14:23:55:33 | Input File: ../input-nup.pdf +2017-05-14:23:55:33 | Output File: ../My Glorius PDF.pdf +2017-05-14:23:55:33 | Get Page Size: Adaptive Enabled +2017-05-14:23:55:33 | Method: Cat + Grep +2017-05-14:23:55:33 | Failed +2017-05-14:23:55:33 | Method: Mac Quartz mdls +2017-05-14:23:55:33 | Source Width: 842 postscript-points +2017-05-14:23:55:33 | Source Height: 595 postscript-points +2017-05-14:23:55:33 | Scale Factor: 0.9 (manual) +2017-05-14:23:55:33 | Translation X: 46.777310 +2017-05-14:23:55:33 | Translation Y: 33.055225 +2017-05-14:23:55:33 | Run Scaling: -10 % +2017-05-14:23:55:33 | Final Status: File created successfully +``` +``` +$ pdfscale -v -r a2 ../input.pdf +pdfscale v2.0.0 - Verbose Execution + Single Task: Resize PDF Paper + Input File: ../input.pdf + Output File: ../input.A2.pdf + Get Page Size: Adaptive Enabled + Method: Cat + Grep + Source Width: 595 postscript-points + Source Height: 842 postscript-points + Scale Factor: Disabled (resize only) + Flip Detect: No change needed + Run Resizing: A2 ( 1191 x 1684 ) pts + Final Status: File created successfully +``` + ## Help info ``` $ pdfscale -h @@ -152,61 +208,6 @@ Examples: pdfScale.sh -h ``` -## Example Runs -``` -$ pdfscale -v -r a0 -s 1.05 ../mixsync\ manual\ v1-2-3.pdf -pdfscale v2.0.0 - Verbose Execution - Mixed Tasks: Resize & Scale - Input File: ../mixsync manual v1-2-3.pdf - Output File: ../mixsync manual v1-2-3.A0.SCALED.pdf - Get Page Size: Adaptive Enabled - Method: Cat + Grep - Source Width: 842 postscript-points - Source Height: 595 postscript-points - Flip Detect: Wrong orientation! - Inverting Width <-> Height - Run Resizing: A0 ( 3370 x 2384 ) pts - New Width: 3370 postscript-points - New Height: 2384 postscript-points - Scale Factor: 1.05 - Translation X: -80.236330 - Translation Y: -56.760656 - Run Scaling: 5 % - Final Status: File created successfully -``` -``` -$ pdfscale -v -v -s 0.9 ../input-nup.pdf "../My Glorius PDF" -2017-05-14:23:55:33 | pdfscale v2.0.0 - Verbose Execution -2017-05-14:23:55:33 | Single Task: Scale PDF Contents -2017-05-14:23:55:33 | Input File: ../input-nup.pdf -2017-05-14:23:55:33 | Output File: ../My Glorius PDF.pdf -2017-05-14:23:55:33 | Get Page Size: Adaptive Enabled -2017-05-14:23:55:33 | Method: Cat + Grep -2017-05-14:23:55:33 | Failed -2017-05-14:23:55:33 | Method: Mac Quartz mdls -2017-05-14:23:55:33 | Source Width: 842 postscript-points -2017-05-14:23:55:33 | Source Height: 595 postscript-points -2017-05-14:23:55:33 | Scale Factor: 0.9 (manual) -2017-05-14:23:55:33 | Translation X: 46.777310 -2017-05-14:23:55:33 | Translation Y: 33.055225 -2017-05-14:23:55:33 | Run Scaling: -10 % -2017-05-14:23:55:33 | Final Status: File created successfully -``` -``` -$ pdfscale -v -r a2 ../input.pdf -pdfscale v2.0.0 - Verbose Execution - Single Task: Resize PDF Paper - Input File: ../input.pdf - Output File: ../input.A2.pdf - Get Page Size: Adaptive Enabled - Method: Cat + Grep - Source Width: 595 postscript-points - Source Height: 842 postscript-points - Scale Factor: Disabled (resize only) - Flip Detect: No change needed - Run Resizing: A2 ( 1191 x 1684 ) pts - Final Status: File created successfully -``` ## GhostScript Paper Tables ``` $ ./pdfScale.sh -p From d1f18f236f26e9635bb40a51ec3649baf72a2f5c Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 00:13:36 -0300 Subject: [PATCH 28/59] messing with readme --- README.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/README.md b/README.md index bfd38a7..1224bf6 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ brew install imagemagick xpdf ## Example Runs +#### Resize to A0 and scale by 1.05 (+5%) ``` $ pdfscale -v -r a0 -s 1.05 ../mixsync\ manual\ v1-2-3.pdf pdfscale v2.0.0 - Verbose Execution @@ -76,6 +77,7 @@ pdfscale v2.0.0 - Verbose Execution Run Scaling: 5 % Final Status: File created successfully ``` +#### Scale by 0.9 (-10%) ``` $ pdfscale -v -v -s 0.9 ../input-nup.pdf "../My Glorius PDF" 2017-05-14:23:55:33 | pdfscale v2.0.0 - Verbose Execution @@ -94,6 +96,7 @@ $ pdfscale -v -v -s 0.9 ../input-nup.pdf "../My Glorius PDF" 2017-05-14:23:55:33 | Run Scaling: -10 % 2017-05-14:23:55:33 | Final Status: File created successfully ``` +#### Resize to A2 ``` $ pdfscale -v -r a2 ../input.pdf pdfscale v2.0.0 - Verbose Execution @@ -109,6 +112,27 @@ pdfscale v2.0.0 - Verbose Execution Run Resizing: A2 ( 1191 x 1684 ) pts Final Status: File created successfully ``` +#### Resize to custom 200x200 mm and Scale by 0.95 (-5%) +``` +$ pdfscale -v -v -r 'custom mm 200 200' -s 0.9 ../mixsync\ manual\ v1-2-3.pdf +2017-05-15:00:12:20 | pdfscale v2.0.0 - Verbose Execution +2017-05-15:00:12:20 | Mixed Tasks: Resize & Scale +2017-05-15:00:12:20 | Input File: ../mixsync manual v1-2-3.pdf +2017-05-15:00:12:20 | Output File: ../mixsync manual v1-2-3.CUSTOM.SCALED.pdf +2017-05-15:00:12:20 | Get Page Size: Adaptive Enabled +2017-05-15:00:12:20 | Method: Cat + Grep +2017-05-15:00:12:20 | Source Width: 842 postscript-points +2017-05-15:00:12:20 | Source Height: 595 postscript-points +2017-05-15:00:12:20 | Flip Detect: No change needed +2017-05-15:00:12:20 | Run Resizing: CUSTOM ( 567 x 567 ) pts +2017-05-15:00:12:20 | New Width: 567 postscript-points +2017-05-15:00:12:20 | New Height: 567 postscript-points +2017-05-15:00:12:20 | Scale Factor: 0.9 +2017-05-15:00:12:20 | Translation X: 31.499685 +2017-05-15:00:12:20 | Translation Y: 31.499685 +2017-05-15:00:12:20 | Run Scaling: -10 % +2017-05-15:00:12:20 | Final Status: File created successfully +``` ## Help info ``` From 0d18ac7a7f6bc32ffaa50f2d5139e0caada8f46f Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 00:24:33 -0300 Subject: [PATCH 29/59] more tunning --- README.md | 2 +- pdfScale.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1224bf6..43ee855 100644 --- a/README.md +++ b/README.md @@ -190,7 +190,7 @@ Page Detection Modes: p, pdfinfo Forces the use of PDFInfo i, identify Forces the use of ImageMagick's Identify -Valid Ghostscript Paper Names: +Valid Paper Names: A0 A1 A2 A3 A4 A4SMALL A5 A6 A7 A8 A9 A10 ISOB0 ISOB1 ISOB2 diff --git a/pdfScale.sh b/pdfScale.sh index 2d8f666..90f6d5e 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -1039,7 +1039,7 @@ Page Detection Modes: p, pdfinfo Forces the use of PDFInfo i, identify Forces the use of ImageMagick's Identify -Valid Ghostscript Paper Names: +Valid Paper Names: $paperList Custom Paper Size: From 3f2d134bdbb6ddc4f6e3afd213fd2d8a5bc820c6 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 00:28:01 -0300 Subject: [PATCH 30/59] messing with readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 43ee855..559030e 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ brew install imagemagick xpdf ## Example Runs -#### Resize to A0 and scale by 1.05 (+5%) +#### Resize to A0 and Scale by 1.05 (+5%) ``` $ pdfscale -v -r a0 -s 1.05 ../mixsync\ manual\ v1-2-3.pdf pdfscale v2.0.0 - Verbose Execution From 14531e554cc93bbcc9bb2ff6ec3739f5bebae2e6 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 00:37:39 -0300 Subject: [PATCH 31/59] cleanning up --- pdfScale.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pdfScale.sh b/pdfScale.sh index 90f6d5e..0a5f622 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -81,7 +81,7 @@ main() { vprint " Input File: $INFILEPDF" vprint " Output File: $OUTFILEPDF" getPageSize - vPrintSourcePageSizes ' Source' + vPrintPageSizes ' Source' local finalRet=$EXIT_ERROR if isMixedMode; then @@ -94,7 +94,7 @@ main() { OUTFILEPDF="$outputFile" # reset final target PGWIDTH=$RESIZE_WIDTH # we already know the new page size PGHEIGHT=$RESIZE_HEIGHT # from the last command (Resize) - vPrintSourcePageSizes ' New' + vPrintPageSizes ' New' vPrintScaleFactor pageScale # scale the resized pdf finalRet=$(($finalRet+$?)) @@ -540,7 +540,7 @@ notAdaptiveFailed() { } # Verbose print of the Width and Height (Source or New) to screen -vPrintSourcePageSizes() { +vPrintPageSizes() { vprint " $1 Width: $PGWIDTH postscript-points" vprint "$1 Height: $PGHEIGHT postscript-points" } From c70edc969382ff43296e5182d3e3bc6bcce184a8 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 00:42:06 -0300 Subject: [PATCH 32/59] messing with readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 559030e..aa96b6e 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ A temporary file is used in `mixed mode`, at the target location. The script uses `basename`, `cat`, `grep`, `bc`, `head` and `gs` (ghostscript). You probably have everything installed already, except for ghostscript. Optional dependencies are `imagemagick`, `pdfinfo` and `mdls` (Mac). -This app is focused in `Bash`, so it will probably not run in other Shells. +This app is focused in `Bash`, so it will probably not run in other shells. ##### apt-get ``` From 202a714ccecc5f9b936bce6c900eff1907948eb6 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 00:44:47 -0300 Subject: [PATCH 33/59] cleanning up --- README.md | 2 +- pdfScale.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index aa96b6e..d3c7277 100644 --- a/README.md +++ b/README.md @@ -190,7 +190,7 @@ Page Detection Modes: p, pdfinfo Forces the use of PDFInfo i, identify Forces the use of ImageMagick's Identify -Valid Paper Names: +Valid Paper Names: (case-insensitive) A0 A1 A2 A3 A4 A4SMALL A5 A6 A7 A8 A9 A10 ISOB0 ISOB1 ISOB2 diff --git a/pdfScale.sh b/pdfScale.sh index 0a5f622..32a8b80 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -1039,7 +1039,7 @@ Page Detection Modes: p, pdfinfo Forces the use of PDFInfo i, identify Forces the use of ImageMagick's Identify -Valid Paper Names: +Valid Paper Names: (case-insensitive) $paperList Custom Paper Size: From 4e02c87e7a549a1fead48bf58986ac4f3bf3e8b3 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 02:07:50 -0300 Subject: [PATCH 34/59] changes to flip detection, adding GS autoRotation options for resizing --- pdfScale.sh | 197 ++++++++++++++++++++++++++++++++-------------------- 1 file changed, 123 insertions(+), 74 deletions(-) diff --git a/pdfScale.sh b/pdfScale.sh index 32a8b80..4768f5c 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -50,6 +50,8 @@ MODE="" RESIZE_PAPER_TYPE="" CUSTOM_RESIZE_PAPER=$FALSE FLIP_DETECTION=$TRUE +FLIP_FORCE=$FALSE +AUTO_ROTATION='/PageByPage' PGWIDTH="" PGHEIGHT="" RESIZE_WIDTH="" @@ -122,7 +124,76 @@ main() { } -########################## INITIALIZER ########################## +###################### GHOSTSCRIPT CALLS ####################### + +# Runs the ghostscript scaling script +pageScale() { + # Compute translation factors (to center page). + XTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGWIDTH" | "$BCBIN") + YTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGHEIGHT" | "$BCBIN") + vprint " Translation X: $XTRANS" + vprint " Translation Y: $YTRANS" + + local increase=$(echo "scale=0; (($SCALE - 1) * 100)/1" | "$BCBIN") + vprint " Run Scaling: $increase %" + + # Scale page + "$GSBIN" \ +-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \ +-dCompatibilityLevel="1.5" -dPDFSETTINGS="/printer" \ +-dColorConversionStrategy=/LeaveColorUnchanged \ +-dSubsetFonts=true -dEmbedAllFonts=true \ +-dDEVICEWIDTHPOINTS=$PGWIDTH -dDEVICEHEIGHTPOINTS=$PGHEIGHT \ +-sOutputFile="$OUTFILEPDF" \ +-c "<> setpagedevice" \ +-f "$INFILEPDF" + + return $? +} + + +# Runs the ghostscript paper resize script +pageResize() { + # Get new paper sizes if not custom paper + isNotCustomPaper && getGSPaperSize "$RESIZE_PAPER_TYPE" + + vprint " Auto Rotate: $(basename $AUTO_ROTATION)" + + # Flip detect + local tmpInverter="" + if [[ $FLIP_DETECTION -eq $TRUE || $FLIP_FORCE -eq $TRUE ]]; then + if [[ $PGWIDTH -gt $PGHEIGHT && $RESIZE_WIDTH -lt $RESIZE_HEIGHT ]] || [[ $FLIP_FORCE -eq $TRUE ]]; then + [[ $FLIP_FORCE -eq $TRUE ]] && vprint " Flip Detect: Forced Mode!" || vprint " Flip Detect: Wrong orientation detected!" + vprint " Inverting Width <-> Height" + tmpInverter=$RESIZE_HEIGHT + RESIZE_HEIGHT=$RESIZE_WIDTH + RESIZE_WIDTH=$tmpInverter + else + vprint " Flip Detect: No change needed" + fi + else + vprint " Flip Detect: Disabled" + fi + + vprint " Run Resizing: $(uppercase "$RESIZE_PAPER_TYPE") ( "$RESIZE_WIDTH" x "$RESIZE_HEIGHT" ) pts" + + # Change page size + "$GSBIN" \ +-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \ +-dCompatibilityLevel="1.5" -dPDFSETTINGS="/printer" \ +-dColorConversionStrategy=/LeaveColorUnchanged \ +-dSubsetFonts=true -dEmbedAllFonts=true \ +-dDEVICEWIDTHPOINTS=$RESIZE_WIDTH -dDEVICEHEIGHTPOINTS=$RESIZE_HEIGHT \ +-dAutoRotatePages=$AUTO_ROTATION \ +-dFIXEDMEDIA -dPDFFitPage \ +-sOutputFile="$OUTFILEPDF" \ +-f "$INFILEPDF" + + return $? +} + + +########################## INITIALIZERS ######################### # Loads external dependencies and checks for errors initDeps() { @@ -160,7 +231,7 @@ checkDeps() { # Parse options getOptions() { - while getopts ":vhVs:m:r:pf" o; do + while getopts ":vhVs:m:r:pf:a:" o; do case "${o}" in v) ((VERBOSE++)) @@ -187,7 +258,10 @@ getOptions() { exit $EXIT_SUCCESS ;; f) - FLIP_DETECTION=$FALSE + parseFlipDetectionMode ${OPTARG} + ;; + a) + parseAutoRotationMode ${OPTARG} ;; *) initError "Invalid Option: -$OPTARG" $EXIT_INVALID_OPTION @@ -229,75 +303,6 @@ parseScale() { SCALE="$1" } - -###################### GHOSTSCRIPT CALLS ####################### - -# Runs the ghostscript scaling script -pageScale() { - # Compute translation factors (to center page). - XTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGWIDTH" | "$BCBIN") - YTRANS=$(echo "scale=6; 0.5*(1.0-$SCALE)/$SCALE*$PGHEIGHT" | "$BCBIN") - vprint " Translation X: $XTRANS" - vprint " Translation Y: $YTRANS" - - local increase=$(echo "scale=0; (($SCALE - 1) * 100)/1" | "$BCBIN") - vprint " Run Scaling: $increase %" - - # Scale page - "$GSBIN" \ --q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \ --dCompatibilityLevel="1.5" -dPDFSETTINGS="/printer" \ --dColorConversionStrategy=/LeaveColorUnchanged \ --dSubsetFonts=true -dEmbedAllFonts=true \ --dDEVICEWIDTHPOINTS=$PGWIDTH -dDEVICEHEIGHTPOINTS=$PGHEIGHT \ --sOutputFile="$OUTFILEPDF" \ --c "<> setpagedevice" \ --f "$INFILEPDF" - - return $? -} - - -# Runs the ghostscript paper resize script -pageResize() { - # Get new paper sizes if not custom paper - isNotCustomPaper && getGSPaperSize "$RESIZE_PAPER_TYPE" - - # Flip detect - local tmpInverter="" - if [[ $FLIP_DETECTION -eq $TRUE ]]; then - if [[ $PGWIDTH -gt $PGHEIGHT && $RESIZE_WIDTH -lt $RESIZE_HEIGHT ]]; then - vprint " Flip Detect: Wrong orientation!" - vprint " Inverting Width <-> Height" - tmpInverter=$RESIZE_HEIGHT - RESIZE_HEIGHT=$RESIZE_WIDTH - RESIZE_WIDTH=$tmpInverter - else - vprint " Flip Detect: No change needed" - fi - else - vprint " Flip Detect: Disabled" - fi - - vprint " Run Resizing: $(uppercase "$RESIZE_PAPER_TYPE") ( "$RESIZE_WIDTH" x "$RESIZE_HEIGHT" ) pts" - - # Change page size - "$GSBIN" \ --q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dSAFER \ --dCompatibilityLevel="1.5" -dPDFSETTINGS="/printer" \ --dColorConversionStrategy=/LeaveColorUnchanged \ --dSubsetFonts=true -dEmbedAllFonts=true \ --dDEVICEWIDTHPOINTS=$RESIZE_WIDTH -dDEVICEHEIGHTPOINTS=$RESIZE_HEIGHT \ --dFIXEDMEDIA -dPDFFitPage \ --sOutputFile="$OUTFILEPDF" \ --f "$INFILEPDF" - - return $? -} - - -################### PDF PAGE SIZE DETECTION #################### - # Parse a forced mode of operation parseMode() { if isEmpty "$1"; then @@ -339,6 +344,47 @@ parseMode() { return $FALSE } +# Parses and validates the scaling factor +parseFlipDetectionMode() { + local param="$(lowercase $1)" + case "${param}" in + d|disable) + FLIP_DETECTION=$FALSE + FLIP_FORCE=$FALSE + ;; + f|force) + FLIP_DETECTION=$FALSE + FLIP_FORCE=$TRUE + ;; + *) + [[ "$param" != 'a' || "$param" != 'auto' ]] && printError "Error! Invalid Flip Detection Mode: \"$1\", using automatic mode!" + FLIP_DETECTION=$TRUE + FLIP_FORCE=$FALSE + ;; + esac +} + +# Parses and validates the scaling factor +parseAutoRotationMode() { + local param="$(lowercase $1)" + case "${param}" in + n|none) + AUTO_ROTATION='/None' + ;; + a|all) + AUTO_ROTATION='/All' + ;; + p|pagebypage|auto) + AUTO_ROTATION='/PageByPage' + ;; + *) + printError "Error! Invalid Auto Rotation Mode: $param, using default: $(basename $AUTO_ROTATION)" + ;; + esac +} + + +################### PDF PAGE SIZE DETECTION #################### # Gets page size using imagemagick's identify getPageSizeImagemagick() { @@ -1006,8 +1052,11 @@ Parameters: -r Triggers the Resize Paper Mode Resize PDF paper proportionally Uses a valid paper name or a custom defined paper - -f Disables the flip detection, paper will not be - rotated when inconsistent sizes are detected. + -f Flip Detection Mode, defaults to 'auto'. + Inverts Width <-> Height of a Resized PDF. + Modes: a, auto - automatic detection, default + f, force - forces flip W <-> H + d, disable - disables flipping -p Prints Ghostscript paper info tables to screen Scaling Mode: From 7f34eb21beb09f33ec5110f0913c31288cd6f3e9 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 02:13:03 -0300 Subject: [PATCH 35/59] adding autorotation to help --- pdfScale.sh | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pdfScale.sh b/pdfScale.sh index 4768f5c..a23ca53 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -1057,6 +1057,12 @@ Parameters: Modes: a, auto - automatic detection, default f, force - forces flip W <-> H d, disable - disables flipping + -a GS Auto-Rotation Setting, defaults to 'PageByPage'. + Setting for GS -dAutoRotatePages. + Modes: p, pagebypage - auto-rotates pages individually + a, all - rotates all pages (or none) depending + on a kind of \"majority decision\" + n, none - retains orientation of each page -p Prints Ghostscript paper info tables to screen Scaling Mode: From f5979cba6db0d7bc9c6c2e30612ca65408862dba Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 02:47:04 -0300 Subject: [PATCH 36/59] making stuff better :) case-insensitive page size mode and changed ifs to case switch --- pdfScale.sh | 146 ++++++++++++++++++++++++++-------------------------- 1 file changed, 74 insertions(+), 72 deletions(-) diff --git a/pdfScale.sh b/pdfScale.sh index a23ca53..4c6b6f2 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -157,13 +157,13 @@ pageResize() { # Get new paper sizes if not custom paper isNotCustomPaper && getGSPaperSize "$RESIZE_PAPER_TYPE" - vprint " Auto Rotate: $(basename $AUTO_ROTATION)" + vprint " Auto Rotate: $(basename $AUTO_ROTATION)" # Flip detect local tmpInverter="" if [[ $FLIP_DETECTION -eq $TRUE || $FLIP_FORCE -eq $TRUE ]]; then if [[ $PGWIDTH -gt $PGHEIGHT && $RESIZE_WIDTH -lt $RESIZE_HEIGHT ]] || [[ $FLIP_FORCE -eq $TRUE ]]; then - [[ $FLIP_FORCE -eq $TRUE ]] && vprint " Flip Detect: Forced Mode!" || vprint " Flip Detect: Wrong orientation detected!" + [[ $FLIP_FORCE -eq $TRUE ]] && vprint " Flip Detect: Forced Mode!" || vprint " Flip Detect: Wrong orientation detected!" vprint " Inverting Width <-> Height" tmpInverter=$RESIZE_HEIGHT RESIZE_HEIGHT=$RESIZE_WIDTH @@ -305,82 +305,79 @@ parseScale() { # Parse a forced mode of operation parseMode() { - if isEmpty "$1"; then - printError "Mode is empty, please specify the desired mode" - printError "Falling back to adaptive mode!" - ADAPTIVEMODE=$TRUE - MODE="" - return $FALSE - fi - - if [[ $1 = 'c' || $1 = 'catgrep' || $1 = 'cat+grep' || $1 = 'CatGrep' || $1 = 'C' || $1 = 'CATGREP' ]]; then - ADAPTIVEMODE=$FALSE - MODE="CATGREP" - return $TRUE - elif [[ $1 = 'i' || $1 = 'imagemagick' || $1 = 'identify' || $1 = 'ImageMagick' || $1 = 'Identify' || $1 = 'I' || $1 = 'IDENTIFY' ]]; then - ADAPTIVEMODE=$FALSE - MODE="IDENTIFY" - return $TRUE - elif [[ $1 = 'm' || $1 = 'mdls' || $1 = 'MDLS' || $1 = 'quartz' || $1 = 'mac' || $1 = 'M' ]]; then - ADAPTIVEMODE=$FALSE - MODE="MDLS" - return $TRUE - elif [[ $1 = 'p' || $1 = 'pdfinfo' || $1 = 'PDFINFO' || $1 = 'PdfInfo' || $1 = 'P' ]]; then - ADAPTIVEMODE=$FALSE - MODE="PDFINFO" - return $TRUE - elif [[ $1 = 'a' || $1 = 'adaptive' || $1 = 'automatic' || $1 = 'A' || $1 = 'ADAPTIVE' || $1 = 'AUTOMATIC' ]]; then - ADAPTIVEMODE=$TRUE - MODE="" - return $TRUE - else - printError "Invalid mode: $1" - printError "Falling back to adaptive mode!" - ADAPTIVEMODE=$TRUE - MODE="" - return $FALSE - fi + local param="$(lowercase $1)" + case "${param}" in + c|catgrep|'cat+grep') + ADAPTIVEMODE=$FALSE + MODE="CATGREP" + return $TRUE + ;; + i|imagemagick|identify) + ADAPTIVEMODE=$FALSE + MODE="IDENTIFY" + return $TRUE + ;; + m|mdls|quartz|mac) + ADAPTIVEMODE=$FALSE + MODE="MDLS" + return $TRUE + ;; + p|pdfinfo) + ADAPTIVEMODE=$FALSE + MODE="PDFINFO" + return $TRUE + ;; + *) + ADAPTIVEMODE=$TRUE + MODE="" + if [[ "$param" != 'a' && "$param" != 'auto' && "$param" != 'automatic' && "$param" != 'adaptive' ]]; then + printError "Error! Invalid PDF Size Detection Mode: \"$1\", using adaptive mode!" + return $FALSE + fi + return $TRUE + ;; + esac return $FALSE } # Parses and validates the scaling factor parseFlipDetectionMode() { - local param="$(lowercase $1)" - case "${param}" in - d|disable) - FLIP_DETECTION=$FALSE - FLIP_FORCE=$FALSE - ;; - f|force) - FLIP_DETECTION=$FALSE - FLIP_FORCE=$TRUE - ;; - *) - [[ "$param" != 'a' || "$param" != 'auto' ]] && printError "Error! Invalid Flip Detection Mode: \"$1\", using automatic mode!" - FLIP_DETECTION=$TRUE - FLIP_FORCE=$FALSE - ;; - esac + local param="$(lowercase $1)" + case "${param}" in + d|disable) + FLIP_DETECTION=$FALSE + FLIP_FORCE=$FALSE + ;; + f|force) + FLIP_DETECTION=$FALSE + FLIP_FORCE=$TRUE + ;; + *) + [[ "$param" != 'a' && "$param" != 'auto' ]] && printError "Error! Invalid Flip Detection Mode: \"$1\", using automatic mode!" + FLIP_DETECTION=$TRUE + FLIP_FORCE=$FALSE + ;; + esac } # Parses and validates the scaling factor parseAutoRotationMode() { - local param="$(lowercase $1)" - case "${param}" in - n|none) - AUTO_ROTATION='/None' - ;; - a|all) - AUTO_ROTATION='/All' - ;; - p|pagebypage|auto) - AUTO_ROTATION='/PageByPage' - ;; - *) - printError "Error! Invalid Auto Rotation Mode: $param, using default: $(basename $AUTO_ROTATION)" - ;; - esac + local param="$(lowercase $1)" + case "${param}" in + n|none) + AUTO_ROTATION='/None' + ;; + a|all) + AUTO_ROTATION='/All' + ;; + p|pagebypage|auto) + AUTO_ROTATION='/PageByPage' + ;; + *) + printError "Error! Invalid Auto Rotation Mode: $param, using default: $(basename $AUTO_ROTATION)" + ;; + esac } @@ -1013,10 +1010,13 @@ notIsAvailable() { printVersion() { local vStr="" [[ "$2" = 'verbose' ]] && vStr=" - Verbose Execution" + local strBanner="$PDFSCALE_NAME v$VERSION$vStr" if [[ $1 -eq 2 ]]; then - printError "$PDFSCALE_NAME v$VERSION$vStr" + printError "$strBanner" + elif [[ $1 -eq 3 ]]; then + echo "$strBanner" else - vprint "$PDFSCALE_NAME v$VERSION$vStr" + vprint "$strBanner" fi } @@ -1030,10 +1030,12 @@ vPrintScaleFactor() { # Prints help info printHelp() { - printVersion + printVersion 3 local paperList="$(printPaperNames)" echo " -Usage: $PDFSCALE_NAME [-v] [-s ] [-m ] [-r ] [outfile.pdf] +Usage: $PDFSCALE_NAME + $PDFSCALE_NAME [-v] [-s ] [-m ] [outfile.pdf] + $PDFSCALE_NAME [-v] [-r ] [-f ] [-a ] [outfile.pdf] $PDFSCALE_NAME -p $PDFSCALE_NAME -h $PDFSCALE_NAME -V From 3b9011f428ef2f22d58b450fa08c9e8ed50c5261 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 02:48:34 -0300 Subject: [PATCH 37/59] update help info --- README.md | 45 ++++++++++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index d3c7277..1840068 100644 --- a/README.md +++ b/README.md @@ -137,11 +137,14 @@ $ pdfscale -v -v -r 'custom mm 200 200' -s 0.9 ../mixsync\ manual\ v1-2-3.pdf ## Help info ``` $ pdfscale -h +pdfscale v2.0.0 -Usage: pdfScale.sh [-v] [-s ] [-m ] [-r ] [outfile.pdf] - pdfScale.sh -p - pdfScale.sh -h - pdfScale.sh -V +Usage: pdfscale + pdfscale [-v] [-s ] [-m ] [outfile.pdf] + pdfscale [-v] [-r ] [-f ] [-a ] [outfile.pdf] + pdfscale -p + pdfscale -h + pdfscale -V Parameters: -v Verbose mode, prints extra information @@ -157,8 +160,17 @@ Parameters: -r Triggers the Resize Paper Mode Resize PDF paper proportionally Uses a valid paper name or a custom defined paper - -f Disables the flip detection, paper will not be - rotated when inconsistent sizes are detected. + -f Flip Detection Mode, defaults to 'auto'. + Inverts Width <-> Height of a Resized PDF. + Modes: a, auto - automatic detection, default + f, force - forces flip W <-> H + d, disable - disables flipping + -a GS Auto-Rotation Setting, defaults to 'PageByPage'. + Setting for GS -dAutoRotatePages. + Modes: p, pagebypage - auto-rotates pages individually + a, all - rotates all pages (or none) depending + on a kind of "majority decision" + n, none - retains orientation of each page -p Prints Ghostscript paper info tables to screen Scaling Mode: @@ -204,8 +216,8 @@ Valid Paper Names: (case-insensitive) Custom Paper Size: Paper size can be set manually in Milimeters, Inches or Points. - Use: pdfScale.sh -r 'custom ' - Ex: pdfScale.sh -r 'custom mm 210 297' + Use: pdfscale -r 'custom ' + Ex: pdfscale -r 'custom mm 210 297' Measurements can be: mm, inch, pts. Custom paper definition MUST be quoted into a single parameter. Actual size is applied in points (mms and inches are transformed). @@ -221,15 +233,14 @@ Notes: result on cropping parts of the pdf. Examples: - pdfScale.sh myPdfFile.pdf - pdfScale.sh myPdfFile.pdf "My Scaled Pdf" - pdfScale.sh -v -v myPdfFile.pdf - pdfScale.sh -s 0.85 myPdfFile.pdf My\ Scaled\ Pdf.pdf - pdfScale.sh -m pdfinfo -s 0.80 -v myPdfFile.pdf - pdfScale.sh -v -v -m i -s 0.7 myPdfFile.pdf - pdfScale.sh -r A4 myPdfFile.pdf - pdfScale.sh -v -v -r "custom mm 252 356" -s 0.9 -f "../input file.pdf" "../my new pdf" - pdfScale.sh -h + pdfscale myPdfFile.pdf + pdfscale myPdfFile.pdf "My Scaled Pdf" + pdfscale -v -v myPdfFile.pdf + pdfscale -s 0.85 myPdfFile.pdf My\ Scaled\ Pdf.pdf + pdfscale -m pdfinfo -s 0.80 -v myPdfFile.pdf + pdfscale -v -v -m i -s 0.7 myPdfFile.pdf + pdfscale -r A4 myPdfFile.pdf + pdfscale -v -v -r "custom mm 252 356" -s 0.9 -f "../input file.pdf" "../my new pdf" ``` ## GhostScript Paper Tables From 15ae4b233304991ea8b0655a1a704cbc50f34426 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 02:55:33 -0300 Subject: [PATCH 38/59] more changes to help --- README.md | 13 +++++++------ pdfScale.sh | 12 ++++++------ 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 1840068..0f1eb54 100644 --- a/README.md +++ b/README.md @@ -176,12 +176,12 @@ Parameters: Scaling Mode: The default mode of operation is scaling mode with fixed paper size and scaling pre-set to 0.95. By not using the resize mode - you are using scaling mode. + you are using scaling mode. Flip-Detection and auto-rotation are + disabled in Scaling mode. Resize Paper Mode: Disables the default scaling factor! (0.95) - Alternative mode of operation to change the PDF paper - proportionally. Will fit-to-page. + Changes the PDF Paper Size in points. Will fit-to-page. Mixed Mode: In mixed mode both the -s option and -r option must be specified. @@ -195,7 +195,7 @@ Output filename: ..pdf is added to resized files ..SCALED.pdf is added in mixed mode -Page Detection Modes: +Page Size Detection Modes: a, adaptive Default mode, tries all the methods below c, cat+grep Forces the use of the cat + grep method m, mdls Forces the use of MacOS Quartz mdls @@ -217,12 +217,12 @@ Valid Paper Names: (case-insensitive) Custom Paper Size: Paper size can be set manually in Milimeters, Inches or Points. Use: pdfscale -r 'custom ' - Ex: pdfscale -r 'custom mm 210 297' + Ex: pdfscale -r 'custom mm 300 300' Measurements can be: mm, inch, pts. Custom paper definition MUST be quoted into a single parameter. Actual size is applied in points (mms and inches are transformed). -Notes: +Additional Notes: - Adaptive Page size detection will try different modes until it gets a page size. You can force a mode with -m 'mode'. - Options must be passed before the file names to be parsed. @@ -241,6 +241,7 @@ Examples: pdfscale -v -v -m i -s 0.7 myPdfFile.pdf pdfscale -r A4 myPdfFile.pdf pdfscale -v -v -r "custom mm 252 356" -s 0.9 -f "../input file.pdf" "../my new pdf" + pdfscale -h ``` ## GhostScript Paper Tables diff --git a/pdfScale.sh b/pdfScale.sh index 4c6b6f2..35e3f10 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -1070,12 +1070,12 @@ Parameters: Scaling Mode: The default mode of operation is scaling mode with fixed paper size and scaling pre-set to $SCALE. By not using the resize mode - you are using scaling mode. + you are using scaling mode. Flip-Detection and auto-rotation are + disabled in Scaling mode. Resize Paper Mode: Disables the default scaling factor! ($SCALE) - Alternative mode of operation to change the PDF paper - proportionally. Will fit-to-page. + Changes the PDF Paper Size in points. Will fit-to-page. Mixed Mode: In mixed mode both the -s option and -r option must be specified. @@ -1089,7 +1089,7 @@ Output filename: ..pdf is added to resized files ..SCALED.pdf is added in mixed mode -Page Detection Modes: +Page Size Detection Modes: a, adaptive Default mode, tries all the methods below c, cat+grep Forces the use of the cat + grep method m, mdls Forces the use of MacOS Quartz mdls @@ -1102,12 +1102,12 @@ $paperList Custom Paper Size: Paper size can be set manually in Milimeters, Inches or Points. Use: $PDFSCALE_NAME -r 'custom ' - Ex: $PDFSCALE_NAME -r 'custom mm 210 297' + Ex: $PDFSCALE_NAME -r 'custom mm 300 300' Measurements can be: mm, inch, pts. Custom paper definition MUST be quoted into a single parameter. Actual size is applied in points (mms and inches are transformed). -Notes: +Additional Notes: - Adaptive Page size detection will try different modes until it gets a page size. You can force a mode with -m 'mode'. - Options must be passed before the file names to be parsed. From 67c640d77fba927c659366bcdb4bbafa24ec7d91 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 02:56:32 -0300 Subject: [PATCH 39/59] more changes to help --- pdfScale.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pdfScale.sh b/pdfScale.sh index 35e3f10..5c49fb1 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -1070,7 +1070,7 @@ Parameters: Scaling Mode: The default mode of operation is scaling mode with fixed paper size and scaling pre-set to $SCALE. By not using the resize mode - you are using scaling mode. Flip-Detection and auto-rotation are + you are using scaling mode. Flip-Detection and Auto-Rotation are disabled in Scaling mode. Resize Paper Mode: From f55af29e2878a906d2d0bc071cc19d6abae54d55 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 02:56:54 -0300 Subject: [PATCH 40/59] more changes to help --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0f1eb54..05f6a60 100644 --- a/README.md +++ b/README.md @@ -176,7 +176,7 @@ Parameters: Scaling Mode: The default mode of operation is scaling mode with fixed paper size and scaling pre-set to 0.95. By not using the resize mode - you are using scaling mode. Flip-Detection and auto-rotation are + you are using scaling mode. Flip-Detection and Auto-Rotation are disabled in Scaling mode. Resize Paper Mode: From a6f93646ef852e15cb40eafa53d9416d73e6df62 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 02:59:56 -0300 Subject: [PATCH 41/59] more changes to help --- README.md | 1 + pdfScale.sh | 1 + 2 files changed, 2 insertions(+) diff --git a/README.md b/README.md index 05f6a60..de745c6 100644 --- a/README.md +++ b/README.md @@ -231,6 +231,7 @@ Additional Notes: - File and folder names with spaces should be quoted or escaped. - The scaling is centered and using a scale bigger than 1 may result on cropping parts of the pdf. + - Most of the options are case-insensitive, Ex: -m PdFinFo Examples: pdfscale myPdfFile.pdf diff --git a/pdfScale.sh b/pdfScale.sh index 5c49fb1..47643c3 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -1116,6 +1116,7 @@ Additional Notes: - File and folder names with spaces should be quoted or escaped. - The scaling is centered and using a scale bigger than 1 may result on cropping parts of the pdf. + - Most of the options are case-insensitive, Ex: -m PdFinFo Examples: $PDFSCALE_NAME myPdfFile.pdf From 1b13989973a1b48a3add993edfc6d0e46b985431 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 03:04:25 -0300 Subject: [PATCH 42/59] update example runs --- README.md | 73 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 38 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index de745c6..6c76d97 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,8 @@ pdfscale v2.0.0 - Verbose Execution Method: Cat + Grep Source Width: 842 postscript-points Source Height: 595 postscript-points - Flip Detect: Wrong orientation! + Auto Rotate: PageByPage + Flip Detect: Wrong orientation detected! Inverting Width <-> Height Run Resizing: A0 ( 3370 x 2384 ) pts New Width: 3370 postscript-points @@ -80,25 +81,25 @@ pdfscale v2.0.0 - Verbose Execution #### Scale by 0.9 (-10%) ``` $ pdfscale -v -v -s 0.9 ../input-nup.pdf "../My Glorius PDF" -2017-05-14:23:55:33 | pdfscale v2.0.0 - Verbose Execution -2017-05-14:23:55:33 | Single Task: Scale PDF Contents -2017-05-14:23:55:33 | Input File: ../input-nup.pdf -2017-05-14:23:55:33 | Output File: ../My Glorius PDF.pdf -2017-05-14:23:55:33 | Get Page Size: Adaptive Enabled -2017-05-14:23:55:33 | Method: Cat + Grep -2017-05-14:23:55:33 | Failed -2017-05-14:23:55:33 | Method: Mac Quartz mdls -2017-05-14:23:55:33 | Source Width: 842 postscript-points -2017-05-14:23:55:33 | Source Height: 595 postscript-points -2017-05-14:23:55:33 | Scale Factor: 0.9 (manual) -2017-05-14:23:55:33 | Translation X: 46.777310 -2017-05-14:23:55:33 | Translation Y: 33.055225 -2017-05-14:23:55:33 | Run Scaling: -10 % -2017-05-14:23:55:33 | Final Status: File created successfully +2017-05-15:03:03:23 | pdfscale v2.0.0 - Verbose Execution +2017-05-15:03:03:23 | Single Task: Scale PDF Contents +2017-05-15:03:03:23 | Input File: ../input-nup.pdf +2017-05-15:03:03:23 | Output File: ../My Glorius PDF.pdf +2017-05-15:03:03:23 | Get Page Size: Adaptive Enabled +2017-05-15:03:03:23 | Method: Cat + Grep +2017-05-15:03:03:23 | Failed +2017-05-15:03:03:23 | Method: Mac Quartz mdls +2017-05-15:03:03:23 | Source Width: 842 postscript-points +2017-05-15:03:03:23 | Source Height: 595 postscript-points +2017-05-15:03:03:23 | Scale Factor: 0.9 (manual) +2017-05-15:03:03:23 | Translation X: 46.777310 +2017-05-15:03:03:23 | Translation Y: 33.055225 +2017-05-15:03:03:23 | Run Scaling: -10 % +2017-05-15:03:03:24 | Final Status: File created successfully ``` -#### Resize to A2 +#### Resize to A2 and disables Auto-Rotation ``` -$ pdfscale -v -r a2 ../input.pdf +$ pdfscale -v -r A2 -a none ../input.pdf pdfscale v2.0.0 - Verbose Execution Single Task: Resize PDF Paper Input File: ../input.pdf @@ -108,6 +109,7 @@ pdfscale v2.0.0 - Verbose Execution Source Width: 595 postscript-points Source Height: 842 postscript-points Scale Factor: Disabled (resize only) + Auto Rotate: None Flip Detect: No change needed Run Resizing: A2 ( 1191 x 1684 ) pts Final Status: File created successfully @@ -115,23 +117,24 @@ pdfscale v2.0.0 - Verbose Execution #### Resize to custom 200x200 mm and Scale by 0.95 (-5%) ``` $ pdfscale -v -v -r 'custom mm 200 200' -s 0.9 ../mixsync\ manual\ v1-2-3.pdf -2017-05-15:00:12:20 | pdfscale v2.0.0 - Verbose Execution -2017-05-15:00:12:20 | Mixed Tasks: Resize & Scale -2017-05-15:00:12:20 | Input File: ../mixsync manual v1-2-3.pdf -2017-05-15:00:12:20 | Output File: ../mixsync manual v1-2-3.CUSTOM.SCALED.pdf -2017-05-15:00:12:20 | Get Page Size: Adaptive Enabled -2017-05-15:00:12:20 | Method: Cat + Grep -2017-05-15:00:12:20 | Source Width: 842 postscript-points -2017-05-15:00:12:20 | Source Height: 595 postscript-points -2017-05-15:00:12:20 | Flip Detect: No change needed -2017-05-15:00:12:20 | Run Resizing: CUSTOM ( 567 x 567 ) pts -2017-05-15:00:12:20 | New Width: 567 postscript-points -2017-05-15:00:12:20 | New Height: 567 postscript-points -2017-05-15:00:12:20 | Scale Factor: 0.9 -2017-05-15:00:12:20 | Translation X: 31.499685 -2017-05-15:00:12:20 | Translation Y: 31.499685 -2017-05-15:00:12:20 | Run Scaling: -10 % -2017-05-15:00:12:20 | Final Status: File created successfully +2017-05-15:03:00:53 | pdfscale v2.0.0 - Verbose Execution +2017-05-15:03:00:53 | Mixed Tasks: Resize & Scale +2017-05-15:03:00:53 | Input File: ../mixsync manual v1-2-3.pdf +2017-05-15:03:00:53 | Output File: ../mixsync manual v1-2-3.CUSTOM.SCALED.pdf +2017-05-15:03:00:53 | Get Page Size: Adaptive Enabled +2017-05-15:03:00:53 | Method: Cat + Grep +2017-05-15:03:00:53 | Source Width: 842 postscript-points +2017-05-15:03:00:53 | Source Height: 595 postscript-points +2017-05-15:03:00:53 | Auto Rotate: PageByPage +2017-05-15:03:00:53 | Flip Detect: No change needed +2017-05-15:03:00:53 | Run Resizing: CUSTOM ( 567 x 567 ) pts +2017-05-15:03:00:53 | New Width: 567 postscript-points +2017-05-15:03:00:53 | New Height: 567 postscript-points +2017-05-15:03:00:53 | Scale Factor: 0.9 +2017-05-15:03:00:53 | Translation X: 31.499685 +2017-05-15:03:00:53 | Translation Y: 31.499685 +2017-05-15:03:00:53 | Run Scaling: -10 % +2017-05-15:03:00:54 | Final Status: File created successfully ``` ## Help info From d8f04754b511ad987e19b9f5c9cccf25846c5b60 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 03:06:49 -0300 Subject: [PATCH 43/59] update example runs --- README.md | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 6c76d97..36ad62e 100644 --- a/README.md +++ b/README.md @@ -114,27 +114,27 @@ pdfscale v2.0.0 - Verbose Execution Run Resizing: A2 ( 1191 x 1684 ) pts Final Status: File created successfully ``` -#### Resize to custom 200x200 mm and Scale by 0.95 (-5%) +#### Resize to custom 200x200 mm, disable Flip-Detection and Scale by 0.95 (-5%) ``` -$ pdfscale -v -v -r 'custom mm 200 200' -s 0.9 ../mixsync\ manual\ v1-2-3.pdf -2017-05-15:03:00:53 | pdfscale v2.0.0 - Verbose Execution -2017-05-15:03:00:53 | Mixed Tasks: Resize & Scale -2017-05-15:03:00:53 | Input File: ../mixsync manual v1-2-3.pdf -2017-05-15:03:00:53 | Output File: ../mixsync manual v1-2-3.CUSTOM.SCALED.pdf -2017-05-15:03:00:53 | Get Page Size: Adaptive Enabled -2017-05-15:03:00:53 | Method: Cat + Grep -2017-05-15:03:00:53 | Source Width: 842 postscript-points -2017-05-15:03:00:53 | Source Height: 595 postscript-points -2017-05-15:03:00:53 | Auto Rotate: PageByPage -2017-05-15:03:00:53 | Flip Detect: No change needed -2017-05-15:03:00:53 | Run Resizing: CUSTOM ( 567 x 567 ) pts -2017-05-15:03:00:53 | New Width: 567 postscript-points -2017-05-15:03:00:53 | New Height: 567 postscript-points -2017-05-15:03:00:53 | Scale Factor: 0.9 -2017-05-15:03:00:53 | Translation X: 31.499685 -2017-05-15:03:00:53 | Translation Y: 31.499685 -2017-05-15:03:00:53 | Run Scaling: -10 % -2017-05-15:03:00:54 | Final Status: File created successfully +$ pdfscale -v -v -r 'custom mm 200 200' -f disable -s 0.9 ../mixsync\ manual\ v1-2-3.pdf +2017-05-15:03:06:23 | pdfscale v2.0.0 - Verbose Execution +2017-05-15:03:06:23 | Mixed Tasks: Resize & Scale +2017-05-15:03:06:23 | Input File: ../mixsync manual v1-2-3.pdf +2017-05-15:03:06:23 | Output File: ../mixsync manual v1-2-3.CUSTOM.SCALED.pdf +2017-05-15:03:06:23 | Get Page Size: Adaptive Enabled +2017-05-15:03:06:23 | Method: Cat + Grep +2017-05-15:03:06:23 | Source Width: 842 postscript-points +2017-05-15:03:06:23 | Source Height: 595 postscript-points +2017-05-15:03:06:23 | Auto Rotate: PageByPage +2017-05-15:03:06:23 | Flip Detect: Disabled +2017-05-15:03:06:23 | Run Resizing: CUSTOM ( 567 x 567 ) pts +2017-05-15:03:06:23 | New Width: 567 postscript-points +2017-05-15:03:06:23 | New Height: 567 postscript-points +2017-05-15:03:06:23 | Scale Factor: 0.9 +2017-05-15:03:06:23 | Translation X: 31.499685 +2017-05-15:03:06:23 | Translation Y: 31.499685 +2017-05-15:03:06:23 | Run Scaling: -10 % +2017-05-15:03:06:23 | Final Status: File created successfully ``` ## Help info From c2c4a12e8f0e7d482c4286a2f16555df83421fe0 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 03:15:09 -0300 Subject: [PATCH 44/59] adding some randomness to temporary file --- pdfScale.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pdfScale.sh b/pdfScale.sh index 47643c3..3a8ac6d 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -85,10 +85,12 @@ main() { getPageSize vPrintPageSizes ' Source' local finalRet=$EXIT_ERROR + local tempFile="" + local tempSuffix="$RANDOM""_TEMP_$RANDOM.pdf" if isMixedMode; then outputFile="$OUTFILEPDF" # backup outFile name - tempFile="${OUTFILEPDF%.pdf}.__TEMP__.pdf" # set a temp file name + tempFile="${OUTFILEPDF%.pdf}.$tempSuffix" # set a temp file name OUTFILEPDF="$tempFile" # set output to tmp file pageResize # resize to tmp file finalRet=$? From 69ce95d61ee35717da365c4f1362951ee5dd0b9f Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 03:22:28 -0300 Subject: [PATCH 45/59] adding check and abort process if the temp file already exists, prob has a 0.000000000000001% chance of happening, but that is not zero anyways --- pdfScale.sh | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pdfScale.sh b/pdfScale.sh index 3a8ac6d..4d1c40a 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -70,6 +70,7 @@ EXIT_MISSING_DEPENDENCY=25 EXIT_IMAGEMAGIK_NOT_FOUND=26 EXIT_MAC_MDLS_NOT_FOUND=27 EXIT_PDFINFO_NOT_FOUND=28 +EXIT_TEMP_FILE_EXISTS=40 EXIT_INVALID_PAPER_SIZE=50 @@ -91,6 +92,10 @@ main() { if isMixedMode; then outputFile="$OUTFILEPDF" # backup outFile name tempFile="${OUTFILEPDF%.pdf}.$tempSuffix" # set a temp file name + if isFile "$tempFile"; then + printError $'Error! Temporary file name already exists!\n'"File: $tempFile"$'\nAborting execution to avoid overwriting the file.\nPlease Try again...' + exit $EXIT_TEMP_FILE_EXISTS + fi OUTFILEPDF="$tempFile" # set output to tmp file pageResize # resize to tmp file finalRet=$? From 56742e608f4ed70385a9f81a4a335a052f034bde Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 03:25:17 -0300 Subject: [PATCH 46/59] more randomness to temp file --- pdfScale.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pdfScale.sh b/pdfScale.sh index 4d1c40a..6c655ff 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -87,7 +87,7 @@ main() { vPrintPageSizes ' Source' local finalRet=$EXIT_ERROR local tempFile="" - local tempSuffix="$RANDOM""_TEMP_$RANDOM.pdf" + local tempSuffix="$RANDOM$RANDOM""_TEMP_$RANDOM$RANDOM.pdf" if isMixedMode; then outputFile="$OUTFILEPDF" # backup outFile name From f0c44906745acae06e473a23c0f82ca72c665261 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 04:58:32 -0300 Subject: [PATCH 47/59] adding -i, file information option --- README.md | 12 +++ pdfScale.sh | 226 +++++++++++++++++++++++++++++++--------------------- 2 files changed, 146 insertions(+), 92 deletions(-) diff --git a/README.md b/README.md index 36ad62e..0d052e5 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,15 @@ brew install imagemagick xpdf ## Example Runs +#### Checking File Information +``` +./pdfScale.sh -i ../mixsync\ manual\ v1-2-3.A0.SCALED.pdf +pdfScale.sh v2.0.0 - Paper Sizes + File: mixsync manual v1-2-3.A0.SCALED.pdf + Points: 3370 x 2384 + Milimeters: 1189 x 841 + Inches: 46.81 x 33.11 +``` #### Resize to A0 and Scale by 1.05 (+5%) ``` $ pdfscale -v -r a0 -s 1.05 ../mixsync\ manual\ v1-2-3.pdf @@ -143,6 +152,7 @@ $ pdfscale -h pdfscale v2.0.0 Usage: pdfscale + pdfscale -i pdfscale [-v] [-s ] [-m ] [outfile.pdf] pdfscale [-v] [-r ] [-f ] [-a ] [outfile.pdf] pdfscale -p @@ -156,6 +166,7 @@ Parameters: -V Prints version to screen and exits -m Page size Detection mode May disable the Adaptive Mode + -i Prints Page Size information to screen and exits -s Changes the scaling factor or forces scaling Defaults: 0.95 / no scaling (resize mode) MUST be a number bigger than zero @@ -238,6 +249,7 @@ Additional Notes: Examples: pdfscale myPdfFile.pdf + pdfscale -i '/home/My Folder/My PDF File.pdf' pdfscale myPdfFile.pdf "My Scaled Pdf" pdfscale -v -v myPdfFile.pdf pdfscale -s 0.85 myPdfFile.pdf My\ Scaled\ Pdf.pdf diff --git a/pdfScale.sh b/pdfScale.sh index 6c655ff..be240ce 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -12,29 +12,19 @@ # And: https://gist.github.com/MichaelJCole/86e4968dbfc13256228a -################################################### -# PAGESIZE LOGIC -# 1- Try to get Mediabox with CAT/GREP -# 2- MacOS => try to use mdls -# 3- Try to use pdfinfo -# 4- Try to use identify (imagemagick) -# 5- Fail -################################################### +VERSION="2.0.0" -VERSION="2.0.0" -SCALE="0.95" # scaling factor (0.95 = 95%, e.g.) -VERBOSE=0 # verbosity Level -PDFSCALE_NAME="$(basename $0)" # simplified name of this script +###################### EXTERNAL PROGRAMS ####################### -# SET AND VALIDATED LATER GSBIN="" # GhostScript Binary BCBIN="" # BC Math Binary IDBIN="" # Identify Binary PDFINFOBIN="" # PDF Info Binary MDLSBIN="" # MacOS mdls Binary -OSNAME="$(uname 2>/dev/null)" # Check where we are running + +##################### ENVIRONMENT SET-UP ####################### LC_MEASUREMENT="C" # To make sure our numbers have .decimals LC_ALL="C" # Some languages use , as decimal token @@ -44,20 +34,30 @@ LC_NUMERIC="C" TRUE=0 # Silly stuff FALSE=1 -ADAPTIVEMODE=$TRUE # Automatically try to guess best mode -AUTOMATIC_SCALING=$TRUE # Default scaling in $SCALE, override by resize mode -MODE="" -RESIZE_PAPER_TYPE="" -CUSTOM_RESIZE_PAPER=$FALSE -FLIP_DETECTION=$TRUE -FLIP_FORCE=$FALSE -AUTO_ROTATION='/PageByPage' -PGWIDTH="" -PGHEIGHT="" -RESIZE_WIDTH="" -RESIZE_HEIGHT="" - -### EXIT FLAGS +########################### GLOBALS ############################ + +SCALE="0.95" # scaling factor (0.95 = 95%, e.g.) +VERBOSE=0 # verbosity Level +PDFSCALE_NAME="$(basename $0)" # simplified name of this script +OSNAME="$(uname 2>/dev/null)" # Check where we are running + +JUST_IDENTIFY=$FALSE # Flag to just show PDF info +ADAPTIVEMODE=$TRUE # Automatically try to guess best mode +AUTOMATIC_SCALING=$TRUE # Default scaling in $SCALE, override by resize mode +MODE="" # Which page size detection to use +RESIZE_PAPER_TYPE="" # Pre-defined paper to use +CUSTOM_RESIZE_PAPER=$FALSE # If we are using a custom-defined paper +FLIP_DETECTION=$TRUE # If we shoudl run the Flip-detection +FLIP_FORCE=$FALSE # If we should force Flipping +AUTO_ROTATION='/PageByPage' # GS cal auto-rotation setting +PGWIDTH="" # Input PDF Page Width +PGHEIGHT="" # Input PDF Page Height +RESIZE_WIDTH="" # Resized PDF Page Width +RESIZE_HEIGHT="" # Resized PDF Page Height + + +########################## EXIT FLAGS ########################## + EXIT_SUCCESS=0 EXIT_ERROR=1 EXIT_INVALID_PAGE_SIZE_DETECTED=10 @@ -74,13 +74,12 @@ EXIT_TEMP_FILE_EXISTS=40 EXIT_INVALID_PAPER_SIZE=50 - - ############################# MAIN ############################# # Main function called at the end main() { checkDeps + printPDFSizes vprint " Input File: $INFILEPDF" vprint " Output File: $OUTFILEPDF" getPageSize @@ -130,6 +129,19 @@ main() { return $finalRet } +# Prints PDF Info and exits with $EXIT_SUCCESS +printPDFSizes() { + if [[ $JUST_IDENTIFY -eq $TRUE ]]; then + VERBOSE=0 + printVersion 3 " - Paper Sizes" + getPageSize || initError "Could not get pagesize!" + printf " File: %+8s \n" "$(basename "$INFILEPDF")" + printf " Points: %+8s x %-8s\n" "$PGWIDTH" "$PGHEIGHT" + printf " Milimeters: %+8s x %-8s\n" "$(pointsToMilimeters $PGWIDTH)" "$(pointsToMilimeters $PGHEIGHT)" + printf " Inches: %+8s x %-8s\n" "$(pointsToInches $PGWIDTH)" "$(pointsToInches $PGHEIGHT)" + exit $EXIT_SUCCESS + fi +} ###################### GHOSTSCRIPT CALLS ####################### @@ -238,7 +250,7 @@ checkDeps() { # Parse options getOptions() { - while getopts ":vhVs:m:r:pf:a:" o; do + while getopts ":vhVis:m:r:pf:a:" o; do case "${o}" in v) ((VERBOSE++)) @@ -251,6 +263,9 @@ getOptions() { printVersion exit $EXIT_SUCCESS ;; + i) + JUST_IDENTIFY=$TRUE + ;; s) parseScale ${OPTARG} ;; @@ -277,6 +292,10 @@ getOptions() { done shift $((OPTIND-1)) + if [[ $JUST_IDENTIFY -eq $TRUE ]]; then + VERBOSE=0 + fi + # Validate input PDF file INFILEPDF="$1" isEmpty "$INFILEPDF" && initError "Input file is empty!" $EXIT_NO_INPUT_FILE @@ -390,6 +409,70 @@ parseAutoRotationMode() { ################### PDF PAGE SIZE DETECTION #################### +################################################################ +# Detects operation mode and also runs the adaptive mode +# PAGESIZE LOGIC +# 1- Try to get Mediabox with CAT/GREP +# 2- MacOS => try to use mdls +# 3- Try to use pdfinfo +# 4- Try to use identify (imagemagick) +# 5- Fail +################################################################ +getPageSize() { + if isNotAdaptiveMode; then + vprint " Get Page Size: Adaptive Disabled" + if [[ $MODE = "CATGREP" ]]; then + vprint " Method: Cat + Grep" + getPageSizeCatGrep + elif [[ $MODE = "MDLS" ]]; then + vprint " Method: Mac Quartz mdls" + getPageSizeMdls + elif [[ $MODE = "PDFINFO" ]]; then + vprint " Method: PDFInfo" + getPageSizePdfInfo + elif [[ $MODE = "IDENTIFY" ]]; then + vprint " Method: ImageMagick's Identify" + getPageSizeImagemagick + else + printError "Error! Invalid Mode: $MODE" + printError "Aborting execution..." + exit $EXIT_INVALID_OPTION + fi + return $TRUE + fi + + vprint " Get Page Size: Adaptive Enabled" + vprint " Method: Cat + Grep" + getPageSizeCatGrep + if pageSizeIsInvalid && [[ $OSNAME = "Darwin" ]]; then + vprint " Failed" + vprint " Method: Mac Quartz mdls" + getPageSizeMdls + fi + + if pageSizeIsInvalid; then + vprint " Failed" + vprint " Method: PDFInfo" + getPageSizePdfInfo + fi + + if pageSizeIsInvalid; then + vprint " Failed" + vprint " Method: ImageMagick's Identify" + getPageSizeImagemagick + fi + + if pageSizeIsInvalid; then + vprint " Failed" + printError "Error when detecting PDF paper size!" + printError "All methods of detection failed" + printError "You may want to install pdfinfo or imagemagick" + exit $EXIT_INVALID_PAGE_SIZE_DETECTED + fi + + return $TRUE +} + # Gets page size using imagemagick's identify getPageSizeImagemagick() { # Sanity and Adaptive together @@ -517,63 +600,6 @@ getPageSizeCatGrep() { return $TRUE } - -# Detects operation mode and also runs the adaptive mode -getPageSize() { - if isNotAdaptiveMode; then - vprint " Get Page Size: Adaptive Disabled" - if [[ $MODE = "CATGREP" ]]; then - vprint " Method: Cat + Grep" - getPageSizeCatGrep - elif [[ $MODE = "MDLS" ]]; then - vprint " Method: Mac Quartz mdls" - getPageSizeMdls - elif [[ $MODE = "PDFINFO" ]]; then - vprint " Method: PDFInfo" - getPageSizePdfInfo - elif [[ $MODE = "IDENTIFY" ]]; then - vprint " Method: ImageMagick's Identify" - getPageSizeImagemagick - else - printError "Error! Invalid Mode: $MODE" - printError "Aborting execution..." - exit $EXIT_INVALID_OPTION - fi - return $TRUE - fi - - vprint " Get Page Size: Adaptive Enabled" - vprint " Method: Cat + Grep" - getPageSizeCatGrep - if pageSizeIsInvalid && [[ $OSNAME = "Darwin" ]]; then - vprint " Failed" - vprint " Method: Mac Quartz mdls" - getPageSizeMdls - fi - - if pageSizeIsInvalid; then - vprint " Failed" - vprint " Method: PDFInfo" - getPageSizePdfInfo - fi - - if pageSizeIsInvalid; then - vprint " Failed" - vprint " Method: ImageMagick's Identify" - getPageSizeImagemagick - fi - - if pageSizeIsInvalid; then - vprint " Failed" - printError "Error when detecting PDF paper size!" - printError "All methods of detection failed" - printError "You may want to install pdfinfo or imagemagick" - exit $EXIT_INVALID_PAGE_SIZE_DETECTED - fi - - return $TRUE -} - # Prints error message and exits execution notAdaptiveFailed() { local errProgram="$2" @@ -882,16 +908,28 @@ uppercase() { # Prints the postscript points rounded equivalent from $1 mm milimetersToPoints() { - local pts=$(echo "scale=6; $1 * 72 / 25.4" | "$BCBIN") + local pts=$(echo "scale=8; $1 * 72 / 25.4" | "$BCBIN") printf '%.0f' "$pts" # Print rounded conversion } -# Prints the postscript points rounded equivalent from $1 mm +# Prints the postscript points rounded equivalent from $1 inches inchesToPoints() { - local pts=$(echo "scale=6; $1 * 72" | "$BCBIN") + local pts=$(echo "scale=8; $1 * 72" | "$BCBIN") printf '%.0f' "$pts" # Print rounded conversion } +# Prints the mm equivalent from $1 postscript points +pointsToMilimeters() { + local pts=$(echo "scale=8; $1 / 72 * 25.4" | "$BCBIN") + printf '%.0f' "$pts" # Print rounded conversion +} + +# Prints the inches equivalent from $1 postscript points +pointsToInches() { + local pts=$(echo "scale=8; $1 / 72" | "$BCBIN") + printf '%.2f' "$pts" # Print rounded conversion +} + ########################## VALIDATORS ########################## @@ -1021,7 +1059,8 @@ printVersion() { if [[ $1 -eq 2 ]]; then printError "$strBanner" elif [[ $1 -eq 3 ]]; then - echo "$strBanner" + local extra="$(isNotEmpty "$2" && echo "$2")" + echo "$strBanner$extra" else vprint "$strBanner" fi @@ -1041,6 +1080,7 @@ printHelp() { local paperList="$(printPaperNames)" echo " Usage: $PDFSCALE_NAME + $PDFSCALE_NAME -i $PDFSCALE_NAME [-v] [-s ] [-m ] [outfile.pdf] $PDFSCALE_NAME [-v] [-r ] [-f ] [-a ] [outfile.pdf] $PDFSCALE_NAME -p @@ -1054,6 +1094,7 @@ Parameters: -V Prints version to screen and exits -m Page size Detection mode May disable the Adaptive Mode + -i Prints Page Size information to screen and exits -s Changes the scaling factor or forces scaling Defaults: $SCALE / no scaling (resize mode) MUST be a number bigger than zero @@ -1127,6 +1168,7 @@ Additional Notes: Examples: $PDFSCALE_NAME myPdfFile.pdf + $PDFSCALE_NAME -i '/home/My Folder/My PDF File.pdf' $PDFSCALE_NAME myPdfFile.pdf \"My Scaled Pdf\" $PDFSCALE_NAME -v -v myPdfFile.pdf $PDFSCALE_NAME -s 0.85 myPdfFile.pdf My\\ Scaled\\ Pdf.pdf From 7773b2ec22beb49cd55995f54bff5198c7b7c7c4 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 05:48:19 -0300 Subject: [PATCH 48/59] finishing -i info mode --- README.md | 12 +++++----- pdfScale.sh | 64 +++++++++++++++++++++++++++++++++++++++-------------- 2 files changed, 54 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 0d052e5..69b8c25 100644 --- a/README.md +++ b/README.md @@ -57,12 +57,14 @@ brew install imagemagick xpdf #### Checking File Information ``` -./pdfScale.sh -i ../mixsync\ manual\ v1-2-3.A0.SCALED.pdf +$ ./pdfScale.sh -i ../input-nup.A0.SCALED.pdf pdfScale.sh v2.0.0 - Paper Sizes - File: mixsync manual v1-2-3.A0.SCALED.pdf - Points: 3370 x 2384 - Milimeters: 1189 x 841 - Inches: 46.81 x 33.11 + File: input-nup.A0.SCALED.pdf + Paper Type: A0 Landscape +------------+----WIDTH-+-HEIGHT----------- + Points | 3370 | 2384 + Milimeters | 1189 | 841 + Inches | 46.81 | 33.11 ``` #### Resize to A0 and Scale by 1.05 (+5%) ``` diff --git a/pdfScale.sh b/pdfScale.sh index be240ce..e3c711f 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -79,7 +79,7 @@ EXIT_INVALID_PAPER_SIZE=50 # Main function called at the end main() { checkDeps - printPDFSizes + printPDFSizes vprint " Input File: $INFILEPDF" vprint " Output File: $OUTFILEPDF" getPageSize @@ -129,18 +129,23 @@ main() { return $finalRet } -# Prints PDF Info and exits with $EXIT_SUCCESS +# Prints PDF Info and exits with $EXIT_SUCCESS, but only if $JUST_IDENTIFY is $TRUE printPDFSizes() { - if [[ $JUST_IDENTIFY -eq $TRUE ]]; then - VERBOSE=0 - printVersion 3 " - Paper Sizes" - getPageSize || initError "Could not get pagesize!" - printf " File: %+8s \n" "$(basename "$INFILEPDF")" - printf " Points: %+8s x %-8s\n" "$PGWIDTH" "$PGHEIGHT" - printf " Milimeters: %+8s x %-8s\n" "$(pointsToMilimeters $PGWIDTH)" "$(pointsToMilimeters $PGHEIGHT)" - printf " Inches: %+8s x %-8s\n" "$(pointsToInches $PGWIDTH)" "$(pointsToInches $PGHEIGHT)" - exit $EXIT_SUCCESS - fi + if [[ $JUST_IDENTIFY -eq $TRUE ]]; then + VERBOSE=0 + printVersion 3 " - Paper Sizes" + getPageSize || initError "Could not get pagesize!" + local paperType="$(getGSPaperName $PGWIDTH $PGHEIGHT)" + isEmpty "$paperType" && paperType="NOT Detected" + printf " File: %s\n" "$(basename "$INFILEPDF")" + printf " Paper Type: %s\n" "$paperType" + printf '%s\n' "------------+----WIDTH-+-HEIGHT-----------" + printf " Points | %+8s | %-8s\n" "$PGWIDTH" "$PGHEIGHT" + printf " Milimeters | %+8s | %-8s\n" "$(pointsToMilimeters $PGWIDTH)" "$(pointsToMilimeters $PGHEIGHT)" + printf " Inches | %+8s | %-8s\n" "$(pointsToInches $PGWIDTH)" "$(pointsToInches $PGHEIGHT)" + exit $EXIT_SUCCESS + fi + return $EXIT_SUCCESS } ###################### GHOSTSCRIPT CALLS ####################### @@ -292,10 +297,10 @@ getOptions() { done shift $((OPTIND-1)) - if [[ $JUST_IDENTIFY -eq $TRUE ]]; then - VERBOSE=0 - fi - + if [[ $JUST_IDENTIFY -eq $TRUE ]]; then + VERBOSE=0 + fi + # Validate input PDF file INFILEPDF="$1" isEmpty "$INFILEPDF" && initError "Input file is empty!" $EXIT_NO_INPUT_FILE @@ -703,6 +708,31 @@ getGSPaperSize() { done <<< "$sizesAll" } +# Gets a paper size in points and sets it to RESIZE_WIDTH and RESIZE_HEIGHT +getGSPaperName() { + local w="$(printf "%.0f" $1)" + local h="$(printf "%.0f" $2)" + isEmpty "$sizesall" && getPaperInfo + # Because US Standard has inverted sizes, I need to scan 2 times + # instead of just testing if width is bigger than height + while read l; do + local cols=($l) + if [[ "$w" == ${cols[5]} && "$h" == ${cols[6]} ]]; then + printf "%s Portrait" $(uppercase ${cols[0]}) + return $TRUE + fi + done <<< "$sizesAll" + while read l; do + local cols=($l) + if [[ "$w" == ${cols[6]} && "$h" == ${cols[5]} ]]; then + printf "%s Landscape" $(uppercase ${cols[0]}) + return $TRUE + fi + done <<< "$sizesAll" + return $FALSE +} + + # Loads an array with paper names to memory getPaperNames() { 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 \ @@ -1059,7 +1089,7 @@ printVersion() { if [[ $1 -eq 2 ]]; then printError "$strBanner" elif [[ $1 -eq 3 ]]; then - local extra="$(isNotEmpty "$2" && echo "$2")" + local extra="$(isNotEmpty "$2" && echo "$2")" echo "$strBanner$extra" else vprint "$strBanner" From 720d0c22d2792e294b33184e26086072beecf582 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 05:51:59 -0300 Subject: [PATCH 49/59] messing with readme --- README.md | 92 +++++++++++++++++++++++++++---------------------------- 1 file changed, 46 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 69b8c25..9a3b995 100644 --- a/README.md +++ b/README.md @@ -7,52 +7,6 @@ In `resize mode`, the PDF paper will be changed and fit-to-page will be applied. In `mixed mode`, the PDF will first be `resized` then `scaled` with two Ghostscript calls. A temporary file is used in `mixed mode`, at the target location. -## Dependencies -The script uses `basename`, `cat`, `grep`, `bc`, `head` and `gs` (ghostscript). -You probably have everything installed already, except for ghostscript. -Optional dependencies are `imagemagick`, `pdfinfo` and `mdls` (Mac). -This app is focused in `Bash`, so it will probably not run in other shells. - -##### apt-get -``` -sudo apt-get install ghostscript bc -``` -##### yum -``` -sudo yum install ghostscript bc -``` -##### homebrew MacOS -``` -brew install ghostscript -``` -##### Optionals -Page Size detection is by default in Adaptive Mode. -It will try the following methods in sequence: - 1. Try to get `/MediaBox` with `cat` + `grep` - 2. Failed AND MacOS ? Try `mdls` - 3. Failed ? Try `pdfinfo` - 4. Failed ? Try ImageMagick's `identify` - 5. Failed ? `Exit` with error message - -The `cat`+`grep` method will fail on PDFs without a `/MediaBox`. -You may install any of the optionals to be used in that case. - -MacOS is fine using `mdls` if the metadata of the file is accurate. -The metadata is generated automatically by the OS (Spotlight) - -##### apt-get -``` -sudo apt-get install imagemagick pdfinfo -``` -##### yum -``` -sudo yum install imagemagick pdfinfo -``` -##### homebrew MacOS -``` -brew install imagemagick xpdf -``` - ## Example Runs #### Checking File Information @@ -345,6 +299,52 @@ Valid Ghostscript Paper Sizes accepted +-----------------+-------+-------+-------+-------+-------+-------+ ``` +## Dependencies +The script uses `basename`, `cat`, `grep`, `bc`, `head` and `gs` (ghostscript). +You probably have everything installed already, except for ghostscript. +Optional dependencies are `imagemagick`, `pdfinfo` and `mdls` (Mac). +This app is focused in `Bash`, so it will probably not run in other shells. + +##### apt-get +``` +sudo apt-get install ghostscript bc +``` +##### yum +``` +sudo yum install ghostscript bc +``` +##### homebrew MacOS +``` +brew install ghostscript +``` +##### Optionals +Page Size detection is by default in Adaptive Mode. +It will try the following methods in sequence: + 1. Try to get `/MediaBox` with `cat` + `grep` + 2. Failed AND MacOS ? Try `mdls` + 3. Failed ? Try `pdfinfo` + 4. Failed ? Try ImageMagick's `identify` + 5. Failed ? `Exit` with error message + +The `cat`+`grep` method will fail on PDFs without a `/MediaBox`. +You may install any of the optionals to be used in that case. + +MacOS is fine using `mdls` if the metadata of the file is accurate. +The metadata is generated automatically by the OS (Spotlight) + +##### apt-get +``` +sudo apt-get install imagemagick pdfinfo +``` +##### yum +``` +sudo yum install imagemagick pdfinfo +``` +##### homebrew MacOS +``` +brew install imagemagick xpdf +``` + ## System Install The installer will name the executable as `pdfscale` with no uppercase chars and without the `.sh` extension. From fb188d8f2ec6a4902ba379bdb007064ff5da7554 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 05:54:50 -0300 Subject: [PATCH 50/59] messing with readme --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 9a3b995..b695e16 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,7 @@ Examples: ``` ## GhostScript Paper Tables +The `-p` parameters prints detailed paper types information ``` $ ./pdfScale.sh -p pdfScale.sh v2.0.0 From 22ac853dcbd809de50f24113e023643725d18f88 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 05:55:09 -0300 Subject: [PATCH 51/59] messing with readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b695e16..cee03cf 100644 --- a/README.md +++ b/README.md @@ -217,7 +217,7 @@ Examples: ``` ## GhostScript Paper Tables -The `-p` parameters prints detailed paper types information +The `-p` parameter prints detailed paper types information ``` $ ./pdfScale.sh -p pdfScale.sh v2.0.0 From f9008c7e2f38697cab81972beeafb6910be18377 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 06:26:12 -0300 Subject: [PATCH 52/59] CAT is DEADED, removed the need for CAT and HEAD. Renamed -m c, cat+grep to -g, grep. Old way is preserved for compatibility reasons; Some extra dependecy checks added, more which to work --- README.md | 5 +++-- pdfScale.sh | 31 +++++++++++++++++++++---------- 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index cee03cf..60a79bd 100644 --- a/README.md +++ b/README.md @@ -301,10 +301,11 @@ Valid Ghostscript Paper Sizes accepted ``` ## Dependencies -The script uses `basename`, `cat`, `grep`, `bc`, `head` and `gs` (ghostscript). +The script uses `basename`, `grep`, `bc` and `gs` (ghostscript). You probably have everything installed already, except for ghostscript. Optional dependencies are `imagemagick`, `pdfinfo` and `mdls` (Mac). This app is focused in `Bash`, so it will probably not run in other shells. +The script will need to see the dependencies on your `$PATH` variable. ##### apt-get ``` @@ -321,7 +322,7 @@ brew install ghostscript ##### Optionals Page Size detection is by default in Adaptive Mode. It will try the following methods in sequence: - 1. Try to get `/MediaBox` with `cat` + `grep` + 1. Try to get `/MediaBox` with `grep` (fastest) 2. Failed AND MacOS ? Try `mdls` 3. Failed ? Try `pdfinfo` 4. Failed ? Try ImageMagick's `identify` diff --git a/pdfScale.sh b/pdfScale.sh index e3c711f..4bc1f66 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -221,15 +221,18 @@ pageResize() { # Loads external dependencies and checks for errors initDeps() { + GREPBIN="$(which grep 2>/dev/null)" GSBIN="$(which gs 2>/dev/null)" BCBIN="$(which bc 2>/dev/null)" IDBIN=$(which identify 2>/dev/null) MDLSBIN="$(which mdls 2>/dev/null)" PDFINFOBIN="$(which pdfinfo 2>/dev/null)" - vprint "Checking for ghostscript and bcmath" - if notIsAvailable "$GSBIN"; then printDependency 'ghostscript'; fi - if notIsAvailable "$BCBIN"; then printDependency 'bc'; fi + vprint "Checking for grep, ghostscript and bcmath" + notIsAvailable "$GSBIN" && printDependency 'ghostscript' + notIsAvailable "$BCBIN" && printDependency 'bc' + notIsAvailable "$GREPBIN" && printDependency 'grep' + return $TRUE } # Checks for dependencies errors, run after getting options @@ -248,6 +251,7 @@ checkDeps() { initError 'mdls executable was not found! Is this even MacOS?' $EXIT_MAC_MDLS_NOT_FOUND 'nobanner' fi fi + return $TRUE } @@ -338,7 +342,7 @@ parseScale() { parseMode() { local param="$(lowercase $1)" case "${param}" in - c|catgrep|'cat+grep') + c|catgrep|'cat+grep'|grep|g) ADAPTIVEMODE=$FALSE MODE="CATGREP" return $TRUE @@ -417,7 +421,7 @@ parseAutoRotationMode() { ################################################################ # Detects operation mode and also runs the adaptive mode # PAGESIZE LOGIC -# 1- Try to get Mediabox with CAT/GREP +# 1- Try to get Mediabox with GREP # 2- MacOS => try to use mdls # 3- Try to use pdfinfo # 4- Try to use identify (imagemagick) @@ -427,7 +431,7 @@ getPageSize() { if isNotAdaptiveMode; then vprint " Get Page Size: Adaptive Disabled" if [[ $MODE = "CATGREP" ]]; then - vprint " Method: Cat + Grep" + vprint " Method: Grep" getPageSizeCatGrep elif [[ $MODE = "MDLS" ]]; then vprint " Method: Mac Quartz mdls" @@ -447,7 +451,7 @@ getPageSize() { fi vprint " Get Page Size: Adaptive Enabled" - vprint " Method: Cat + Grep" + vprint " Method: Grep" getPageSizeCatGrep if pageSizeIsInvalid && [[ $OSNAME = "Darwin" ]]; then vprint " Failed" @@ -548,7 +552,7 @@ getPageSizePdfInfo() { fi # get data from image magick - local identify="$("$PDFINFOBIN" "$INFILEPDF" 2>/dev/null | grep -i 'Page size:' )" + local identify="$("$PDFINFOBIN" "$INFILEPDF" 2>/dev/null | "$GREPBIN" -i 'Page size:' )" if isEmpty "$identify" && isNotAdaptiveMode; then notAdaptiveFailed "Linux PdfInfo returned an empty string!" @@ -574,7 +578,14 @@ getPageSizeCatGrep() { # /MediaBox[ 0 0 595.28 841.89 ] # Get MediaBox data if possible - local mediaBox="$(cat "$INFILEPDF" | grep -a '/MediaBox' | head -n1)" + #local mediaBox="$(cat "$INFILEPDF" | "$GREPBIN" -a '/MediaBox' | "$HEADBIN" -n1)" + #local mediaBox="$("$GREPBIN" -a -e '/MediaBox' "$INFILEPDF" | "$HEADBIN" -n1)" + local mediaBox="$("$GREPBIN" -a -e '/MediaBox' "$INFILEPDF" 2>/dev/null)"$'\n\n' + while read l; do + mediaBox="$l" + break + done <<< "$mediaBox" + mediaBox="${mediaBox##*/MediaBox}" # No page size data available @@ -1169,7 +1180,7 @@ Output filename: Page Size Detection Modes: a, adaptive Default mode, tries all the methods below - c, cat+grep Forces the use of the cat + grep method + g, grep Forces the use of grep method m, mdls Forces the use of MacOS Quartz mdls p, pdfinfo Forces the use of PDFInfo i, identify Forces the use of ImageMagick's Identify From d4654615a64e4ea367305927a2b1334150b9709b Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 06:34:03 -0300 Subject: [PATCH 53/59] finishing with dependecy changes --- pdfScale.sh | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/pdfScale.sh b/pdfScale.sh index 4bc1f66..18968c5 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -221,18 +221,19 @@ pageResize() { # Loads external dependencies and checks for errors initDeps() { - GREPBIN="$(which grep 2>/dev/null)" + GREPBIN="$(which grep 2>/dev/null)" GSBIN="$(which gs 2>/dev/null)" BCBIN="$(which bc 2>/dev/null)" IDBIN=$(which identify 2>/dev/null) MDLSBIN="$(which mdls 2>/dev/null)" PDFINFOBIN="$(which pdfinfo 2>/dev/null)" - vprint "Checking for grep, ghostscript and bcmath" + vprint "Checking for basename, grep, ghostscript and bcmath" + basename "" >/dev/null 2>&1 || printDependency 'basename' + notIsAvailable "$GREPBIN" && printDependency 'grep' notIsAvailable "$GSBIN" && printDependency 'ghostscript' notIsAvailable "$BCBIN" && printDependency 'bc' - notIsAvailable "$GREPBIN" && printDependency 'grep' - return $TRUE + return $TRUE } # Checks for dependencies errors, run after getting options @@ -251,7 +252,7 @@ checkDeps() { initError 'mdls executable was not found! Is this even MacOS?' $EXIT_MAC_MDLS_NOT_FOUND 'nobanner' fi fi - return $TRUE + return $TRUE } @@ -582,8 +583,8 @@ getPageSizeCatGrep() { #local mediaBox="$("$GREPBIN" -a -e '/MediaBox' "$INFILEPDF" | "$HEADBIN" -n1)" local mediaBox="$("$GREPBIN" -a -e '/MediaBox' "$INFILEPDF" 2>/dev/null)"$'\n\n' while read l; do - mediaBox="$l" - break + mediaBox="$l" + break done <<< "$mediaBox" mediaBox="${mediaBox##*/MediaBox}" From c805fe5a69e0bf345039e32a123e2a2f316955d1 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 06:36:50 -0300 Subject: [PATCH 54/59] messing with help --- README.md | 53 ++++++++++++++++++++++++++--------------------------- pdfScale.sh | 1 - 2 files changed, 26 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 60a79bd..b44c208 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ pdfscale v2.0.0 - Verbose Execution Input File: ../mixsync manual v1-2-3.pdf Output File: ../mixsync manual v1-2-3.A0.SCALED.pdf Get Page Size: Adaptive Enabled - Method: Cat + Grep + Method: Grep Source Width: 842 postscript-points Source Height: 595 postscript-points Auto Rotate: PageByPage @@ -51,7 +51,7 @@ $ pdfscale -v -v -s 0.9 ../input-nup.pdf "../My Glorius PDF" 2017-05-15:03:03:23 | Input File: ../input-nup.pdf 2017-05-15:03:03:23 | Output File: ../My Glorius PDF.pdf 2017-05-15:03:03:23 | Get Page Size: Adaptive Enabled -2017-05-15:03:03:23 | Method: Cat + Grep +2017-05-15:03:03:23 | Method: Grep 2017-05-15:03:03:23 | Failed 2017-05-15:03:03:23 | Method: Mac Quartz mdls 2017-05-15:03:03:23 | Source Width: 842 postscript-points @@ -70,7 +70,7 @@ pdfscale v2.0.0 - Verbose Execution Input File: ../input.pdf Output File: ../input.A2.pdf Get Page Size: Adaptive Enabled - Method: Cat + Grep + Method: Grep Source Width: 595 postscript-points Source Height: 842 postscript-points Scale Factor: Disabled (resize only) @@ -87,7 +87,7 @@ $ pdfscale -v -v -r 'custom mm 200 200' -f disable -s 0.9 ../mixsync\ manual\ v1 2017-05-15:03:06:23 | Input File: ../mixsync manual v1-2-3.pdf 2017-05-15:03:06:23 | Output File: ../mixsync manual v1-2-3.CUSTOM.SCALED.pdf 2017-05-15:03:06:23 | Get Page Size: Adaptive Enabled -2017-05-15:03:06:23 | Method: Cat + Grep +2017-05-15:03:06:23 | Method: Grep 2017-05-15:03:06:23 | Source Width: 842 postscript-points 2017-05-15:03:06:23 | Source Height: 595 postscript-points 2017-05-15:03:06:23 | Auto Rotate: PageByPage @@ -104,16 +104,16 @@ $ pdfscale -v -v -r 'custom mm 200 200' -f disable -s 0.9 ../mixsync\ manual\ v1 ## Help info ``` -$ pdfscale -h -pdfscale v2.0.0 +$ ./pdfScale.sh -h +pdfScale.sh v2.0.0 -Usage: pdfscale - pdfscale -i - pdfscale [-v] [-s ] [-m ] [outfile.pdf] - pdfscale [-v] [-r ] [-f ] [-a ] [outfile.pdf] - pdfscale -p - pdfscale -h - pdfscale -V +Usage: pdfScale.sh + pdfScale.sh -i + pdfScale.sh [-v] [-s ] [-m ] [outfile.pdf] + pdfScale.sh [-v] [-r ] [-f ] [-a ] [outfile.pdf] + pdfScale.sh -p + pdfScale.sh -h + pdfScale.sh -V Parameters: -v Verbose mode, prints extra information @@ -167,7 +167,7 @@ Output filename: Page Size Detection Modes: a, adaptive Default mode, tries all the methods below - c, cat+grep Forces the use of the cat + grep method + g, grep Forces the use of grep method m, mdls Forces the use of MacOS Quartz mdls p, pdfinfo Forces the use of PDFInfo i, identify Forces the use of ImageMagick's Identify @@ -186,8 +186,8 @@ Valid Paper Names: (case-insensitive) Custom Paper Size: Paper size can be set manually in Milimeters, Inches or Points. - Use: pdfscale -r 'custom ' - Ex: pdfscale -r 'custom mm 300 300' + Use: pdfScale.sh -r 'custom ' + Ex: pdfScale.sh -r 'custom mm 300 300' Measurements can be: mm, inch, pts. Custom paper definition MUST be quoted into a single parameter. Actual size is applied in points (mms and inches are transformed). @@ -204,16 +204,15 @@ Additional Notes: - Most of the options are case-insensitive, Ex: -m PdFinFo Examples: - pdfscale myPdfFile.pdf - pdfscale -i '/home/My Folder/My PDF File.pdf' - pdfscale myPdfFile.pdf "My Scaled Pdf" - pdfscale -v -v myPdfFile.pdf - pdfscale -s 0.85 myPdfFile.pdf My\ Scaled\ Pdf.pdf - pdfscale -m pdfinfo -s 0.80 -v myPdfFile.pdf - pdfscale -v -v -m i -s 0.7 myPdfFile.pdf - pdfscale -r A4 myPdfFile.pdf - pdfscale -v -v -r "custom mm 252 356" -s 0.9 -f "../input file.pdf" "../my new pdf" - pdfscale -h + pdfScale.sh myPdfFile.pdf + pdfScale.sh -i '/home/My Folder/My PDF File.pdf' + pdfScale.sh myPdfFile.pdf "My Scaled Pdf" + pdfScale.sh -v -v myPdfFile.pdf + pdfScale.sh -s 0.85 myPdfFile.pdf My\ Scaled\ Pdf.pdf + pdfScale.sh -m pdfinfo -s 0.80 -v myPdfFile.pdf + pdfScale.sh -v -v -m i -s 0.7 myPdfFile.pdf + pdfScale.sh -r A4 myPdfFile.pdf + pdfScale.sh -v -v -r "custom mm 252 356" -s 0.9 -f "../input file.pdf" "../my new pdf" ``` ## GhostScript Paper Tables @@ -328,7 +327,7 @@ It will try the following methods in sequence: 4. Failed ? Try ImageMagick's `identify` 5. Failed ? `Exit` with error message -The `cat`+`grep` method will fail on PDFs without a `/MediaBox`. +The `grep` method will fail on PDFs without a `/MediaBox`. You may install any of the optionals to be used in that case. MacOS is fine using `mdls` if the metadata of the file is accurate. diff --git a/pdfScale.sh b/pdfScale.sh index 18968c5..007d709 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -1218,7 +1218,6 @@ Examples: $PDFSCALE_NAME -v -v -m i -s 0.7 myPdfFile.pdf $PDFSCALE_NAME -r A4 myPdfFile.pdf $PDFSCALE_NAME -v -v -r \"custom mm 252 356\" -s 0.9 -f \"../input file.pdf\" \"../my new pdf\" - $PDFSCALE_NAME -h " } From 62da2539c75c662392a66050ecbcb0b28ece332b Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 06:47:28 -0300 Subject: [PATCH 55/59] prettier -i info mode --- README.md | 16 +++++++++------- pdfScale.sh | 16 ++++++++++------ 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index b44c208..e6ee08b 100644 --- a/README.md +++ b/README.md @@ -11,14 +11,16 @@ A temporary file is used in `mixed mode`, at the target location. #### Checking File Information ``` -$ ./pdfScale.sh -i ../input-nup.A0.SCALED.pdf +$ ./pdfScale.sh -i ../input-nup.pdf pdfScale.sh v2.0.0 - Paper Sizes - File: input-nup.A0.SCALED.pdf - Paper Type: A0 Landscape -------------+----WIDTH-+-HEIGHT----------- - Points | 3370 | 2384 - Milimeters | 1189 | 841 - Inches | 46.81 | 33.11 +------------+----------------------------- + File | input-nup.pdf + Paper Type | A4 Landscape +------------+----------------------------- + | WIDTH x HEIGHT + Points | 842 x 595 + Milimeters | 297 x 210 + Inches | 11.69 x 8.26 ``` #### Resize to A0 and Scale by 1.05 (+5%) ``` diff --git a/pdfScale.sh b/pdfScale.sh index 007d709..5f56f60 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -137,12 +137,16 @@ printPDFSizes() { getPageSize || initError "Could not get pagesize!" local paperType="$(getGSPaperName $PGWIDTH $PGHEIGHT)" isEmpty "$paperType" && paperType="NOT Detected" - printf " File: %s\n" "$(basename "$INFILEPDF")" - printf " Paper Type: %s\n" "$paperType" - printf '%s\n' "------------+----WIDTH-+-HEIGHT-----------" - printf " Points | %+8s | %-8s\n" "$PGWIDTH" "$PGHEIGHT" - printf " Milimeters | %+8s | %-8s\n" "$(pointsToMilimeters $PGWIDTH)" "$(pointsToMilimeters $PGHEIGHT)" - printf " Inches | %+8s | %-8s\n" "$(pointsToInches $PGWIDTH)" "$(pointsToInches $PGHEIGHT)" + #printf '%s\n' "-----+------+----WIDTH-+-HEIGHT-----------" + printf '%s\n' "------------+-----------------------------" + printf " File | %s\n" "$(basename "$INFILEPDF")" + printf " Paper Type | %s\n" "$paperType" + printf '%s\n' "------------+-----------------------------" + #printf '%s\n' "------------+----WIDTH-+-HEIGHT-----------" + printf '%s\n' " | WIDTH x HEIGHT" + printf " Points | %+8s x %-8s\n" "$PGWIDTH" "$PGHEIGHT" + printf " Milimeters | %+8s x %-8s\n" "$(pointsToMilimeters $PGWIDTH)" "$(pointsToMilimeters $PGHEIGHT)" + printf " Inches | %+8s x %-8s\n" "$(pointsToInches $PGWIDTH)" "$(pointsToInches $PGHEIGHT)" exit $EXIT_SUCCESS fi return $EXIT_SUCCESS From 5ef192d27492e0724a2fc3129b5f5a13d8adb94d Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 06:50:35 -0300 Subject: [PATCH 56/59] gitignore for system files --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 8bfaac4..8143e84 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,6 @@ .Trashes ehthumbs.db Thumbs.db + +## Hidden files +.* From 81b2e4e07da3772b9517c8ec609c25f2875045f6 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 06:56:10 -0300 Subject: [PATCH 57/59] making inches floating to 1 decimal precison to correlate to the defined tables --- pdfScale.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pdfScale.sh b/pdfScale.sh index 5f56f60..2f4d085 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -973,7 +973,7 @@ pointsToMilimeters() { # Prints the inches equivalent from $1 postscript points pointsToInches() { local pts=$(echo "scale=8; $1 / 72" | "$BCBIN") - printf '%.2f' "$pts" # Print rounded conversion + printf '%.1f' "$pts" # Print rounded conversion } From 8a83e5f980a5ecff5a03aeb3af8297e04ee99e40 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 06:57:51 -0300 Subject: [PATCH 58/59] code cleanup --- pdfScale.sh | 2 -- 1 file changed, 2 deletions(-) diff --git a/pdfScale.sh b/pdfScale.sh index 2f4d085..cad5d61 100755 --- a/pdfScale.sh +++ b/pdfScale.sh @@ -137,12 +137,10 @@ printPDFSizes() { getPageSize || initError "Could not get pagesize!" local paperType="$(getGSPaperName $PGWIDTH $PGHEIGHT)" isEmpty "$paperType" && paperType="NOT Detected" - #printf '%s\n' "-----+------+----WIDTH-+-HEIGHT-----------" printf '%s\n' "------------+-----------------------------" printf " File | %s\n" "$(basename "$INFILEPDF")" printf " Paper Type | %s\n" "$paperType" printf '%s\n' "------------+-----------------------------" - #printf '%s\n' "------------+----WIDTH-+-HEIGHT-----------" printf '%s\n' " | WIDTH x HEIGHT" printf " Points | %+8s x %-8s\n" "$PGWIDTH" "$PGHEIGHT" printf " Milimeters | %+8s x %-8s\n" "$(pointsToMilimeters $PGWIDTH)" "$(pointsToMilimeters $PGHEIGHT)" From 40cb09132ae353505b6bac62aaa13f63498b2f44 Mon Sep 17 00:00:00 2001 From: Gustavo Neves Date: Mon, 15 May 2017 07:02:57 -0300 Subject: [PATCH 59/59] messing with readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e6ee08b..936391c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # pdfScale 2 Bash Script to ***scale*** and/or ***resize*** PDFs from the command line. -Uses ghostscript to create a scaled and/or resized version of the pdf input. +Uses ghostscript (`gs`) to create a scaled and/or resized version of the pdf input. In `scaling mode`, the PDF paper size does not change, just the elements are scaled. In `resize mode`, the PDF paper will be changed and fit-to-page will be applied.