LoginSignup
5
5

More than 5 years have passed since last update.

groovyでPDFからtextを抽出する

Last updated at Posted at 2016-11-07

groovy勉強のメモを残していきたいと思います。

環境

Windwows上でVM入れたりしていますが、Git bash 上で動かす方が多いと思います。
groovyは 2.4.7 でやっています。
groovyのソースはGGTSやEclipse neon上でいじっていますが、フリーズしたら vim でいじります。

text化

コマンドラインでやってるとどうしても grep したくなりますよね。
PDFだけのドキュメントなんて...
フラストレーションたまるので簡単にtextにできるのないかなーって思って探していたら、PDFBoxなんてのがありました(^ ^)
javaで使えるから groovy ならできるでしょーってことで groovy 勉強し始めて、やらないとすぐ忘れちゃうのでメモを残して行きたいと思います。

PDFBox
https://pdfbox.apache.org/

javaでPDFをごにょごにょできるツールみたいですねぇ。
ごにょごにょいっぱいしないので、今はtextにすることだけ集中してみたら
PDDocument, PDFTextStripper あたりを使ったらできそうでしたのでやってみました。

/*
 * http://pdfbox.apache.org/
 * PDFからテキストを抽出するサンプル
 */


import static groovy.io.FileType.*

import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.text.PDFTextStripper

@Grab('org.apache.pdfbox:pdfbox:2.0.0')
@Grab('org.bouncycastle:bcprov-jdk15on:1.47')


def fileToText(String path) {
  return fileToText(new File(path))
}

def fileToText(File file) {
  println "convert ${file.name}"
  PDDocument doc = PDDocument.load(file)

  def stripper = new PDFTextStripper()
  def text = stripper.getText(doc)

  doc.close()
  return text
}

/**
 * 特定のディレクトリのPDFをtext化する。
 */
def convertDir(dir) {
  dir.eachFileMatch(FILES, ~/.*\.pdf/) {
    convertFile(it)
  }
}

/**
 * 特定のファイルのPDFをtext化する。
 */
def convertFile(file) {
    String textPath = file.getAbsolutePath()
    textPath = textPath.substring(0, textPath.length() - 3) + "txt"
    new File(textPath).text = fileToText(file)
}

def convert(path) {
  File target = new File(path)
  if (target.isDirectory()) {
    convertDir(target)
  } else if (target.isFile()) {
    convertFile(target)
  } else {
    println "skip $path"
  }
}

args.each {
  convert(it)
}

うーん。groovyっぽくない気もしますけど、動くので良しとしておきましょう(^ ^;
PDFと同じディレクトリに txt ファイルを作成してくれます。
bcprov-jdk15onはなんか無いっていわれたので入れたような...


file.text って文字化けする時としないときがあるような気がしますが、文字化けするときは write つかって書き込むといい感じでしょうか。

5
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
5
5