반응형

일정 시간마다 특정 URL의 화면을 캡처하여 저장해달라는 요청이 있었다.

 

자바로 스케줄러를 구성하고 URL에 해당하는 정보를 가지고와서 JEditorPane 통해 이미지 컨텐츠를 구성하고 파일을 생성하는 예제이다. JEditorPane는 자바2에서부터 존재했던 클래스로 다양한 컨텐츠를 편집하기 위한 텍스트 컴퍼넌트이다.

해당 컴포넌트는 EditorKit 구현을 사용하여 동작하여 상속을 받은 클래스를 사용했습니다.

 

 

JAVA로 웹페이지 화면 저장하기

테스트용 화면 JSP페이지

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="/assets/css/test.css">
</head>
<body>
    <div>
        <p class="title">o 금일 할일</p>
        <p>- 프로젝트 검수</p>
        <p>- GIT 최신화</p>
    </div>
</body>
</html>

 

 

파일 생성처리

import java.awt.Container;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.JEditorPane;
import javax.swing.SwingUtilities;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;

public class App {
	public static void main(String[] args) {
		BufferedImage ire;
		// 저장할 서버 url
		String requestUrl = "http://localhost/test/view";

		// 저장될 위치 + 파일명
		String path = "E:/test/test.jpg";

		App app = new App();
		// 사이즈 크기 설정 및 생성
		ire = app.create(requestUrl, 200, 200);
		try {
			ImageIO.write(ire, "PNG", new File(path));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
	}

	static class Kit extends HTMLEditorKit {
		private static final long serialVersionUID = 2048542251827518481L;

		public Document createDefaultDocument() {
			HTMLDocument doc = (HTMLDocument) super.createDefaultDocument();
			doc.setTokenThreshold(Integer.MAX_VALUE);
			doc.setAsynchronousLoadPriority(-1);
			return doc;
		}
	}

	public BufferedImage create(String src, int width, int height) {
		BufferedImage image = null;
		JEditorPane pane = new JEditorPane();
		Kit kit = new Kit();
		pane.setEditorKit(kit);
		pane.setEditable(false);
		pane.setMargin(new Insets(0, 20, 0, 20));

		try {
			pane.setPage(new URL(src));
			image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics g = image.createGraphics();
			Container c = new Container();
			SwingUtilities.paintComponent(g, pane, c, 0, 0, width, height);
			g.dispose();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return image;
	}
}

 

 

동작결과

 

다만, 웹페이지의 100% 유동적인 이미지로 생성하는 방식은 찾지를 못했다. web page에서 특정 데이터에 사이즈를 담아두고 파싱부분에서 처리하면 가능할 수도 있겠지만, 응답을 해주지 않는 타사이트라면 해당 방식 적용도 어려울 것으로 보인다.

 

 

반응형