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");
答案 0 :(得分:1)
在XWPF
版本3.15之前,在apache poi
页眉/页脚中输入图片时出现问题。见Add image into a word .docx document header using POI XWPF
但在apache poi
版本3.16 Beta 2中似乎已修复,因为以下代码使用apache poi
版本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();
}
}
答案 1 :(得分:0)
这是使用XWPF运行方法添加图像的代码。
import org.apache.poi.xwpf.usermodel.XWPFRun;
String imgFile = "C:\\poi-3.9\\pictures\\Picture1.jpeg";
XWPFParagraph p = document.createParagraph();
XWPFRun r = p.createRun();
int format = XWPFDocument.PICTURE_TYPE_JPEG;
try {
r.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(400),
Units.toEMU(100)); // 200x200 pixels
} catch (Exception e){
System.out.println (e.getMessage());
}