본문 바로가기
Spring/study

spring 11강 itextpdf를 활용한 pdf 파일 만들기

by avvin 2019. 6. 26.

spring 11강 itextpdf를 활용한 pdf 파일 만들기



- Maven Repository에서 itextpdf 라이브러리 소스 가져오기

- http://itextpdf.com에 API , 사용법 제시돼있음

- 한글 처리를 위한 폰트 정보 필요



pom.xml에 itext 관련 라이브러리 추가


<artifactId>

itextpdf

itext-pdfa

itext-xtra

xmlworker

itext-asian



PdfController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.example.spring02test.controller.pdf;
 
import javax.inject.Inject;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
import com.example.spring02test.service.pdf.PdfServiceImpl;
 
@Controller
@RequestMapping("pdf/*")//공통적인 url mapping
public class PdfController {
 
 
    @Inject
    PdfServiceImpl pdfService;
    
    @RequestMapping("list.do")
    public ModelAndView list() throws Exception{
        //pdf 파일 생성
        String result = pdfService.createPdf();
        
        return new ModelAndView("pdf/result""message", result);
    }
}
 



PdfService.java


PdfServiceImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package com.example.spring02test.service.pdf;
 
import java.io.FileOutputStream;
import java.util.List;
 
import javax.inject.Inject;
 
import org.springframework.stereotype.Service;
 
import com.example.spring02test.model.shop.dto.CartDTO;
import com.example.spring02test.service.shop.CartService;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
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;
 
@Service
public class PdfServiceImpl implements PdfService {
    
    //장바구니 서비스 객체 주입 : 장바구니 목록 출력할 예정
    @Inject
    CartService cartService;
    
    @Override
    public String createPdf() {
        
         String result = "";
         try {
            //pdf 문서 처리하는 객체
             Document document = new Document();
             PdfWriter writer =
                     PdfWriter.getInstance(document, new FileOutputStream("d:/sample.pdf"));
             document.open();
             BaseFont baseFont = BaseFont.createFont(
                     "c:/windows/fonts/malgun.ttf",
                     BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
             //확장자가 .ttf인 폰트를 써야한다.
             Font font = new Font(baseFont, 12); //기본 폰트 생성
             PdfPTable table = new PdfPTable(4);//4개의 셀을 가진 테이블
             
             Chunk chunk = new Chunk("장바구니", font); //기본폰트로 타이틀
             
             Paragraph ph = new Paragraph(chunk);//문단 객체 만들어서
             ph.setAlignment(Element.ALIGN_CENTER);//가운데 정렬
             document.add(ph); //문서에 문단 설정 추가
             
             document.add(Chunk.NEWLINE);
             document.add(Chunk.NEWLINE);//문서에 줄바꿈 두 줄
         
             PdfPCell cell1 = new PdfPCell(new Phrase("상품명",font));
             cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
             PdfPCell cell2 = new PdfPCell(new Phrase("단가",font));
             cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
             PdfPCell cell3 = new PdfPCell(new Phrase("수량",font));
             cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
             PdfPCell cell4 = new PdfPCell(new Phrase("금액",font));
             cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
             
             //셀 4개로 만든 테이블에 셀 붙이기
             table.addCell(cell1);
             table.addCell(cell2);
             table.addCell(cell3);
             table.addCell(cell4);
             
             List<CartDTO> items = cartService.listCart("park");//아이디 기입
             
             for(int i=0; i<items.size(); i++) {
                 CartDTO dto = items.get(i);
                 PdfPCell cellProductName = 
                         new PdfPCell (new Phrase(dto.getProduct_name(), font));
                 PdfPCell cellPrice= 
                         new PdfPCell (new Phrase("" + dto.getPrice(), font));
                 PdfPCell cellAmount = 
                         new PdfPCell (new Phrase("" + dto.getAmount(), font));
                 PdfPCell cellMoney = 
                         new PdfPCell (new Phrase("" + dto.getMoney(), font));
                 table.addCell(cellProductName);
                 table.addCell(cellPrice);
                 table.addCell(cellAmount);
                 table.addCell(cellMoney);
             }
             document.add(table);
             document.close();
             result ="pdf 파일이 생성되었습니다.";
             
         } catch(Exception e) {
             result=  "pdf 파일 생성 실패...";
             e.printStackTrace();
         }
 
        return result;
    }
 
}
 





result.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<%@include file="../include/header.jsp" %>
</head>
<body>
<%@include file="../include/admin_menu.jsp" %>
<h2>${message}</h2>
 
</body>
</html>