-->

Screenshot the whole web page in Java

2019-08-01 20:26发布

问题:

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