Below code insert images along with the relevant text in MS Word document.
package msWord;
import java.io.File;
import
java.io.FileInputStream;
import java.io.FileNotFoundException;
import
java.io.FileOutputStream;
import
org.apache.poi.util.Units;
import
org.apache.poi.xwpf.usermodel.UnderlinePatterns;
import
org.apache.poi.xwpf.usermodel.XWPFDocument;
import
org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFPicture;
import
org.apache.poi.xwpf.usermodel.XWPFRun;
public class
PasteImagesInToWord {
public static void main(String[] args) throws Exception {
String[]
imageName = new String[3];
imageName[0] = "D:\\NewFolder\\image0.jpg";
imageName[1] = "D:\\NewFolder\\image1.jpg";
imageName[2] = "D:\\NewFolder\\image2.jpg";
String
pathDOCX = "D:\\NewFolder\\ScreenshotJAVA.docx";
File
file = new File(pathDOCX);// ScreenshotJAVA.docx
file will be created.
FileOutputStream
outputFile = new
FileOutputStream(file);
// Create
document
XWPFDocument
docx = new XWPFDocument();
// Add
Paragraph
XWPFParagraph
pgraph = docx.createParagraph();
XWPFRun
run = pgraph.createRun();
run.setText("Below
are the Screenshots"); // run has lots of methods , you can explore.
run.setBold(true);
run.setFontSize(20);
run.setUnderline(UnderlinePatterns.THICK);// for
underline pattern :
//
run.setColor("FF0000");//RED
//
run.setColor("00FF00");//Green
run.setColor("0000FF");// Blue rgbstr
for (int i = 0; i < 3; i++) {
pgraph = docx.createParagraph();
run = pgraph.createRun();
run.setText("Image
Title_" + i);
run = pgraph.createRun();
// Below line
returns value XWPFPicture
/* XWPFPicture
pic = */run.addPicture(new FileInputStream(imageName[i]),
XWPFDocument.PICTURE_TYPE_JPEG,
imageName[i], Units.toEMU(150),
Units.toEMU(135));//image size
run = pgraph.createRun();
run.setText("Image
Title_" + i + " ****DONE****");
pgraph = docx.createParagraph();
run = pgraph.createRun();
run.setText(
"........................................................................................................................");
}
docx.write(new
FileOutputStream(pathDOCX));
outputFile.close();
System.out.println("MS Word
document with images created.");
}
}
Output:
MS Word document with images created.
No comments:
Post a Comment