everyone ! I am exporting word in poi word, I want to add a image in my header, but I am failure. There are many questions in stack overflow about this problem, but I could not find any answers. I using the poi-3.15.jar, below is my code. Can anybody give me some advice? Add text is successfully but image is failure.
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
paragraph.createRun().setText("hhhhh");
InputStream a = new FileInputStream("2.png");
paragraph.createRun().addPicture(a, Document.PICTURE_TYPE_PNG, "2.png", 20, 20);
saveDocument(document2, "D:\\4.docx");
There was a problem with inputting pictures in XWPF
header/footer until apache poi
version 3.15. See Add image into a word .docx document header using POI XWPF
But in apache poi
version 3.16 Beta 2 it seems to be fixed since the following code works using apache poi
version 3.16 Beta 2:
import java.io.*;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.util.Units;
public class CreateWordHeaderFooter {
public static void main(String[] args) throws Exception {
XWPFDocument doc= new XWPFDocument();
// the body content
XWPFParagraph paragraph = doc.createParagraph();
XWPFRun run=paragraph.createRun();
run.setText("The Body:");
// create header-footer
XWPFHeaderFooterPolicy headerFooterPolicy = doc.getHeaderFooterPolicy();
if (headerFooterPolicy == null) headerFooterPolicy = doc.createHeaderFooterPolicy();
// create header start
XWPFHeader header = headerFooterPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT);
paragraph = header.createParagraph();
paragraph.setAlignment(ParagraphAlignment.LEFT);
run = paragraph.createRun();
run.setText("The Header:");
InputStream a = new FileInputStream("file_icon.png");
paragraph.createRun().addPicture(a, Document.PICTURE_TYPE_PNG, "file_icon.png", Units.toEMU(20), Units.toEMU(20));
a.close();
// create footer start
XWPFFooter footer = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);
paragraph = footer.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
run = paragraph.createRun();
run.setText("The Footer: ");
doc.write(new FileOutputStream("CreateWordHeaderFooter.docx"));
doc.close();
}
}