Created
October 15, 2024 13:38
-
-
Save documentprocessing/fc3898d57e526f1e91d81831fc8db828 to your computer and use it in GitHub Desktop.
Insert image in DOCX using Apache POI XWPF API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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