简体   繁体   中英

Java Code to save Web page as image

I have an application developed using struts2. One of my web page has a div in which it displays a world map created using Google map API. On click of a button I want to save this map as an image on the server location. I tried this using the ROBOT class but this is not working. My application supports IE8. Below is the code I wrote:

Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle rect = new Rectangle(screenDim);
Robot rob = new Robot();
BufferedImage img = rob.createScreenCapture(rect);
String FileName="D:\\SP_Maps\\Map.png";
ImageIO.write(img, "png", new File(FileName));

Basically I tried to take a screen shot of the page on click of a button and save it as an image. This works fine on my local host but, when I deploy this on my server and try to get the screen shot I just get a black page saved as png image.

While you are developing a web application you may use javascript if you are interested..

To get a screen shot and save it with any format you may use PhantomJS

PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast
and native support for various web standards: DOM handling, CSS selector, 
JSON, Canvas, and SVG.

Check those examples written with PhantomJS:

https://github.com/ariya/phantomjs/wiki/Examples

Also check this tutorial Taking website screenshots using PhantomJS

The tutorial is about taking a web shot and saving it as JPEG, PNG, PDF ... etc

Hope this helps you...

Can you explain your use case clearly ? If I understand correctly you have a web application which has a functionality to take a screen capture upon user action? Ideally, Java Robot utility should use to do automated testing of java applications. As per the doc

The primary purpose of Robot is to facilitate automated testing of Java platform implementations.

Maybe you can try using phantomjs. example

var page = require('webpage').create();
page.open('http://google.com', function () {
    page.render('google.png');
    phantom.exit();
});

https://github.com/ariya/phantomjs/wiki/Quick-Start

To perform user actions like button clicks, you can use casper.js http://casperjs.org/quickstart.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM