-
input/outputstream 활용한 PDF 다운로드개발공부/JAVA 2023. 2. 24. 13:18
이전에 pdf에 워터마크 적용한 기능 테스트를 하다가 굳이 로컬에 저장하지 않고 서버에서 바로 적용해서 outputstream으로 뱉어내는게 가능하지 않을까 해서 진행해 보았다
사실 outputstream으로 응답을 리턴하는게 코드의 목적이지만 내부 테스트라 우선 결과물 확인을 위해 outputstream으로 만든걸 로컬에 저장해서 확인하는걸로 테스트를 대신하였다
#작업내용요약
- pdf 파일을 로컬에 저장하지 않고 url을 통해 inputstream으로 다운로드 후 서버에서 워터마크 적용하여 outputstream으로 리턴하기
- pdf url은 구글 드라이브에 올려놓은 것으로 임시 테스트 진행
- 워터마크 적용이 제대로 됐는지 확인하기 위해 결과물은 로컬에 저장하여 확인
#main
public static void main(String[] args) throws IOException, DocumentException { //pdf 테스트 url String pdfUrl = ""; if (StringUtils.isEmpty(pdfUrl)) { log.error("PDF URL is NULL !"); } //2) PDF 다운로드 InputStream inputStream = downloadPDF(pdfUrl); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (inputStream != null) { //다운로드 시간 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date now = new Date(); String downloadDate = sdf.format(now); String watermarkTxt = "PDF WATERMARK TEST !!! " + downloadDate; //3) 워터마크 생성 createWatermarkPdf(inputStream, outputStream, watermarkTxt); } else { log.error("PDF inputstream null ! > PDF 파일 없음"); } //TODO 결과 확인을 위해 로컬 경로에 저장 byte[] pdfBytes = outputStream.toByteArray(); FileOutputStream fileOutputStream = new FileOutputStream(new File("PDF 로컬 저장 경로")); fileOutputStream.write(pdfBytes); fileOutputStream.close(); }
#Inputstream을 통한 pdf 다운로드
public static InputStream downloadPDF(String url) { InputStream inputStream = null; try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); //통신상태 200 일 때 int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { inputStream = conn.getInputStream(); } else { log.error("downloadPDF > 통신 상태 오류 STATUS : {}", responseCode); } } catch (Exception e) { log.error("downloadPDF Error !"); e.printStackTrace(); } return inputStream; }
#워터마크 생성
public static void createWatermarkPdf(InputStream inputStream, OutputStream outputStream, String watermarkTxt) { try { //PDF 정보 가져오기 PdfReader reader = new PdfReader(inputStream); PdfStamper stamper = new PdfStamper(reader, outputStream); int pdfPages = reader.getNumberOfPages(); PdfContentByte watermark; //글꼴 설정 BaseFont baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, true); Font font = new Font(baseFont, 13, Font.NORMAL, BaseColor.BLACK); for (int i = 1; i <= pdfPages; i++) { watermark = stamper.getOverContent(i); watermark.saveState(); watermark.beginText(); watermark.setFontAndSize(font.getBaseFont(), 13); watermark.showTextAligned(PdfContentByte.ALIGN_CENTER, watermarkTxt, 300, 15, 0); //TODO size : 10~15 watermark.endText(); watermark.restoreState(); } stamper.close(); reader.close(); } catch (Exception e) { log.error("createWatermarkPdf Error !"); e.printStackTrace(); } }
#통합
import com.itextpdf.text.BaseColor; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Font; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; @Slf4j public class PdfWatermarkTest { public static void main(String[] args) throws IOException, DocumentException { //임의의 테스트 pdf url String pdfUrl = ""; if (StringUtils.isEmpty(pdfUrl)) { log.error("PDF URL is NULL !"); } //2) PDF 다운로드 InputStream inputStream = downloadPDF(pdfUrl); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (inputStream != null) { //다운로드 시간 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date now = new Date(); String downloadDate = sdf.format(now); String watermarkTxt = "PDF WATERMARK TEST !!! " + downloadDate; //3) 워터마크 생성 createWatermarkPdf(inputStream, outputStream, watermarkTxt); } else { log.error("PDF inputstream null ! > PDF 파일 없음"); } //TODO 결과 확인을 위해 로컬 경로에 저장 byte[] pdfBytes = outputStream.toByteArray(); FileOutputStream fileOutputStream = new FileOutputStream(new File("/Users/cheerupkm/watermarktest/watermarked.pdf")); fileOutputStream.write(pdfBytes); fileOutputStream.close(); } public static InputStream downloadPDF(String url) { InputStream inputStream = null; try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); //통신상태 200 일 때 int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { inputStream = conn.getInputStream(); } else { log.error("downloadMusicBookPDF > 통신 상태 오류 STATUS : {}", responseCode); } } catch (Exception e) { log.error("downloadMusicBookPDF Error !"); e.printStackTrace(); } return inputStream; } public static void createWatermarkPdf(InputStream inputStream, OutputStream outputStream, String watermarkTxt) { try { //PDF 정보 가져오기 PdfReader reader = new PdfReader(inputStream); PdfStamper stamper = new PdfStamper(reader, outputStream); int pdfPages = reader.getNumberOfPages(); PdfContentByte watermark; //글꼴 설정 BaseFont baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, true); Font font = new Font(baseFont, 13, Font.NORMAL, BaseColor.BLACK); for (int i = 1; i <= pdfPages; i++) { watermark = stamper.getOverContent(i); watermark.saveState(); watermark.beginText(); watermark.setFontAndSize(font.getBaseFont(), 13); watermark.showTextAligned(PdfContentByte.ALIGN_CENTER, watermarkTxt, 300, 15, 0); //TODO size : 10~15 watermark.endText(); watermark.restoreState(); } stamper.close(); reader.close(); } catch (Exception e) { log.error("createWatermarkPdf Error !"); e.printStackTrace(); } } }
#결과물
'개발공부 > JAVA' 카테고리의 다른 글
슬랙 토큰을 이용해서 알람봇 연동하기 (0) 2023.08.04 log4j / logback / log4j2 정리 (0) 2022.11.09 [TDD] 예제 테스트 작성 (0) 2022.10.04 [TDD] BDD 스타일의 mockito API (0) 2022.09.28 [TDD] Mock 객체 생성 및 구현 (0) 2022.09.26