How do i write/paste a captured image to a doc file?

后端 未结 1 1200
有刺的猬
有刺的猬 2021-01-28 21:36

I have a scenario where i need to capture image and write them to a word file one after the other. I have written the below code but doesn\'t seem to be working. Please help

相关标签:
1条回答
  • 2021-01-28 21:45

    Using ImageIO.write(screenShot, "JPG", baos); the image is there but it is a little bit small because the measurement unit is not pixel but EMU (English Metric Unit). There is a org.apache.poi.util.Units which can convert pixels to EMUs.

    The following does work for me:

    import java.io.*;
    
    import org.apache.poi.xwpf.usermodel.*;
    import org.apache.poi.util.Units;
    
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import javax.imageio.ImageIO;
    
    
    public class CreateWordPictureScreenshot {
    
     public static void main(String[] args) throws Exception {
    
      XWPFDocument document= new XWPFDocument();
    
      String resulttext = "The Screenshot:";
    
      Robot robot = new Robot();
    
      BufferedImage screenShot = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      //ImageIO.write(screenShot, "JPG", new File("NEW1.JPG"));
      ImageIO.write(screenShot, "JPG", baos);
      baos.flush();
      InputStream is = new ByteArrayInputStream(baos.toByteArray());
      baos.close();
      XWPFParagraph paragraph = document.createParagraph();
      XWPFRun run=paragraph.createRun();
      run.setText(resulttext);
      run.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, "new", Units.toEMU(72*6), Units.toEMU(72*6/16*9));
      is.close();
    
      document.write(new FileOutputStream("CreateWordPictureScreenshot.docx"));
    
      document.close();
    
     }
    }
    
    0 讨论(0)
提交回复
热议问题