반응형

# 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();
		}
	}
}
반응형
반응형

#  Naver Search API 활용 도서정보를 입력하여 ISBN, IMAGE 검출 후 Excel에 저장하기

  • Naver Search API 연동, 도서정보를 입력(요청 변수 값) 하여 원하는 정보(ISBN, IMAGE) 검출. (Jsoup 사용)
  • 검출된 데이터 Excel에 저장.

## 작업 소스

  • 메인 java 소스
import java.io.*;

import kr.inflearn.ExcelDAO;

public class Project03_F {
	public static void main(String[] args) {
		ExcelDAO dao = new ExcelDAO();
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		try {
			System.out.print("입력처리(I) / 종료(E) : ");
			String sw = br.readLine();
			switch (sw) {
				case "I":
					dao.excel_input();
					break;
				case "E":
					System.out.println("프로그램이 종료됩니다.");
					System.exit(0);
					break;
				default:
					System.out.println("I or E 를 입력해주세요.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
  • 실 기능 수행하는 java 소스
package kr.inflearn;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class ExcelDAO {
	private List<ExcelVO> list;
	private HSSFWorkbook wb;
	public ExcelDAO() {
		list = new ArrayList<ExcelVO>();
		wb = new HSSFWorkbook();
	}
	
	public void excel_input() {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		try {
			HSSFSheet firstSheet = wb.createSheet("BOOK SHEET");
			HSSFRow rowA = firstSheet.createRow(0);
			HSSFCell cellA = rowA.createCell(0);
			cellA.setCellValue(new HSSFRichTextString("책제목"));
			
			HSSFCell cellB = rowA.createCell(1);
			cellB.setCellValue(new HSSFRichTextString("저자"));
			
			HSSFCell cellC = rowA.createCell(2);
			cellC.setCellValue(new HSSFRichTextString("출판사"));
			
			HSSFCell cellD = rowA.createCell(3);
			cellD.setCellValue(new HSSFRichTextString("ISBN"));

			HSSFCell cellE = rowA.createCell(4);
			cellE.setCellValue(new HSSFRichTextString("이미지이름"));
			
			int i = 1;
			while (true) {
				System.out.print("책의 제목을 입력해주세요 : ");
				String title = br.readLine();
				System.out.print("책의 저자를 입력해주세요 : ");
				String author = br.readLine();
				System.out.print("책의 출판사를 입력해주세요 : ");
				String company = br.readLine();
				
				HSSFRow rowRa1 = firstSheet.createRow(i);
				HSSFCell cellTitle = rowRa1.createCell(0);
				cellTitle.setCellValue(new HSSFRichTextString(title));
				HSSFCell cellAuthor = rowRa1.createCell(1);
				cellTitle.setCellValue(new HSSFRichTextString(author));
				HSSFCell cellCompany = rowRa1.createCell(2);
				cellTitle.setCellValue(new HSSFRichTextString(company));
				i++;
				
				ExcelVO vo = new ExcelVO(title, author, company);
				ExcelVO data = naver_search(vo);
				list.add(data);
				System.out.println("계속 입력하시려면 Y / 종료하시려면 N 을 입력해주세요 : ");
				String key = br.readLine();
				if (key.equals("N")) break;
			}
			System.out.println("데이터 추출 작업 중 입니다.........");
			excel_save();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private ExcelVO naver_search(ExcelVO vo) {
		try {
			String openApi = "https://openapi.naver.com/v1/search/book_adv.xml?d_titl=" 
					+ URLEncoder.encode(vo.getTitle(), "UTF-8") 
					+ "&d_auth=" + URLEncoder.encode(vo.getAuthor(), "UTF-8") 
					+ "&d_publ="+ URLEncoder.encode(vo.getCompany(), "UTF-8");
			
			URL url = new URL(openApi);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("GET");
			con.setRequestProperty("X-Naver-Client-Id", "발급받은 Client_Id 입력");
			con.setRequestProperty("X-Naver-Client-Secret", "발급받은 Client_Secret 입력");
			
			int responseCode = con.getResponseCode();
			BufferedReader br1 = null;

			if (responseCode == 200) {
				br1 = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
			} else {
				br1 = new BufferedReader(new InputStreamReader(con.getErrorStream()));
			}
			
			String inputLine = null;
			StringBuffer response = new StringBuffer();
			
			while ((inputLine = br1.readLine()) != null) {
				response.append(inputLine);
			}
			br1.close();
			
			// ISBN, IMAGE 정보 꺼내기
			Document doc = Jsoup.parse(response.toString());
			Element isbn = doc.select("isbn").first();
			String img = doc.toString();
			String imgTag = img.substring(img.indexOf("<img>")+5);
			
			img = imgTag.substring(0, imgTag.indexOf("?"));
			vo.setIsbn(isbn.text().split(" ")[1]);
			
			String fileName = img.substring(img.lastIndexOf("/")+1);
			vo.setImageUrl(fileName);
			
			// DownloadBroker
			Runnable download = new DownloadBroker(img, fileName);
			Thread t = new Thread(download);
			t.start();			
		} catch (Exception e) {
			e.printStackTrace();
		}
			
		return vo;
	}
	
	private void excel_save() {
		try {
			HSSFSheet sheet = wb.getSheetAt(0);
			
			if (wb != null && sheet != null) {
				Iterator rows = sheet.rowIterator();
				rows.next();
				
				int i = 0;
				while (rows.hasNext()) {
					HSSFRow row = (HSSFRow) rows.next();
					HSSFCell cell = row.createCell(3);		
					cell.setCellType(CellType.STRING);
					cell.setCellValue(list.get(i).getIsbn());
					
					cell = row.createCell(4);
					cell.setCellType(CellType.STRING);
					cell.setCellValue(list.get(i).getImageUrl());
					
					InputStream inputStream = new FileInputStream(list.get(i).getImageUrl());
					byte[] bytes = IOUtils.toByteArray(inputStream);
					int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
					inputStream.close();
					
					CreationHelper helper = wb.getCreationHelper();
					Drawing drawing = sheet.createDrawingPatriarch();
					ClientAnchor anchor = helper.createClientAnchor();
					
					anchor.setCol1(5);
					anchor.setRow1(i+1);
					anchor.setCol2(6);
					anchor.setRow2(i+2);
					
					Picture pict = drawing.createPicture(anchor, pictureIdx);
					Cell cellImg = row.createCell(5);
					int widthUnits = 20*256;
					sheet.setColumnWidth(5, widthUnits);
					short heightUnits = 120*20;
					cellImg.getRow().setHeight(heightUnits);
					
					i++;
				}
				
				FileOutputStream fos = new FileOutputStream("isbn.xls");
				wb.write(fos);
				fos.close();
				System.out.println("ISBN 및 ImageURL 저장 성공.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

## 출력 결과

  • 아래와 같이 진행 시 Java의 정석 책 표지 이미지가 추출되어 저장되는것을 확인할 수 있다.

반응형
반응형

#  Naver Search API 활용 도서정보를 입력하여 ISBN, IMAGE 검출하기

  • Naver Search API 연동, 도서정보를 입력(요청 변수 값) 하여 원하는 정보(ISBN, IMAGE) 검출. (Jsoup 사용)

## 준비물

 

책 - Search API

책 NAVER Developers - 검색 API 책 검색 개발가이드 검색 > 책 네이버 책 검색 결과를 출력해주는 REST API입니다. 비로그인 오픈 API이므로 GET으로 호출할 때 HTTP Header에 애플리케이션 등록 시 발급받은 C

developers.naver.com

  • 위 사이트 접속하여 '오픈 API 이용 신청' 버튼 클릭.

  • 아래와 같이 정보 입력하여 등록 신청.

  • 등록 완료 시 발급 되는 키 (Client ID, Client Secret) 이용하여 연동 진행.

## 작업 소스

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import kr.inflearn.ExcelVO;

public class Project03_D {
	public static void main(String[] args) {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		try {
			System.out.print("책의 제목을 입력해주세요 : ");
			String title = br.readLine();
			System.out.print("책의 저자를 입력해주세요 : ");
			String author = br.readLine();
			System.out.print("출판사를 입력해주세요 : ");
			String company = br.readLine();
			
			ExcelVO vo = new ExcelVO(title, author, company);

			getIsbnImage(vo);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void getIsbnImage(ExcelVO vo) {
		try {
			String openApi = "https://openapi.naver.com/v1/search/book_adv.xml?d_titl=" 
					+ URLEncoder.encode(vo.getTitle(), "UTF-8") 
					+ "&d_auth=" + URLEncoder.encode(vo.getAuthor(), "UTF-8") 
					+ "&d_publ="+ URLEncoder.encode(vo.getCompany(), "UTF-8");
			
			URL url = new URL(openApi);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("GET");
			con.setRequestProperty("X-Naver-Client-Id", "발급받은 Client_Id 입력");
			con.setRequestProperty("X-Naver-Client-Secret", "발급받은 Client_Secret 입력");
			
			int responseCode = con.getResponseCode();
			BufferedReader br1 = null;

			if (responseCode == 200) {
				br1 = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
			} else {
				br1 = new BufferedReader(new InputStreamReader(con.getErrorStream()));
			}
			
			String inputLine = null;
			StringBuffer response = new StringBuffer();
			
			while ((inputLine = br1.readLine()) != null) {
				response.append(inputLine);
			}
			br1.close();
			
			// ISBN, IMAGE 정보 꺼내기
			Document doc = Jsoup.parse(response.toString());
			Element total = doc.select("total").first();
			
			if (!total.text().equals("0")) {
				Element isbn = doc.select("isbn").first();
				String isbnStr = isbn.text();
				String isbn_find = isbnStr.split(" ")[1];
				vo.setIsbn(isbn_find);
				
				String imgDoc = doc.toString();
				String imgTag = imgDoc.substring(imgDoc.indexOf("<img>")+5);
				String imgURL = imgTag.substring(0, imgTag.indexOf("?"));
				System.out.println(imgURL);
				String fileName = imgURL.substring(imgURL.lastIndexOf("/")+1);
				System.out.println(fileName);
				vo.setImageUrl(fileName);
				System.out.println(vo);
			} else {
				System.out.println("검색된 데이터가 없습니다.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
			
	}
}

## 출력 결과

  • 도서 정보 입력 후 확인 시 아래와 같이 출력 되는것을 확인할 수 있다.

 

반응형
반응형

# Naver Search API 활용 Excel에서 Cell의 데이터타입 알아보기

## 작업소스

  • 아래와 같이 엑셀 파일 생성하여 저장.

cellDataType.xls
0.02MB

  • 아래와 같이 작업하여 셀타입 확인 가능.
import java.io.FileInputStream;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;

public class Project03_C {
	public static void main(String[] args) {
		String fileName = "cellDataType.xls";
		
		try (FileInputStream fis = new FileInputStream(fileName)) {
			
			HSSFWorkbook workbook = new HSSFWorkbook(fis);
			
			HSSFSheet sheet = workbook.getSheetAt(0);
			Iterator<Row> rows = sheet.rowIterator();
			
			while (rows.hasNext()) {
				HSSFRow row = (HSSFRow) rows.next();
				Iterator<Cell> cells = row.cellIterator();
				
				while (cells.hasNext()) {
					HSSFCell cell = (HSSFCell) cells.next();
					CellType type = cell.getCellType();
					
					if (type == CellType.STRING) {
						System.out.println("[" + cell.getRowIndex() 
								+ "," + cell.getColumnIndex() + "]"
								+ " = STRING; Value : " + cell.getRichStringCellValue());
					} else if (type == CellType.NUMERIC) {
						System.out.println("[" + cell.getRowIndex() 
						+ "," + cell.getColumnIndex() + "]"
						+ " = NUMERIC; Value : " + cell.getNumericCellValue());
					} else if (type == CellType.BOOLEAN) {
						System.out.println("[" + cell.getRowIndex() 
						+ "," + cell.getColumnIndex() + "]"
						+ " = BOOLEAN; Value : " + cell.getBooleanCellValue());
					} else if (type == CellType.BLANK) {
						System.out.println("[" + cell.getRowIndex() 
						+ "," + cell.getColumnIndex() + "]"
						+ " = BLANK; Value : BLANK CELL");
					}					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
반응형

+ Recent posts