Skip to content

Instantly share code, notes, and snippets.

@documentprocessing
Created October 15, 2024 13:38
Show Gist options
  • Save documentprocessing/fc3898d57e526f1e91d81831fc8db828 to your computer and use it in GitHub Desktop.
Save documentprocessing/fc3898d57e526f1e91d81831fc8db828 to your computer and use it in GitHub Desktop.
Insert image in DOCX using Apache POI XWPF API
// Create a new document
XWPFDocument document = new XWPFDocument();
// Create a new paragraph in the document
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("Here is an image below:");
// Insert an image
FileInputStream imageStream = new FileInputStream("path/to/your/image.jpg");
run.addBreak();
// To move to the next line
run.addPicture( imageStream, // Input stream of the image XWPFDocument.PICTURE_TYPE_JPEG, // Image type (JPEG in this case) "image.jpg", // Filename of the image Units.toEMU(200), // Image width in EMUs (English Metric Units) Units.toEMU(200) // Image height in EMUs );
imageStream.close();
// Save the document to a file
try (FileOutputStream fos = new FileOutputStream("doc_with_image.docx"))
{
document.write(fos);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment