9
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

表示範囲 (CropBox) を考慮して PDF のサムネイルをつくる

Posted at

Automator や ImageMagick でも PDF を画像に変換することはできるが、表示範囲 (CropBox) が考慮されず、トンボや余白が画像に含まれてしまう場合がある。

Poppler という PDF レンダリングライブラリに含まれる pdftoppm コマンドなら -cropbox オプションで表示範囲のみを画像にすることができる。

Poppler のインストール

Homebrew を使っているなら、下記コマンドで完了。

$ brew install poppler

XQuartz のインストールを要求されたら、下記からダウンロード、インストールする。

pdftoppm の使い方

ヘルプは -h オプションで。

$ pdftoppm -h

下記コマンドで foo.pdf の 1 ページ目の表示範囲が foo.jpg に保存される。

# -cropsize  表示範囲を考慮
# -f 1       1 ページ目
# -jpeg      jpeg で出力
$ pdftoppm -cropbox -f 1 -jpeg foo.pdf > foo.jpg

サムネイルに

pdftoppm-scale-to オプションでもサイズの変更は可能だが、あまり綺麗でなかったので ImageMagick の convert でリサイズする。

# jpeg:-         標準入力のデータを JPEG として読み込む
# -resize 96x96  96x96px に収まるサイズに縦横比を変えずリサイズ
$ pdftoppm -cropbox -f 1 -jpeg foo.pdf | convert jpeg:- -resize 96x96 foo.jpg

下記は、pdf ディレクトリにある PDF のサムネイルを作成し、thumbnail ディレクトリに保存する Ruby スクリプト。

require "shellwords"
Dir.glob("pdf/*.pdf") do |pdf|
  puts pdf
  dest = "thumbnail/" + File.basename(pdf).gsub(/\.pdf$/, ".jpg")
  `pdftoppm -cropbox -f 1 -jpeg #{pdf.shellescape} | convert jpeg:- -resize 96x96 #{dest.shellescape}`
end
9
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?