반응형

# Java iText API 활용 Excel에서 데이터 읽어서 PDF로 만들기

  • Excel 에 저장된 데이터를 읽어서 PDF로 생성. (Excel > PDF)
  • 기존에 키값에 해당하는 데이터를 입력하여 조회된 정보를 Excel 파일로 만드는 작업을 했었는데, 반대로 Excel 에 저장된 데이터를 가져와 PDF로 생성하는 작업 진행. (이전 작업 내역 종합하여 진행)

## 생성 결과

## 작업 소스

isbn.xls
0.25MB
bookList.pdf
0.31MB
malgun.ttf
12.83MB

import java.io.*;
import java.util.*;
import java.util.List;

import org.apache.poi.hssf.usermodel.*;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import kr.inflearn.ExcelVO;

public class Project04_F {
	public static void main(String[] args) {
		// 엑셀 데이터 읽어와서 PDF 생성하기.
		// 1. 엑셀 불러오기
		String filename = "isbn.xls";	
		
		List<ExcelVO> data = new ArrayList<ExcelVO>();
		try (FileInputStream fis = new FileInputStream(filename)) {
			HSSFWorkbook workbook = new HSSFWorkbook(fis);
			HSSFSheet sheet = workbook.getSheetAt(0);
			Iterator rows = sheet.rowIterator();
			String[] imsi = new String[5];
			
			rows.next();	// 첫번째 줄은 헤더 이므로 다음줄로 이동.
			while (rows.hasNext()) { // 로우
				HSSFRow row = (HSSFRow) rows.next();
				Iterator cells = row.cellIterator();
				
				int i = 0;
				while (cells.hasNext()) {	// 셀 정보
					HSSFCell cell = (HSSFCell) cells.next();
					imsi[i] = cell.toString();
					i++;
					
					if (i == 5) {	// 5의 경우 이미지 정보로 필요없으므로 5일때 break.
						break;
					}
				}
				
				ExcelVO vo = new ExcelVO(imsi[0], imsi[1], imsi[2], imsi[3], imsi[4]);
				data.add(vo);
			}
			
			// 2. Excel 데이터 바탕으로 PDF 생성
			pdf_maker(data);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private static void pdf_maker(List<ExcelVO> data) {
		// 헤더에 들어갈 값.
		String[] headers = new String[]{"제목", "저자", "출판사", "이미지"};
		
		Document doc = new Document(PageSize.A4);
		try {
			PdfWriter.getInstance(doc, new FileOutputStream(new File("bookList.pdf")));
			doc.open();
			
			// 폰트 설정.
			BaseFont bFont = BaseFont.createFont(
					"MALGUN.TTF", 
					BaseFont.IDENTITY_H	
					, BaseFont.NOT_EMBEDDED);
			Font headerFont = new Font(bFont, 12);	// 헤더 폰트
			Font rowFont = new Font(bFont, 10);	// row 폰트
			
			// 테이블 생성
			PdfPTable table = new PdfPTable(headers.length);
			
			for (String header : headers) {
				// 테이블_셀 생성
				PdfPCell cell = new PdfPCell();
				cell.setGrayFill(0.9f);
				cell.setPhrase(new Phrase(header.toUpperCase(), headerFont));
				table.addCell(cell);
			}	
			table.completeRow();	
			
			// Excel데이터 바탕, PDF에 들어갈 테이블에 정보 입력.
			for (ExcelVO vo : data) {
				Phrase phrase = new Phrase(vo.getTitle(), rowFont);
				table.addCell(new PdfPCell(phrase));
				
				phrase = new Phrase(vo.getAuthor(), rowFont);
				table.addCell(new PdfPCell(phrase));
				
				phrase = new Phrase(vo.getCompany(), rowFont);
				table.addCell(new PdfPCell(phrase));
				
				// 이미지
				Image image = Image.getInstance(vo.getImageUrl());
				table.addCell(image);
				
				table.completeRow();
			}
			doc.addTitle("PDF Table Demo");
			doc.add(table);	// document 에 생성한 테이블 추가.
			System.out.println("bookList 생성 완료.");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			doc.close();
		}		
	}
}
반응형

+ Recent posts