'PDFRenderer'에 해당되는 글 1건

PDFRenderer는 pdf파일을 page단위로 java.awt.Image 개체로 만듭니다.

package com.pdfImg.pdfTest;

import java.awt.Graphics2D;
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 PdfImage {
	public static void main(String args[]) throws IOException{
    
    	//load a pdf from a byte buffer
        File file = new File("c:\\User\\test.pdf");
        RandomAccessFile raf = new RandomAccessFile(file, "r");
        FileChannel channel = raf.getChannel();
        ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
        PDFFile pdffile = new PDFFile(buf);
        
        // draw the first page to an image
        PDFPage page = pdffile.getPage(2);
        
        //get the width and height for the doc at the default zoom 
        Rectangle rect = new Rectangle(0,0,(int)page.getBBox().getWidth(),(int)page.getBBox().getHeight());
        
        //generate the image
        Image image = 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
		);
        
        int w = image.getWidth(null);
        int h = image.getHeight(null);
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bi.createGraphics();
        g2.drawImage(image, 0, 0, null);
        g2.dispose();
        
        try{
        	ImageIO.write(bi, "jpg", new File("c:\\User\\imagePdfTest.jpg"));
        }catch(IOException ioe){
        	System.out.println("write: " + ioe.getMessage());
        }
	}        
}

---------------- 간략한 소스 설명 ----------------
// draw the first page to an image
PDFPage page = pdffile.getPage(2);

위의 코드가 pdf의 특정 page를 선택하는 부분입니다. 2페이지를 선택했습니다.

pdffile.getNumPages();
위의 코드로 pdf파일의 총 페이지 수를 알 수 있습니다.

총 페이지 수로 for문을 돌리면 모든 페이지를 이미지로 만들 수 있을 것 입니다.

'JAVA' 카테고리의 다른 글

[JAVA] RequestContextListene request 반환  (0) 2022.05.24
[JAVA] replaceAll 정규식  (0) 2022.05.23
[JAVA] PathVariable  (0) 2022.05.23
[JAVA] Object Array  (0) 2022.05.23
[JAVA] 휴일 알아내기  (0) 2021.06.25
블로그 이미지

마크제이콥스

초보 개발자의 이슈및 공부 내용 정리 블로그 입니다.

,