본문 바로가기
IT 개발/JAVA

PDF파일 작성 (pdfbox)

by Love of fate 2022. 7. 7.
728x90
반응형

[PDF파일 작성 (pdfbox)]

 

POM.XML

- pdfbox maven 설정

1
2
3
4
5
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.8</version>
        </dependency>     
cs

 

JAVA Controller

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
    @RequestMapping(value = "/pdfTest", method = RequestMethod.GET)
    @ResponseBody
    public void pdfTest(HttpServletResponse response) throws IOException {
        
        // 문서 만들기
        PDDocument doc = new PDDocument();
        // 파일 다운로드 설정
        response.setContentType("application/pdf");
        String fileName;
 
        
        try {
            
            fileName = URLEncoder.encode("샘플PDF""UTF-8");
 
            response.setHeader("Content-Disposition""inline; filename=" + fileName + ".pdf");
 
            PDPage blankPage = null;
            PDPage page = null
            InputStream fontStream = new FileInputStream("C:/Windows/fonts/malgun.ttf");
            PDType0Font fontGulim = PDType0Font.load(doc, fontStream);
            
            for(int i = 0; i < 3; i++) {
                
                // 작업 페이지 설정
                blankPage = new PDPage(PDRectangle.A4);
                doc.addPage(blankPage);
                
                page = doc.getPage(i);
                
                // 배경이미지 로드
                //PDImageXObject pdImage = PDImageXObject.createFromFile(webroot + "resources/back.jpg", doc);
                
                // 컨텐츠 스트림 열기
                PDPageContentStream contentStream = new PDPageContentStream(doc, page);
                
                // 배경 이미지  그리기
                //contentStream.drawImage(pdImage, 0, 0, 595, 842);
                
                
                contentStream.beginText();
                contentStream.setFont(fontGulim, 12);
 
                String text = "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn";
                
                // 글쓰기
                contentStream.showText(text);
                
                // 글쓰기 종료
                contentStream.endText();
                contentStream.close();
 
            }
            
            doc.save(response.getOutputStream());
 
            // Closing the document
            doc.close();
            
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
cs

 

생성된 파일 

샘플PDF.pdf
0.01MB

728x90
반응형

'IT 개발 > JAVA' 카테고리의 다른 글

JAVA - WAS 서버에서 이미지 표출 처리  (0) 2023.03.13
CollectionUtils 사용법  (0) 2023.01.02
jasypt 암호화 복호화  (0) 2022.01.03
JAVA - Enum 타입  (0) 2021.11.04
Not allowed to read local resource 오류  (0) 2021.11.04