Insert Image using Apache POI and Aspose.Words

Aspose.Words - Insert Image

This example inserts a floating image from a file or URL at a specified position and size.

Java

// The path to the documents directory.
String dataDir = Utils.getDataDir(AsposeInsertImage.class);

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.insertImage(dataDir + "background.jpg");
builder.insertImage(dataDir + "background.jpg",
        RelativeHorizontalPosition.MARGIN,
        100,
        RelativeVerticalPosition.MARGIN,
        200,
        200,
        100,
        WrapType.SQUARE);

doc.save(dataDir + "Aspose_InsertImage.docx");

Apache POI HWPF XWPF - Insert Image

XWPFRun.addPicture is used to add an image to document.

Java

// The path to the documents directory.
String dataDir = Utils.getDataDir(ApacheInsertImage.class);

XWPFDocument doc = new XWPFDocument();
XWPFParagraph p = doc.createParagraph();

String imgFile = dataDir + "aspose.jpg";
XWPFRun r = p.createRun();

int format = XWPFDocument.PICTURE_TYPE_JPEG;
r.setText(imgFile);
r.addBreak();
r.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200)); // 200x200 pixels
r.addBreak(BreakType.PAGE);

FileOutputStream out = new FileOutputStream(dataDir + "Apache_ImagesInDoc.docx");
doc.write(out);
out.close();

Download Running Code

Download Sample Code