22
22

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.

Apache PDFBoxでPDFページを画像にする(ラスタライズ)

Posted at

Apache PDFBoxが日本語出力できるようになったのでちょっとPDFBoxどんなことできるのっていうのを少しずつ調べようかと思いました。

今回はPDFを画像にする(ラスタライズ)方法です。

https://pdfbox.apache.org/2.0/migration.html#pdf-rendering
に記載されている方法です。
(ネットで調べると「convertToImage使え」っていう記事が多く出てきますが、2系で方法が変わったようですね。)

コード

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("pdf.jpg");
        try (InputStream in = new FileInputStream("pdf.pdf");
                OutputStream out = Files.newOutputStream(path);) {
            rasterize(in, out);
        }

        System.out.println(path.toAbsolutePath());
    }

    public static void rasterize(InputStream in, OutputStream out) throws IOException {
        try (PDDocument doc = PDDocument.load(in)) {

            PDFRenderer pdfRenderer = new PDFRenderer(doc);

            BufferedImage bim = pdfRenderer.renderImageWithDPI(0/*1ページ目を対象にする*/, 300, ImageType.RGB);

            ImageIO.write(bim, "JPEG", out);
        }
    }

結果

jpgになった。

image

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?