gpt4 book ai didi

Java - 将图像转换为 Word 文档

转载 作者:太空宇宙 更新时间:2023-11-04 10:58:34 25 4
gpt4 key购买 nike

屏幕截图正在创建,word 文档也有一定的大小,但当我打开它时它是空的......任何人都可以建议,附加代码

我需要将 Word 文档中的所有屏幕截图放在一起。

打开 Word 文档时出现一些“启用内容”错误,我已经信任发布者了...现在该错误(不是错误)不会出现,但 WORD 文档是空的,大小合理。

import java.awt.AWTException;
import java.awt.HeadlessException;
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.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import org.apache.commons.io.IOUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class TakeScreenshots {

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

// for (int counter = 0; counter <= 5; counter++) {
captureScreenShot();
// captureScreenShot(out, docx);
// }
} catch (Exception e) {
e.printStackTrace();
}

}

public static void captureScreenShot() throws Exception {

XWPFDocument docx = new XWPFDocument();
String screenshot_name = System.currentTimeMillis() + ".png";

BufferedImage image = new Robot()
.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "png", new File("d:/xyz/" + screenshot_name));

InputStream pic = new FileInputStream("d:/xyz/" + screenshot_name);
docx.addPictureData(pic, Document.PICTURE_TYPE_PNG);
FileOutputStream out = new FileOutputStream("d:/xyz/doc1.docx");
docx.write(out);
pic.close();
out.flush();
out.close();

TimeUnit.SECONDS.sleep(1);
}

}

最佳答案

修改您的 captureScreenShot 方法,如下所示,它将起作用。

public static void captureScreenShot() throws Exception {
XWPFDocument docx = new XWPFDocument();
XWPFParagraph paragraph = docx.createParagraph();
XWPFRun run = paragraph.createRun();
String screenshot_name = System.currentTimeMillis() + ".png";
BufferedImage image = new Robot()
.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "png", new File("d:/xyz/" + screenshot_name));
InputStream pic = new FileInputStream("d:/xyz/" + screenshot_name);
//docx.addPictureData(pic, Document.PICTURE_TYPE_PNG);
run.addBreak();
run.addPicture(pic, XWPFDocument.PICTURE_TYPE_JPEG, screenshot_name, Units.toEMU(350), Units.toEMU(350));
pic.close();
FileOutputStream out = new FileOutputStream("d:/xyz/doc1.docx");
docx.write(out);
out.flush();
out.close();

TimeUnit.SECONDS.sleep(1);
}

关于Java - 将图像转换为 Word 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47139243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com