반응형
# Java iText API 활용 PDF table 만들기 (Java PDF Handling)
## iText API 다운로드 및 적용방법
- Mave Repository 에서 iText 검색 하여 iText Core API 다운로드 (jar 파일 다운로드 받거나 or maven dependency 태그)
- https://mvnrepository.com/search?q=itext
- 다운로드 받은 jar 파일의 경우 별도의 공간(C:\JavaTPC\lib 등..) 에 저장 후 아래와 같이 설정 진행.
- 프로젝트 우 클릭 Build Path > configure Build Path 클릭.
- Libraries > Add External JARs 클릭하여 저장한 jar 파일 추가. (자바가 12버전 이상인 경우 Modulepath(자바모듈) 와 Classpath(외부 API 모듈)로 나누어 표시(관리)되어 있어서 Classpath에 추가해주면 되는데, 자바가 그 이전 버전인 경우에는 Add ExternalJARs 해서 바로 추가해주면 됨)
- 완료 후 아래와 같이 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();
}
}
}
반응형
'인프런 강의 학습 > Java TPC 실전' 카테고리의 다른 글
Java iText API 활용 PDF 에 image 삽입 및 크기조절 하기 (0) | 2022.07.27 |
---|---|
Java iText API 활용 PDF 에 Paragraph(단락, 문단, 절) 만들기 (0) | 2022.07.27 |
Naver Search API 활용 도서정보를 입력하여 검출 후 Excel에 저장하기 (0) | 2022.07.22 |
Naver Search API 활용 도서정보를 입력하여 ISBN, IMAGE 검출하기 (0) | 2022.07.20 |
Naver Search API 활용 Excel에서 Cell의 데이터타입 알아보기 (0) | 2022.07.11 |