Rubyでpdfのテキストを取得(poppler gem編)

実はpoppler gemを使うまでにいろんなpdfを扱うgemを確認してました。でも上手く行かなかったのです。

Ruby/Popplerを使えば、テキストがポンと出てきます。gem i popplerでインストール出来ます。

require "poppler"
document = Poppler::Document.new("keigo_tousin.pdf")
puts document.first.get_text

 :
(追記)
Mac OS Xでインストールに失敗する場合、このあたりを参考にしてみてください。
Rabbitをインストールすれば、Ruby/Popplerもインストールされます
http://rabbit-shocker.org/ja/install/homebrew.html
Ruby で PDF と戯れるの巻 - Qiita

結論として、コメント通り、popplerが一番簡単にpdfからテキストを抜き出せました。
しかし…インストールに手間取りました。
ので記事を書きました。
(ですが、実はこの手間は徒労でした^^;; 徒労を読まずに済ます場合はこちらへ

2015/9/22追記

いつからか分かりませんが、どうやら poppler gem 自身に poppler の native が入ったようです。なので Homebrew で poppler などを入れなくても問題なく動作します

$ gem install poppler
Fetching: pkg-config-1.1.6.gem (100%)
Successfully installed pkg-config-1.1.6
Fetching: cairo-1.14.3.gem (100%)
Building native extensions.  This could take a while...
Successfully installed cairo-1.14.3
Fetching: glib2-3.0.5.gem (100%)
Building native extensions.  This could take a while...
Successfully installed glib2-3.0.5
Fetching: gdk_pixbuf2-3.0.5.gem (100%)
Building native extensions.  This could take a while...
Successfully installed gdk_pixbuf2-3.0.5
Fetching: poppler-3.0.5.gem (100%)
Building native extensions.  This could take a while...
Successfully installed poppler-3.0.5
5 gems installed

(2015/9/22追記ここまで)

poppler gemのリファレンス

Poppler::Document - Ruby-GNOME2 Project Website

Poppler::Page - Ruby-GNOME2 Project Website

  • クラス索引

Ruby/Poppler - Ruby-GNOME2 Project Website

  • メソッド索引

index-ruby-poppler - Ruby-GNOME2 Project Website

  • おまけ:ソース

ruby-gnome2/poppler at master · ruby-gnome2/ruby-gnome2 · GitHub

poppler gemの依存性確認

$ gem dependency poppler --remote
Gem poppler-2.2.0
  cairo (>= 1.12.8)
  gdk_pixbuf2 (= 2.2.0)

poppler gemインストール開始(その1)

$ gem install poppler
Fetching: pkg-config-1.1.5.gem (100%)
Fetching: cairo-1.12.8.gem (100%)
Building native extensions.  This could take a while...
ERROR:  Error installing poppler:
	ERROR: Failed to build gem native extension.

        /Users/riocampos/.rbenv/versions/1.9.3-p484/bin/ruby extconf.rb
checking for GCC... yes
checking for Win32 OS... no
checking for cairo version (>= 1.2.0)... no
checking for brew... yes
installing 'cairo' native package... failed
failed to run 'brew install cairo'.
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
	--with-opt-dir
	--without-opt-dir
	--with-opt-include
	--without-opt-include=${opt-dir}/include
	--with-opt-lib
	--without-opt-lib=${opt-dir}/lib
	--with-make-prog
	--without-make-prog
	--srcdir=.
	--curdir
	--ruby=/Users/riocampos/.rbenv/versions/1.9.3-p484/bin/ruby
	--with-pkg-config
	--without-pkg-config
	--with-override-variables
	--without-override-variables


Gem files will remain installed in /Users/riocampos/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/cairo-1.12.8 for inspection.
Results logged to /Users/riocampos/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/cairo-1.12.8/ext/cairo/gem_make.out

失敗。

brewを使う必要があるようだと気付く

まずbrew update。
そして上で

failed to run 'brew install cairo'.

と指摘してきたので、先にbrewでcairo*1を入れる。

$ brew install cairo
cairo: Unsatisfied dependency: XQuartz 
Homebrew does not package XQuartz. Installers may be found at:
  https://xquartz.macosforge.org
Error: An unsatisfied requirement failed this build.

失敗2。

XQuartzが要るらしい

エラーメッセージにもあるがXQuartzからダウンロードしてインストールする。
そして再起動。

poppler gemインストール開始(その2)

$ gem install poppler
Building native extensions.  This could take a while...
Fetching: glib2-2.2.0.gem (100%)
Building native extensions.  This could take a while...
Fetching: gdk_pixbuf2-2.2.0.gem (100%)
Building native extensions.  This could take a while...
Fetching: poppler-2.2.0.gem (100%)
Building native extensions.  This could take a while...
ERROR:  Error installing poppler:
	ERROR: Failed to build gem native extension.

        /Users/riocampos/.rbenv/versions/1.9.3-p484/bin/ruby extconf.rb
checking for -Wall option to compiler... yes
checking for -Waggregate-return option to compiler... yes
checking for -Wcast-align option to compiler... yes
checking for -Wextra option to compiler... yes
checking for -Wformat=2 option to compiler... yes
checking for -Winit-self option to compiler... yes
checking for -Wlarger-than-65500 option to compiler... yes
checking for -Wmissing-declarations option to compiler... yes
checking for -Wmissing-format-attribute option to compiler... yes
checking for -Wmissing-include-dirs option to compiler... yes
checking for -Wmissing-noreturn option to compiler... yes
checking for -Wmissing-prototypes option to compiler... yes
checking for -Wnested-externs option to compiler... yes
checking for -Wold-style-definition option to compiler... yes
checking for -Wpacked option to compiler... yes
checking for -Wp,-D_FORTIFY_SOURCE=2 option to compiler... yes
checking for -Wpointer-arith option to compiler... yes
checking for -Wswitch-default option to compiler... yes
checking for -Wswitch-enum option to compiler... yes
checking for -Wundef option to compiler... yes
checking for -Wunsafe-loop-optimizations option to compiler... yes
checking for -Wwrite-strings option to compiler... yes
checking for rb_define_alloc_func() in ruby.h... yes
checking for rb_block_proc() in ruby.h... yes
checking for new allocation framework... yes
checking for attribute assignment... no
checking for cairo... yes
checking for rb_cairo.h... yes
checking for Win32 OS... no
checking for poppler-glib version (>= 0.12.0)... no
checking for brew... yes
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
	--with-opt-dir
	--without-opt-dir
	--with-opt-include
	--without-opt-include=${opt-dir}/include
	--with-opt-lib
	--without-opt-lib=${opt-dir}/lib
	--with-make-prog
	--without-make-prog
	--srcdir=.
	--curdir
	--ruby=/Users/riocampos/.rbenv/versions/1.9.3-p484/bin/ruby
	--with-pkg-config
	--without-pkg-config
	--with-override-variables
	--without-override-variables


Gem files will remain installed in /Users/riocampos/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/poppler-2.2.0 for inspection.
Results logged to /Users/riocampos/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/poppler-2.2.0/ext/poppler/gem_make.out

失敗。しかも同じようなメッセージ。

cairoをbrewでインストール

XQuartzを入れただけではダメっぽい。
のでもう一度手動でcairoを入れる。

$ brew install cairo
==> Installing dependencies for cairo: fontconfig, pixman
==> Installing cairo dependency: fontconfig
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/fontconfig-
######################################################################## 100.0%
==> Pouring fontconfig-2.11.0.mavericks.bottle.1.tar.gz
==> /usr/local/Cellar/fontconfig/2.11.0/bin/fc-cache -frv
🍺  /usr/local/Cellar/fontconfig/2.11.0: 445 files, 4.0M
==> Installing cairo dependency: pixman
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/pixman-0.32
######################################################################## 100.0%
==> Pouring pixman-0.32.4.mavericks.bottle.tar.gz
🍺  /usr/local/Cellar/pixman/0.32.4: 11 files, 1.3M
==> Installing cairo
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/cairo-1.12.
######################################################################## 100.0%
==> Pouring cairo-1.12.16_1.mavericks.bottle.tar.gz
🍺  /usr/local/Cellar/cairo/1.12.16_1: 105 files, 7.6M

成功。

poppler gemインストール開始(その3)

$ gem install poppler
Building native extensions.  This could take a while...
ERROR:  Error installing poppler:
	ERROR: Failed to build gem native extension.

        /Users/riocampos/.rbenv/versions/1.9.3-p484/bin/ruby extconf.rb
checking for -Wall option to compiler... yes
checking for -Waggregate-return option to compiler... yes
checking for -Wcast-align option to compiler... yes
checking for -Wextra option to compiler... yes
checking for -Wformat=2 option to compiler... yes
checking for -Winit-self option to compiler... yes
checking for -Wlarger-than-65500 option to compiler... yes
checking for -Wmissing-declarations option to compiler... yes
checking for -Wmissing-format-attribute option to compiler... yes
checking for -Wmissing-include-dirs option to compiler... yes
checking for -Wmissing-noreturn option to compiler... yes
checking for -Wmissing-prototypes option to compiler... yes
checking for -Wnested-externs option to compiler... yes
checking for -Wold-style-definition option to compiler... yes
checking for -Wpacked option to compiler... yes
checking for -Wp,-D_FORTIFY_SOURCE=2 option to compiler... yes
checking for -Wpointer-arith option to compiler... yes
checking for -Wswitch-default option to compiler... yes
checking for -Wswitch-enum option to compiler... yes
checking for -Wundef option to compiler... yes
checking for -Wunsafe-loop-optimizations option to compiler... yes
checking for -Wwrite-strings option to compiler... yes
checking for rb_define_alloc_func() in ruby.h... yes
checking for rb_block_proc() in ruby.h... yes
checking for new allocation framework... yes
checking for attribute assignment... no
checking for cairo... yes
checking for rb_cairo.h... yes
checking for Win32 OS... no
checking for poppler-glib version (>= 0.12.0)... no
checking for brew... yes
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
	--with-opt-dir
	--without-opt-dir
	--with-opt-include
	--without-opt-include=${opt-dir}/include
	--with-opt-lib
	--without-opt-lib=${opt-dir}/lib
	--with-make-prog
	--without-make-prog
	--srcdir=.
	--curdir
	--ruby=/Users/riocampos/.rbenv/versions/1.9.3-p484/bin/ruby
	--with-pkg-config
	--without-pkg-config
	--with-override-variables
	--without-override-variables


Gem files will remain installed in /Users/riocampos/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/poppler-2.2.0 for inspection.
Results logged to /Users/riocampos/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/poppler-2.2.0/ext/poppler/gem_make.out

失敗3。

どうやらoptionを指定する必要があるようだ。

google:ruby poppler install option
で検索した結果、ここが当たった。rabbitというappの関係。どうやらpopplerを使っているようだ。

--with-glibなしでインストールしても動かないので対応するまでは自動でインストールしていないようにしています!
homebrew で poppler の --with-glib の時のエラーメッセージがわかりにくい · Issue #24 · rabbit-shocker/rabbit · GitHub

ということは--with-glibを付けるんだね。

poppler gemインストール開始(その4)

$ gem install poppler --with-glib
ERROR:  While executing gem ... (OptionParser::InvalidOption)
    invalid option: --with-glib

いきなり失敗。
--with-glibはgemのオプションにはならないらしい。
ということは、homebrewか。

brewでpopplerをインストール

$ brew install poppler --with-glib
==> Installing dependencies for poppler: little-cms2, openjpeg
==> Installing poppler dependency: little-cms2
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/little-cms2
######################################################################## 100.0%
==> Pouring little-cms2-2.5.mavericks.bottle.tar.gz
🍺  /usr/local/Cellar/little-cms2/2.5: 16 files, 1.0M
==> Installing poppler dependency: openjpeg
==> Downloading https://openjpeg.googlecode.com/files/openjpeg-1.5.1.tar.gz
######################################################################## 100.0%
==> ./configure --prefix=/usr/local/Cellar/openjpeg/1.5.1_1
==> make install
🍺  /usr/local/Cellar/openjpeg/1.5.1_1: 18 files, 616K, built in 24 seconds
==> Installing poppler
==> Downloading http://poppler.freedesktop.org/poppler-0.24.5.tar.xz
######################################################################## 100.0%
==> ./configure --prefix=/usr/local/Cellar/poppler/0.24.5_1 --enable-xpdf-header
==> make install
==> Downloading http://poppler.freedesktop.org/poppler-data-0.4.6.tar.gz
######################################################################## 100.0%
==> make install prefix=/usr/local/Cellar/poppler/0.24.5_1
🍺  /usr/local/Cellar/poppler/0.24.5_1: 457 files, 22M, built in 75 seconds

入った。

poppler gemインストール開始(その5)

homebrewで入れたpopplerだけではRubyから使えないでしょうから、やはり再度gemでインストール。

$ gem install poppler
Building native extensions.  This could take a while...
Successfully installed poppler-2.2.0
1 gem installed

ようやく入りました!

実は最初に手順情報が

最初のサイトにこのような追記がありました。

(追記)
Mac OS Xでインストールに失敗する場合、このあたりを参考にしてみてください。
Rabbitをインストールすれば、Ruby/Popplerもインストールされます
http://rabbit-shocker.org/ja/install/homebrew.html
Ruby で PDF と戯れるの巻 - Qiita

で。

Mac OS XでHomebrewを使ったインストール方法

brew install と brew link の実行
$ brew install cairo
$ brew link cairo
$ brew link --overwrite pixman
$ brew install pango
$ brew install gtk+
$ brew install poppler --with-glib
Rabbit のインストール
$ sudo gem install rabbit
$ sudo gem install rabbiter # Twitter連携機能を使う場合

Rabbit - Homebrewでインストール

brew linkなどは行ってませんが、brew install popplerでの--with-glibというオプションに付いて、ちゃんと明記されています。
今回の作業は大回りしすぎ^^;;

実行

popplerでテキストを抜き出せるか、pryで確認します。
今回使うpdfファイルは…これ。
研究論文(STAP細胞)の疑義に関する調査報告について(その2)研究論文の疑義に関する調査報告書(スライド)
今日いちばん注目されたスライドの元pdfです。

pry(main)> require 'poppler'
=> true
pry(main)> require 'open-uri'
=> true
pry(main)> riken_stap_research_report_slide = Poppler::Document.new(open("http://www3.riken.jp/stap/j/i2document2.pdf").read)
=> #<Poppler::Document:0x7fb7d41c4b28 ptr=0x7fb7d429d900>
pry(main)> puts riken_stap_research_report_slide.first.get_text;
調査委員会 報告
1

間違いなく日本語でスライド1枚目のテキストを抜き出せました。
見出の「調査委員会 報告」とページ数の「1」です。
次はスライド最後のページ。まとめです。

pry(main)> puts riken_stap_research_report_slide[riken_stap_research_report_slide.size - 1].get_text;
まとめ
小保方氏
2つの点について研究不正行為があった。
若山、笹井両氏
研究不正行為はなかったが、データの正当性と正確性等について
自ら確認することなく論文投稿に至 ており その責任は重大である
自ら確認することなく論文投稿に至っており、その責任は重大である
丹羽氏
論文作成の遅い段階でこの研究に参加したものであり、
論文作成の遅い段階でこの研究に参加したものであり
研究不正行為は認められなかった。
20

こちらも上手く行きました(文章の重複は元pdfのせい、のはず)。
poppler gemの詳細はおいおい確認していきます。

*1:ところでcairoって何ですか?→Rubyist Magazine - cairo: 2 次元画像描画ライブラリ