Screenshot the whole web page in Java

若如初见. 提交于 2019-12-11 10:28:18

问题


I'm trying to figure out of how to get a screenshot the whole web page. I'm working on a dashboard using 20 plus dc.js charts, cross filters all of them, and i'm using JSP. Client want to have a button where a user clicks and it will screen shot the whole web page. I'm running it through java because we have to use IE11 as our standard and all other js libraries such as HTML2canvas.js didnt work (it doesnt display the dc.js charts) though it sort of works on Chrome but we have to use IE11 (any suggestions would help).

So far when I click on a button, it will run a main method in JAVA to do a screen shot. So far I'm using java.awt.Robot but I researched and it says it only screen shot base on the screen of a primary monitor. I'm trying to have a screen shot of my web page. Is there a way to do that? if so how? Here is my Java code below. It screenshot base on the monitor...

 package com.customer_inquiry;

import java.net.URL;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;

    public class screenshotAction {

        public static void main(String[] args) throws Exception {

    String outFileName = args[0];
    if (!outFileName.toLowerCase().endsWith(".png")) {
                System.err.println("Error: output file name must " + "end with \".png\".");
                System.exit(1);
            }
            // determine current screen size
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            Dimension screenSize = toolkit.getScreenSize();
            Rectangle screenRect = new Rectangle(screenSize);
            // create screen shot
            Robot robot = new Robot();


            BufferedImage image = robot.createScreenCapture(screenRect);
            // save captured image to PNG file
            ImageIO.write(image, "png", new File(outFileName));
            // give feedback
            System.out.println("Saved screen shot (" + image.getWidth() + " x " + image.getHeight() + " pixels) to file \""
                    + outFileName + "\".");
            // use System.exit if the program hangs after writing the file;
            // that's an old bug which got fixed only recently
            // System.exit(0);
        }
    }

回答1:


There is html2canvas that might suit your needs: https://html2canvas.hertzen.com/

Apart from that, if you want to do it yourself, what comes to mind is to:

  • first create an svg
  • an a foreignObject tag
  • serialize the entire html using XMLSerializer and then set it to foreignObject via innerHTML. Alternatively use cloneNode.
  • draw the svg on the canvas
  • download the canvas


来源:https://stackoverflow.com/questions/50048981/screenshot-the-whole-web-page-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!