Insert Image into Word Example
This program demonstrates inserting an image into a Word file.
Problem Statement
Write a Java program that inserts an image into a Word .docx file using Apache POI.
Source Code
| 1 | import java.io.*; |
| 2 | import org.apache.poi.xwpf.usermodel.*; |
| 3 | import org.apache.poi.util.Units; |
| 4 | public class InsertImageWordExample { |
| 5 | public static void main(String[] args) { |
| 6 | System.out.println("Eduinq Insert Image Word Example"); |
| 7 | try(XWPFDocument doc=new XWPFDocument()) { |
| 8 | XWPFParagraph p=doc.createParagraph(); |
| 9 | XWPFRun run=p.createRun(); |
| 10 | try(FileInputStream fis=new FileInputStream("logo.png")) { |
| 11 | run.addPicture(fis, Document.PICTURE_TYPE_PNG, "logo.png", Units.toEMU(200), Units.toEMU(100)); |
| 12 | } |
| 13 | try(FileOutputStream fos=new FileOutputStream("image.docx")) { |
| 14 | doc.write(fos); |
| 15 | System.out.println("Eduinq Image Inserted Successfully"); |
| 16 | } |
| 17 | } catch(Exception e) { |
| 18 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 19 | } |
| 20 | } |
| 21 | } |
Program Output
Eduinq Insert Image Word Example Eduinq Image Inserted Successfully
Explanation
Uses addPicture() to embed images. - Converts dimensions using Units.toEMU(). - Exception handling ensures safe operations. - In enterprise systems, images are used for branding and visual reports. Conclusion: Shows inserting images into Word files.