반응형

# Java iText API 활용 PDF table 만들기 (Java PDF Handling)

## iText API 다운로드 및 적용방법

  • 다운로드 받은 jar 파일의 경우 별도의 공간(C:\JavaTPC\lib 등..) 에 저장 후 아래와 같이 설정 진행. 
  1. 프로젝트 우 클릭 Build Path > configure Build Path 클릭.
  2. Libraries > Add External JARs 클릭하여 저장한 jar 파일 추가. (자바가 12버전 이상인 경우 Modulepath(자바모듈) 와 Classpath(외부 API 모듈)로 나누어 표시(관리)되어 있어서 Classpath에 추가해주면 되는데, 자바가 그 이전 버전인 경우에는 Add ExternalJARs 해서 바로 추가해주면 됨) 
  3. 완료 후 아래와 같이 Referenced Libraries에 해당 API가 추가되어있는지 확인, 사용 시에는 import 하여 사용하면 된다.

## 테이블 스타일 설정.

테이블 (Table) 만들기

PdfPTable table = new PdfPTable();
table.setWidthPercentage(100);	// Table 의 폭 %로 조절 가능.

테이블 컬럼 폭 (Table Column Width) 조절

float[] columnWidths = new float[]{20f, 15f, 15f, 30f};
table.setWidths(columnWidths);

테이블 셀 (Table Cell) 정렬

// H정렬 (Element.ALIGN_LEFT, Element.ALIGN_RIGHT, Element.ALIGN_CENTER)
cell.setHorizontalAlignment(Element.ALIGN_CENTER);

// V정렬 (Element.ALIGN_TOP, Element.ALIGN_MIDDLE, Element.ALIGN_BOTTOM)
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

테이블 셀 여백 (Table Cell Padding) 조절

// 전체 한번에 줄 때.
cell.setPadding(10);

// 개별로 줄 때.
cell.setPaddingTop(20);
cell.setPaddingRight(30);
cell.setPaddingBottom(20);
cell.setPaddingLeft(30);

테이블 컬럼 (Table Column) 합치기

cell.setColspan(2);

## 생성 결과

## 작업소스

import java.io.*;

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class Project04_A {
	public static void main(String[] args) {
		// Java iText API 활용.
		String[] title = new String[]{"제목", "저자", "출판사", "이미지URL"};
		String[][] rows = new String[][] {
			{"강아지", "저자1", "출판사1", "http://image.yes24.com/goods/110791050/XL"},
			{"고양이", "저자2", "출판사2", "http://image.yes24.com/goods/110791050/XL"},
			{"흑염소", "저자3", "출판사3", "http://image.yes24.com/goods/110791050/XL"}
		};
		
		// PDF 생성 절차.
		// 1. 메모리에 PDF 파일 임시로 생성. (Document)
		Document doc = new Document(PageSize.A4);
		try {
			PdfWriter.getInstance(doc, new FileOutputStream(new File("book.pdf")));
			doc.open();
			
			// 한글 폰트
			BaseFont bf = BaseFont.createFont("malgun.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
			Font titleFont = new Font(bf, 12);
			Font rowsFont = new Font(bf, 10);
			
			// Table 생성
			PdfPTable table = new PdfPTable(title.length);	// 컬럼 갯수 지정.
			table.setWidthPercentage(100);	// Table 의 폭 %로 조절 가능.
			
			// 테이블 컬럼 폭 지정
			float[] colwidth = new float[]{20f, 15f, 15f, 30f};
			table.setWidths(colwidth);
			
			// 헤더 생성
			for (String header : title) {
				// Cell 생성
				PdfPCell cell = new PdfPCell();
				cell.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell.setPadding(10);	// 셀 여백 지정
				cell.setGrayFill(0.9f);	// 셀 배경 지정.
				cell.setPhrase(new Phrase(header, titleFont));	// 셀에 글자 작성.
				table.addCell(cell);
			}
			table.completeRow();
			
			for (String[] row : rows) {
				for (String data : row) {
					Phrase phrase = new Phrase(data, rowsFont);
					PdfPCell cell = new PdfPCell(phrase);
					cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
					cell.setPaddingTop(20);
					cell.setPaddingRight(30);
					cell.setPaddingLeft(30);
					cell.setPaddingBottom(20);
					table.addCell(cell);
				}
				table.completeRow();
			}
			
			PdfPCell cell4 = new PdfPCell(new Phrase("Cell 5"));
			cell4.setColspan(2);
			
			PdfPCell cell5 = new PdfPCell(new Phrase("Cell 6"));
			cell5.setColspan(2);
			
			table.addCell(cell4);
			table.addCell(cell5);
			
			doc.addTitle("PDF Table Demo");
			doc.add(table);
			
			System.out.println("PDF 생성 완료");
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			doc.close();
		}
	}
}
반응형

+ Recent posts