728x90
public class ConvertFiles {
public static void main(String[] args) throws IOException {
String source = "";
String destinationDir = "";
convertPdfToImage (source, destinationDir);
}
public static void convertPdfToImage (String source, String destinationDir) {
/*
* 파일이 PDF라면 이미지로 변환
*/
try {
File sourceFile = new File(source);
File destinationFile = new File(destinationDir);
InputStream input = new FileInputStream(sourceFile);
if (!destinationFile.exists()) {
destinationFile.mkdirs();
system.out.println("저장 폴더 생성 -> " + destinationFile.getAbsolutePath());
}else if(destinationFile.exists()){
system.out.println("어 저장 폴더 있네!!!");
}else{
system.out.println("저장 폴더 생성 실패 ㅠㅠ!!!");
}
PDDocument document = PDDocument.load(input);// document 생성
PDFRenderer renderer = new PDFRenderer(document); // PDF 렌더러 불러오기
List<BufferedImage> bufferedImages = new ArrayList<BufferedImage>(); // 변환될 이미지 객체를 담을 List 선언
int width = 0, height = 0; // 병합될 이미지 파일의 너비와 높이 값을 담을 변수
for(int page = 0; page < document.getNumberOfPages(); page++) { // 한 페이지씩 꺼내와서
BufferedImage bim = renderer.renderImage(page); // 이미지로 변환
bufferedImages.add(bim); // 그리고 이미지 리스트에 담음
if(bim.getWidth() > width) width = bim.getWidth(); // 병합될 이미지의 최대 너비
height += bim.getHeight(); // 병합될 이미지의 최대 높이
}
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 병합될 이미지 객체 생성
Graphics2D graphics = (Graphics2D) bufferedImage.getGraphics(); // 그래픽 객체 생성
graphics.setBackground(Color.WHITE); // 배경을 흰색으로 지정
// 이미지 병합 과정
int idx = 0;
for(BufferedImage obj : bufferedImages) { // 이미지 List에서 이미지를 하나씩 꺼내와서
if(idx == 0) height = 0; // 첫번째 이미지의 경우 높이를 0으로 설정
graphics.drawImage(obj, 0, height, null); // 그래픽 객체에 꺼내온 이미지를 그려줌
height += obj.getHeight(); // 높이값을 이미지의 높이만큼 더해줌
idx++;
}
ImageIO.write(bufferedImage, "png", destinationFile); // 마지막으로 병합된 이미지 생성
graphics.dispose(); // 그래픽 리소스 해제
if (document != null) {
document.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
728x90