pdf.js와 JSP를 통한 웹 기반 PDF 미리보기 가이드
본 문서에서는 pdf.js 라이브러리를 JSP 환경과 결합하여 웹 페이지에서 PDF 파일을 표시하는 방법을 설명합니다.
1. 사전 준비물
- pdf.js 공식 웹사이트에서 라이브러리 다운로드: http://mozilla.github.io/pdf.js/
- 다운로드한 zip 파일(pdfjs-2.2.228-dist.zip)을 압축 해제하여 pdfjs 폴더 생성 (build 및 web 폴더 포함)
- 생성된 pdfjs 폴더를 프로젝트의 webapp 디렉토리로 이동 (예: G:\\workspace\\web-demo\\src\\main\\webapp)
2. pdf.js 기능 확인
프로젝트를 실행하고 브라우저에서 다음 URL로 접속하여 pdf.js의 기본 기능을 확인합니다:
http://localhost:8080/web-demo/pdfjs/web/viewer.html
pdf.js는 viewer.html 파일을 통해 PDF 렌더링을 구현합니다. 기본적으로 viewer.html과 동일한 디렉토리에 있는 compressed.tracemonkey-pldi-09.pdf 파일을 렌더링합니다.
기본 로드 파일 설정은 viewer.html과 동일한 디렉토리의 viewer.js 파일에 다음과 같이 정의되어 있습니다:
defaultUrl: {
value: 'compressed.tracemonkey-pldi-09.pdf',
kind: OptionKind.VIEWER
}
이 속성 값을 수정하면 다양한 PDF 파일을 미리볼 수 있으며, 한글 및 영문 PDF 파일 모두 정상적으로 표시됩니다.
3. 백엔드 데이터 연동을 통한 PDF 미리보기 구현
3.1. 필요한 라이브러리 의존성 추가
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!-- JSP taglib 의존성 -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
3.2. PDF 뷰 JSP 페이지 생성
viewer.html을 기반으로 PDF 파일을 렌더링하며, 파일은 백엔드에서 동적으로 로드됩니다. file 매개변수 뒤의 경로는 백엔드 메서드 매핑을 참조하며, 경로에 프로젝트 이름을 포함해야 합니다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h2>PDF 미리보기 페이지</h2>
<iframe
src="<c:url value="pdfjs/web/viewer.html" />?file=/web-demo/retrievePdfDocument" width="100%" height="800"></iframe>
</body>
</html>
3.3. 백엔드 컨트롤러 구현
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* PDF 온라인 미리보기 컨트롤러
*/
@Controller
public class DocumentPreviewController {
@RequestMapping("/showPdfViewer")
public String displayPDFViewer() {
return "pdfPreviewPage";
}
@RequestMapping("/retrievePdfDocument")
public void servePDFDocument(HttpServletResponse response) {
try {
File pdfFile = new File("D:/documents/sample.pdf");
FileInputStream fileInputStream = new FileInputStream(pdfFile);
response.setHeader("Content-Disposition", "attachment;fileName=sample.pdf");
response.setContentType("multipart/form-data");
OutputStream outputStream = response.getOutputStream();
IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
}
4. 실행 방법
프로젝트를 실행하고 브라우저에서 다음 URL로 접속하면 D 드라이브의 sample.pdf 파일이 미리보기 페이지에 표시됩니다:
http://localhost:8080/web-demo/showPdfViewer