티스토리 뷰

https://code.google.com/archive/p/java-html2image/ 에 게재되어있는 html2image library 를 사용한 예제 입니다. 해당 사이트에서 html2image jar 를 다운받아 프로젝트에 추가해주시기 바랍니다.


* HttpServletRequest req, HttpServletResponse res


// p.s HTML 에서 doctype ~ html, header, body 등이 들어 가면 이미지가 정상적으로 생성되지 않더라구요. 원인 아시는 분은 코멘트 부탁드립니다.!

String dispHtml = "<b>Hello World!</b> Please goto <a title=\"Goto Google\" href=\"http://www.google.com\">Google</a>";

String tempPath = "C:\\workspace\\";

String fileName = "hello-world.png";


ByteArrayOutputStream baos = null;

ByteArrayInputStream bais = null;

FileInputStream inputStream =  null;


try {

HtmlImageGenerator imageGenerator = new HtmlImageGenerator();

imageGenerator.loadHtml(dispHtml);

imageGenerator.saveAsImage(tempPath + fileName);


File imgFile = new File(tempPath + fileName);


if (imgFile.exists()) {


inputStream = new FileInputStream(imgFile);

baos = new ByteArrayOutputStream();

int len = 0;

byte[] buf = new byte[1024];

while ((len = inputStream.read(buf)) != -1) {

baos.write(buf, 0, len);

}

// 이미지 삭제를 위해 스트림 Close

inputStream.close();

res.setHeader("cache-control","no-cache");

res.setHeader("expires","0");

res.setHeader("pragma","no-cache");

res.setContentType("image/png");

String strClientBrower = req.getHeader( "User-Agent" );

if( strClientBrower.indexOf( "MSIE 5.5" ) > -1 || strClientBrower.indexOf( "MSIE 6.0" ) > -1 ) {

res.setHeader( "Content-Disposition", "filename=" + fileName);

} else {

res.setHeader( "Content-Disposition", "attachment;filename=" + fileName);

}

bais = new ByteArrayInputStream(baos.toByteArray());

IOUtils.copy(bais, res.getOutputStream());

File deleteImgFile = new File(tempPath + fileName); 

if (deleteImgFile.exists()) deleteImgFile.delete();

res.flushBuffer();

}

} catch (IOException ie) {

// Exception 은 용도에 따라!

} catch (Exception e) {

// Exception 은 용도에 따라!

}

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함