본문 바로가기

알아두면 좋은 IT 지식/Java

url에서 pdf를 읽어와서 파일로 저장하기

프로그램 개발 시 보여주고자 하는 내용을 pdf로 변환해서 url로 제공하는 경우가 있다.

크롬의 경우 브라우저에 pdf뷰어가 내장되어 있어서 url을 호출하면 자동으로 화면에 보여지지만, IE는 OS에 설치된 pdf뷰어를 통해서 보여준다. 만약 OS에 adobet reader같은 pdf뷰어가 설치되어 있지 않다면 알 수없는 파일 형식으로 .pdf를 다운로드 받는 링크가 생성된다.

 

 

chrome에서 호출 시

 

 

 

IE에서 호출 시

 

 

사용자 입장에서 OS나 브라우저 환경에 따라서 url호출 시 보여지는 방식이 다르기 때문에 불편할 수 있다.

이런 불편함을 해소하기 위해서 url호출 시 pdf를 파일로 자동으로 저장하는 java소스를 만들어 보자.


 

import java.io.IOException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpDownloader {

private static final int BUFFER_SIZE = 4096;
public static void downloadFile(String fileURL, String saveDir)
throws IOException {
    URL url = new URL(fileURL);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    int responseCode = httpConn.getResponseCode();

    if (responseCode == HttpURLConnection.HTTP_OK) {
        String fileName = "";
        String disposition = httpConn.getHeaderField("Content-Disposition");
        String contentType = httpConn.getContentType();
        int contentLength = httpConn.getContentLength();

        if (disposition != null) {
            int index = disposition.indexOf("filename=");
            if (index > 0) {
                fileName = disposition.substring(index + 9,
                disposition.length());
            }
        } else {
            fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
            fileURL.length());
        }

        System.out.println("Content-Type = " + contentType);
        System.out.println("Content-Disposition = " + disposition);
        System.out.println("Content-Length = " + contentLength);
        System.out.println("fileName = " + fileName);

        InputStream inputStream = httpConn.getInputStream();
        String saveFilePath = saveDir + File.separator + fileName;

        FileOutputStream outputStream = new FileOutputStream(saveFilePath);

        int bytesRead = -1;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        outputStream.close();
        inputStream.close();

        System.out.println("File downloaded");
        } else {
            System.out.println("No file to download. Server replied HTTP code: " + responseCode);
        }
        httpConn.disconnect();
    }
    public static void main(String[] args) {
        String fileURL = "http://www.test.com/pdf?";
        String saveDir = "D:/Download";
        try {
            downloadFile(fileURL, saveDir);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

 

소스가 복잡해 보이지만 파일 경로나 이름을 지정하고 Content 정보를 가져오는 부분을 제외하면 생각보다 간단하다.

 

URL클래스 객체 변수 url에 pdf파일을 가져올 주소을 넣고 HttpURLConnection 클래스의 getResponseCode() 함수를 사용해서 주소를 호출했을 때 응답 결과(pdf파일 포함)를 모두 가져온다.

응답 결과를 InputStream을 통해서 바이트단위로 버퍼에 담은 뒤 OutputStream을 통해서 pdf파일에 써서 저장한다.


위와 같이 처리할 경우 브라우저나 OS에 관계없이 url에 저장된 pdf를 자동으로 파일로 저장할 수 있다.