Adding Images to a Word Document using Java
Java makes it possible to add images to Word documents using the addPicture() method of XWPFRun class provided by Apache POI package. Apache POI is a popular API developed and maintained by the Apache Software Foundation. It provides several classes and methods to perform different file operations on Microsoft office files using Java. In order to attach an image to a word document, the basic necessity is to import the following library of Apache.
- addPicture(): Helps in attaching the image to overall file. It is defined as follows:
run.addPicture(java.io.InputStream imageData,int imageType,java.lang.String imageFileName,int width,int height)
- imageData: The raw picture data
- imageType: The type of the picture, eg XWPFDocument.PICTURE_TYPE_JPEG
- imageFileName: Name of the image file
- width: width in EMUs
- height: height in EMUs
- Create a Blank document using XWPFDocument of Apache POI package.
- Create a paragraph using the createParagraph() method of XWPFParagraph object.
- Create FileOutputStream and FileInputStream of Word and Image respectively.
- Create XWPFRun object and add the picture using addPicture() method.
- Step 1: Creating a blank document
- Step 2: Creating a Paragraph
- Step 3: Creating a File output stream of word document at the required location
- Step 4: Creating a file input stream of the image by specifying its path
- Step 5: Retrieving the image file name and image type
- Step 6: Setting the width and height of the image in pixels
- Step 7: Adding the picture using the addPicture() method and writing into the document
- Step 8: Closing the connections
Sample input image: Before implementation