aboutsummaryrefslogtreecommitdiffstats
path: root/cli/pdf-compress.sh
blob: bd4fd03851faff518c5179b23b6abd3606e8ec79 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/bin/sh
#
# Copyright (c) 2013,2019 Aaron LI
# MIT License
#
# Compress a PDF file by adjust its quality using GhostScript.
#
# Credits:
# * https://www.ghostscript.com/doc/current/Use.htm
# * https://www.ghostscript.com/doc/current/VectorDevices.htm
#

usage() {
    cat << _EOF_
Compress a PDF file by adjust its quality using GhostScript.

usage:
    ${0##*/} [-d dpi] [-l level] [-s settings] <infile> <outfile>

options:
    -d dpi : image dpi to be downsampled to (default: 150)
    -l level : PDF compatibility level (default: 1.5)
    -s settings : predefined settings (default: ebook)
        valid choices: screen, ebook, printer, prepress, default
_EOF_

    exit 1
}

main() {
    local dpi=150
    local level=1.5
    local settings=ebook
    local infile outfile

    while getopts :hd:l:s: opt; do
        case ${opt} in
        h)
            usage
            ;;
        d)
            dpi=${OPTARG}
            ;;
        l)
            level=${OPTARG}
            ;;
        s)
            settings=${OPTARG}
            ;;
        \?)
            echo "Invalid option -${OPTARG}"
            usage
            ;;
        :)
            echo "Option -${OPTARG} requires an argument"
            usage
            ;;
        esac
    done

    shift $((${OPTIND} - 1))
    if [ $# -ne 2 ]; then
        usage
    fi

    infile="$1"
    outfile="$2"

    gs  -dQUIET -dNOPAUSE -dBATCH -dSAFER \
        -sDEVICE=pdfwrite \
        -dCompatibilityLevel=${level} \
        -dPDFSETTINGS=/${settings} \
        -dPrinted=false \
        -dEmbedAllFonts=true \
        -dSubsetFonts=true \
        -dFastWebView=true \
        -dColorImageDownsampleType=/Bicubic \
        -dColorImageResolution=${dpi} \
        -dGrayImageDownsampleType=/Bicubic \
        -dGrayImageResolution=${dpi} \
        -sOutputFile="${outfile}" \
        "${infile}"
}

main "$@"