前人未踏の領域へ Androidアプリ開発編

Androidアプリ開発に関する調査メモ置き場。古い記事にはアプリ以外も含まれます。

PDFを画像に変換する

Pdf-rendererを使用。
日本語フォントはPDFに埋め込まれていないとエラーになります。

package org.codelibs.pdf2image;

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import javax.imageio.ImageIO;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

public class Pdf2Image {

	/**
	 * PDF1ページ分をImageオブジェクトに変換します
	 * @param page
	 * @return
	 */
	public static Image pdf2image(PDFPage page) {
		int w = (int) page.getBBox().getWidth();
		int h = (int) page.getBBox().getHeight();
		// get the width and height for the doc at the default zoom
		Rectangle rect = new Rectangle(0, 0, w, h);

		// generate the image
		return page.getImage(rect.width, rect.height, // width & height
				rect, // clip rect
				null, // null for the ImageObserver
				true, // fill background with white
				true // block until drawing is done
				);
	}

	/**
	 * PDFファイルの任意のページを抽出します。
	 * @param pdf
	 * @param page
	 * @return
	 */
	public static PDFPage getPDFPage(File pdf, int page) {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(pdf, "r");
			FileChannel channel = raf.getChannel();
			ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0,
					channel.size());
			PDFFile pdfFile = new PDFFile(buf);
			return pdfFile.getPage(page);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (raf != null) {
				try {
					raf.close();
				} catch (IOException e) {
					// do nothing
				}
			}
		}
		return null;

	}
	
	/**
	 * PDFファイルをPNGファイルに変換します。
	 * @param pdfPath 読み込むPDFファイルのパス
	 * @param outPath 出力する画像ファイルのパス
	 * @return
	 */
	public static int printImage(String pdfPath,String outPath,int page) {
		File f = new File(pdfPath);
		PDFPage pdfPage = getPDFPage(f, page);
		int w = (int) pdfPage.getBBox().getWidth();
		int h = (int) pdfPage.getBBox().getHeight();
		Image img = pdf2image(pdfPage);
		BufferedImage buffered = new BufferedImage(w, h, Image.SCALE_SMOOTH);
		buffered.getGraphics().drawImage(img, 0, 0, null);
		try {
			save(buffered, new File(outPath));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public static void save(BufferedImage img, File f) throws IOException {
		if (!ImageIO.write(img, "PNG", f)) {
			throw new IOException("フォーマットが対象外");
		}
	}
}

呼び出し側

    private static final String SAMPLE_PDF = "./data/sample.pdf";
    private static final String SAMPLE_PNG = "./data/sampleImage.png";
    public void testPrintSize(){
    	Pdf2Image.printImage(SAMPLE_PDF, SAMPLE_PNG,1);
    }