본문 바로가기

소질없는 개발/Java

java itextpdf 를 이용하여 테이블을 가진 pdf 다운로드 구현하기

1. Gradle 설정 추가

 comlile('com.itextpdf:itextpdf:5.5.13')


 - Gradle 이외 설정은 mvnrepository 참조 (https://mvnrepository.com/artifact/com.itextpdf/itextpdf/5.5.13)

 - AGPL 라이센스임에 주의! 네트웍 서비스에 이용하는 경우에도 소스를 공개하여야 함 ㄷㄷ



2. pdf document 생성 및 download 처리

public ResponseEntity<InputStreamResource> downloadPDF() {

List<TableData> tableDataList = getTableData(); // 각자.. ByteArrayInputStream inputStream = generatePDF(tableDataList); String filename = String.format("download_test_%s.pdf", LocalDateTime.now().toString("yyyy-MM-dd"));


HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "inline; filename=" + filename);


return ResponseEntity.ok()

.headers(headers)

.contentType(MediaType.APPLICATION_PDF)

.body(new InputStreamResource(inputStream)); } private ByteArrayOutputStream generatePDF(List<TableData> tableDataList) { Document document = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try {

document = new Document();

// 한글 처리를 위한 글꼴 설정 추가 String fontPath = "/static/css/fonts/malgun.ttf"; BaseFont bf = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font titleFont = new Font(bf, 15, Font.BOLD); Paragraph title = new Paragraph("문 서 제 목", titleFont); Font subTitleFont = new Font(bf, 14, Font.NORMAL); DateFormat titledf = new SimpleDateFormat("yyyy-MM-dd"); Paragraph subTitle = new Paragraph("문서 소제목", subTitleFont); PdfPTable table = new PdfPTable(6); table.setWidthPercentage(100); table.setWidths(new int[] { 2, 2, 3, 2, 4, 4 }); Font headFont = new Font(bf, 11, Font.BOLD); table.addCell(setHeadCell("필드1", headFont)); table.addCell(setHeadCell("필드2", headFont)); table.addCell(setHeadCell("필드3", headFont)); table.addCell(setHeadCell("필드4", headFont)); table.addCell(setHeadCell("필드5", headFont)); table.addCell(setHeadCell("필드6", headFont)); DateFormat df = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss"); for (TableData tableData : tableDataList) { table.addCell(setChildCell(tableData.getField1() == null ? "-" : tableData.getField1())); table.addCell(setChildCell(tableData.getField2() == null ? "-" : tableData.getField2())); table.addCell(setChildCell(tableData.getField3() == null ? "-" : tableData.getField3())); table.addCell(setChildCell(tableData.getField4() == null ? "-" : tableData.getField4())); table.addCell(setChildCell(tableData.getField5() == null ? "-" : tableData.getField5())); table.addCell(setChildCell(tableData.getField6() == null ? "-" : tableData.getField6())); } PdfWriter.getInstance(document, outputStream); document.open(); document.add(title); document.add(new Paragraph("\\n")); document.add(subTitle); document.add(new Paragraph("\\n")); document.add(table); } catch (DocumentException | IOException ex) { log.error("PDF 파일 생성 실패"); } finally {

if(document != null) {

document.close();

}

} return new ByteArrayInputStream(outputStream.toByteArray());  } private PdfPCell setHeadCell(String content, Font font) { PdfPCell hcell = new PdfPCell(new Phrase(content, font)); hcell.setVerticalAlignment(Element.ALIGN_MIDDLE); hcell.setHorizontalAlignment(Element.ALIGN_CENTER); hcell.setBackgroundColor(new BaseColor(226, 226, 226)); hcell.setFixedHeight(25f); return hcell; } private PdfPCell setChildCell(String content) { PdfPCell cell = new PdfPCell(new Phrase(content)); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setFixedHeight(20f); return cell; }