How to take screenshots and paste it in a word fil

2020-08-09 07:19发布

问题:

I am able to take screenshot by ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

In my application I have to take screenshot for every page so I want to save the multiple screenshot into a single .doc file one by one. Is there any API?

Any Idea? Please Help...

回答1:

Easiest way - take screenshot, put it in PNG/JPEG file, read it, add it in MS-Word, delete the file, simple. here's a ready to use code for you.... BINGO...!!

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class TakeScreenshots {

    public static void main(String[] args) {
        try {

            XWPFDocument docx = new XWPFDocument();
            XWPFRun run = docx.createParagraph().createRun();
            FileOutputStream out = new FileOutputStream("d:/xyz/doc1.docx");

            for (int counter = 1; counter <= 5; counter++) {
                captureScreenShot(docx, run, out);
                TimeUnit.SECONDS.sleep(1);
            }

            docx.write(out);
            out.flush();
            out.close();
            docx.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void captureScreenShot(XWPFDocument docx, XWPFRun run, FileOutputStream out) throws Exception {

        String screenshot_name = System.currentTimeMillis() + ".png";
        BufferedImage image = new Robot()
                .createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        File file = new File("d:/xyz/" + screenshot_name);
        ImageIO.write(image, "png", file);
        InputStream pic = new FileInputStream("d:/xyz/" + screenshot_name);
        run.addBreak();
        run.addPicture(pic, XWPFDocument.PICTURE_TYPE_PNG, screenshot_name, Units.toEMU(350), Units.toEMU(350));
        pic.close();
        file.delete();
    }

}


回答2:

Selenium Webdriver do not provide any feature to add snapshot in word file. For this you need to use third party libraries.

Refer below:-

how to insert image into word document using java

How can I add an Image to MSWord document using Java

You can also add your image file in TestNG output file using reporter

Refer below :-

http://www.automationtesting.co.in/2010/07/testng-take-screenshot-of-failed-test.html

Hope it will help you :)