Home About
EPS , PDF , Java2D , Kotlin

EPS, PDF のサイズを取得する Apache XML Graphics Commons / PDFBox と kotlin を使用

EPS は、 https://xmlgraphics.apache.org/commons/ を使って、 PDF は、 https://pdfbox.apache.org を使って、 それぞれ 画像のタテヨコの大きさを取得します。 使用する言語は kotlin script です。

EPS

@file:DependsOn("org.apache.xmlgraphics:xmlgraphics-commons:2.7")

import java.io.*
import org.apache.xmlgraphics.ps.dsc.DSCParser
import org.apache.xmlgraphics.ps.dsc.events.DSCComment
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentBoundingBox

val epsWidthAndHeight: (File)-> Pair<Double,Double> = { epsFile->
    BufferedInputStream( FileInputStream( epsFile ) ).use { inputStream->
        val parser = DSCParser( inputStream )
    
        val commentList = arrayListOf<DSCComment>()
        while(parser.hasNext()) {
            val event = parser.nextEvent()
            if (event.isDSCComment()) {
                commentList.add( event.asDSCComment() )
            }
        }
    
        val boundingBoxCommentList = commentList.filter { it is DSCCommentBoundingBox }
        if( boundingBoxCommentList.size>0 ){
            val comment: DSCCommentBoundingBox = boundingBoxCommentList[0] as DSCCommentBoundingBox
            Pair(comment.boundingBox.width, comment.boundingBox.height)
        } else {
            Pair(0.toDouble(), 0.toDouble())
        }
    }
}

val epsFile = File("square.eps")
val result = epsWidthAndHeight( epsFile )
println( result )

EPS画像の大きさは、EPSファイル内の情報 BoundingBox または HiResBoundingBox を読みとればよいらしい。 それを XML Graphics Commons を使って調べるには、DSCParser を使って順番に Event をチェックしつつ DSCComment が存在すれば取得。 その後、DSCComment から DSCCommentBoundingBox クラス(またはそのサブクラス)のみをフィルタして、 DSCCommentBoundingBox にある getBoundingBox() メソッドで Rectangle2D を取得する流れです。

square.eps はmacOS で EPSファイルをJPEGに変換するなど のエントリーで使ったものを使用しています。

実行してみます。

$ kotlin ./imagesize.main.kts
(300.0, 300.0)

うまく width/height が取得でました。

なお、imagesize.main.kts の実行方法の詳細はこちらを参照してください。

PDF

今度は PDF の大きさを調べます。 PDFは複数ページある可能性がありますが、ここでは先頭ページの大きさだけを調べます。

@file:DependsOn("org.apache.pdfbox:pdfbox:3.0.0-alpha3")

import java.io.*
import org.apache.pdfbox.Loader
import org.apache.pdfbox.pdmodel.PDPage

val pdfWidthAndHeight: (File)-> Pair<Float,Float> = { pdfFile->
    BufferedInputStream( FileInputStream( pdfFile ) ).use { inputStream->
        val doc = Loader.loadPDF(inputStream)
        val page = doc.getPages()[0]
        val rect = page.getMediaBox()
        Pair(rect.width, rect.height)
    }
}    

val pdfFile = File("square.pdf")
val result = pdfWidthAndHeight( pdfFile )
println( result )

実行してみます。

$ kotlin ./imagesize.main.kts
(300.0, 300.0)

うまくいきました。

Liked some of this entry? Buy me a coffee, please.