관리 메뉴

ふたりで

html을 이미지로 변경시 특정 싸이즈로 나누어 저~장~ 본문

JAVA

html을 이미지로 변경시 특정 싸이즈로 나누어 저~장~

graykang 2020. 7. 14. 16:39
728x90
반응형
SMALL

html을 통짜로 한 개의 이미지로 저장하는 소스는 있는데 페이징 하듯 나누어 저장하는 건 

못 찾았다 하여 대략 이틀 동안 헤딩하며 알게 된 내용을 정리한다. 머 말이 페이징이지

그냥 상단부터 특정 높이만큼 잘라서 저장하는 거다. 그냥 PDF로 만들면 편하건만... 굳이 이미지

로 해야 할 때도 있더라 능;;;

 

나의 경우 컨트롤러 단에서 이미지로 만들 html페이지의 전체 높이를 특정 높이만큼 나눈 후

나눈 값만큼 for문을 돌면서 이미지를 잘랐다.

 

1. controller

	@RequestMapping(value = "/convertorPro", method=RequestMethod.GET)
	@ResponseBody
	public String HtmlToImage() {
		String url = "http://localhost:8080/htmlToJpg";
		String path ="";
		
		JEditorPane src = HtmlToImageUtil.createBase(url);//html을 JEditorPane로 변환하여 쌔벼옴
		
		int orWidth = 800;
		int orHeight = src.getPreferredSize().height;//읽어온 html 전체높이
        	int difHeight = 1200;
		//TODO 여기서 포문 돌리면 될듯
		long h = orHeight/difHeight;
		int rol = (int) Math.ceil(h)+1; //Math 가 않먹혀 그냥 여기서 1을 더해 버렸다.(저수학 못함;;)
		System,out,println("특정 높이 만큼 나눈 값: "+rol);
		
		try {
				for(int i=1; rol>=i; i++) {
					path = "\\TempImage\\"+i+"_test.jpg";
                    
                    //요기서 실재 이미지가 만들어 집니다.
					ire = HtmlToImageUtil.create(src, orWidth, difHeight*i, difHeight);
                    
                    //요기는 위에서 쌔벼온 이미지를 파일로 생성 하는놈 입니다.
					ImageIO.write(ire, "PNG", new File(path));
				}
			
			result = "성공";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = "이미지 생성 실패";
		}
		return result;		
	}

2. HtmlToImageUtil.java

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

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 abstract class HtmlToImageUtil{

	@SuppressWarnings("serial")
	
	static class Kit extends HTMLEditorKit{//참고: HTMLEditorKit는 html 3.2 까지만 지원된다.
	
		public Document createDefaultDocument() {
		
		HTMLDocument doc = (HTMLDocument) super.createDefaultDocument();
		
		doc.setTokenThreshold(Integer.MAX_VALUE);
		
		doc.setAsynchronousLoadPriority(-1);
		
		return doc;
		
		}
	
	}
	
	public static JEditorPane createBase(String src) {
    	
		JEditorPane pane = new JEditorPane();
		
		Kit kit = new Kit();
		
		pane.setEditorKit(kit);
		
		pane.setEditable(false);
		
		pane.setMargin(new Insets(20,20,20,20));
		
		pane.setContentType("text/html; charset=UTF-8");
		
		try {
			pane.setPage(new URL(src));
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return pane;
	}

	
	public static BufferedImage create(JEditorPane src, int width, int height, int difHeight){
	
	BufferedImage image = null;
	
	try{
	
		// HTML 내용을 콘솔창 출력.
		System.out.println(src.getText());
        
		image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);
        
		Graphics g = image.createGraphics();
		Container c = new Container();
        
        //요놈 가지고 구글링을 하며 별짖을 다해봐도 원하는 영역을 뽑아 낼수가 없었다;;;;;
		SwingUtilities.paintComponent(g, src, c, 0, 0, width, height);
		
		g.dispose();
		
		}catch (Exception e) {
		
		System.out.println(e);
		
		}
        
	//요기가 중요: 결국 getSubimage()라는게 있어서 아래와 같이 해주니 어익후 잘 나오네 ㅎㅎ
	return image.getSubimage(0, height-difHeight, width, difHeight);
	
	}
}

3. 결과: 요래 요래 기다란 html 페이지가 3장의 이미지로 분할되어 생성되었다.

728x90
반응형
LIST
Comments