当我使用java将多个图像插入到单词中时无法附加word文档

时间:2016-09-20 12:10:08

标签: java apache-poi

我使用下面的代码拍摄屏幕快照并保存到word文件中。 此代码用作按钮.. 但是当我获得一个屏幕截图时它会替换现有的文件.. 我怎么能追加这个..pls建议 提前致谢。 :)

private void btnmanActionPerformed(java.awt.event.ActionEvent evt) {
    setVisible(false);

    if (btnman.getText().equals("Quick ScreenShot")) {

        try {
            Calendar now = Calendar.getInstance();
            Robot robot = new Robot();
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            Rectangle captureRect = new Rectangle(0, 0, 1430, 840);
            BufferedImage screenFullImage = robot.createScreenCapture(captureRect);

            ImageIO.write(screenFullImage, "JPG", new File(path.getText() + formatter.format(now.getTime()) + ".jpg"));
            img = path.getText() + formatter.format(now.getTime()) + ".jpg";
            System.out.println(img);
            setVisible(true);
        } catch (Exception es) {
            System.out.println("not done");
        }
    } else {

        try {
            Calendar now = Calendar.getInstance();
            Robot robot = new Robot();
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            Rectangle captureRect = new Rectangle(0, 0, 1400, 850);
            BufferedImage screenFullImage = robot.createScreenCapture(captureRect);

            ImageIO.write(screenFullImage, "JPG", new File("E:\\" + formatter.format(now.getTime()) + ".jpg"));
            img = "E:\\" + formatter.format(now.getTime()) + ".jpg";
            System.out.println(img);
            setVisible(true);
        } catch (Exception es) {
            System.out.println("not done");
        }


        XWPFDocument doc = new XWPFDocument();

        XWPFParagraph title = doc.createParagraph();
        XWPFRun run = title.createRun();
        run.setText(path.getText());
        run.setBold(true);
        title.setAlignment(ParagraphAlignment.CENTER);
        try {
            is = new FileInputStream(img);

            //run.addBreak();
            run.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, img, Units.toEMU(500), Units.toEMU(600));

            //is.close();
            System.out.println(img);
            System.out.print(path.getText());

            FileOutputStream fos = new FileOutputStream(path.getText());


            doc.write(fos);
            fos.close();
            System.out.println("Enterd successfully");

        } catch (Exception es) {
            System.err.println("es");
        }


    }
}

1 个答案:

答案 0 :(得分:1)

它覆盖了文件而不是附加,因为你每次都在创建一个新的(空的)XWPFDocument

XWPFDocument doc = new XWPFDocument();

并使用相同的(我假设的)路径保存它。

FileOutputStream fos = new FileOutputStream(path.getText());
doc.write(fos);

所以它最终取代了文件。

请尝试使用:

XWPFDocument doc = new XWPFDocument(new FileInputStream(path.getText()));

如果已存在,请打开上一个文档。