macでpdfのサイズを圧縮して縮小する方法

導入

ghostscriptとShellScriptを使ってpdfファイルを圧縮しサイズを縮小させたいと思います。macで実行確認済みです。予めbrewでghostscriptをインストールしておいてください。

brew install ghostscript

使い方

./shrinkpdf.sh in.pdf > out.pdf

デフォルトではDPI(文字や画像のきめ細かさ)の値は72です。もっと綺麗なアウトプットを望む場合は下記のようにDPI値を指定して実行をします。

./shrinkpdf.sh in.pdf out.pdf 90

実装

shrink ()
{
    gs                  \
      -q -dNOPAUSE -dBATCH -dSAFER      \
      -sDEVICE=pdfwrite         \
      -dCompatibilityLevel=1.3      \
      -dPDFSETTINGS=/screen         \
      -dEmbedAllFonts=true          \
      -dSubsetFonts=true            \
      -dAutoRotatePages=/None       \
      -dColorImageDownsampleType=/Bicubic   \
      -dColorImageResolution=$3     \
      -dGrayImageDownsampleType=/Bicubic    \
      -dGrayImageResolution=$3      \
      -dMonoImageDownsampleType=/Bicubic    \
      -dMonoImageResolution=$3      \
      -sOutputFile="$2"         \
      "$1"
}

check_smaller ()
{
    # If $1 and $2 are regular files, we can compare file sizes to
    # see if we succeeded in shrinking. If not, we copy $1 over $2:
    if [ ! -f "$1" -o ! -f "$2" ]; then
        return 0;
    fi
    ISIZE="$(echo $(wc -c "$1") | cut -f1 -d\ )"
    OSIZE="$(echo $(wc -c "$2") | cut -f1 -d\ )"
    if [ "$ISIZE" -lt "$OSIZE" ]; then
        echo "Input smaller than output, doing straight copy" >&2
        cp "$1" "$2"
    fi
}

usage ()
{
    echo "Reduces PDF filesize by lossy recompressing with Ghostscript."
    echo "Not guaranteed to succeed, but usually works."
    echo "  Usage: $1 infile [outfile] [resolution_in_dpi]"
}

IFILE="$1"

# Need an input file:
if [ -z "$IFILE" ]; then
    usage "$0"
    exit 1
fi

# Output filename defaults to "-" (stdout) unless given:
if [ ! -z "$2" ]; then
    OFILE="$2"
else
    OFILE="-"
fi

# Output resolution defaults to 72 unless given:
if [ ! -z "$3" ]; then
    res="$3"
else
    res="72"
fi

shrink "$IFILE" "$OFILE" "$res" || exit $?

check_smaller "$IFILE" "$OFILE"

参考

下記のサイトの丸パクリです。
Shrinkpdf: shrink PDF files with Ghostscript

藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です