我正在Word文档的标题中添加图片。它显示了图像的框架,并显示“当前无法显示图像”。如果我在标题中添加文本,则显示该文本,如果在文档正文中添加图像,则它也显示该图像。获取图像并在标题上显示文本,也没有图像。
我的支票用完了,有人可以提出建议吗?
谢谢!
public static void createHeaderAndFotter(XWPFDocument document) throws IOException, BadElementException, InvalidFormatException {
XWPFHeaderFooterPolicy headerFooterPolicy = document.getHeaderFooterPolicy();
if (headerFooterPolicy == null) headerFooterPolicy = document.createHeaderFooterPolicy();
File image = new ClassPathResource("/static/images/NIAB_Header.bmp").getFile();
BufferedImage bimg1 = ImageIO.read(image);
int width = bimg1.getWidth();
int height = bimg1.getHeight();
String imageName= image.getName();
XWPFHeader header = headerFooterPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT);
XWPFParagraph paragraph = header.createParagraph();
// XWPFParagraph paragraph = document.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
XWPFRun run = paragraph.createRun();
run.addPicture(new FileInputStream(image), XWPFDocument.PICTURE_TYPE_PNG, imageName, Units.toEMU(width), Units.toEMU(height));
run.setText("HEADER");
}
如果我删除此行上的注释并在前面添加注释,那么它将添加图像
XWPFParagraph paragraph = document.createParagraph();
答案 0 :(得分:2)
我认为这是否奏效很大程度上取决于所使用的apache poi
版本。在以前的apache poi
版本中,页眉/页脚中的图片存在多个问题。
以下是使用apache poi 4.0.1
的最起码的工作代码。建议始终使用最新的稳定版本。
代码:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.wp.usermodel.HeaderFooterType;
import org.apache.poi.util.Units;
public class CreateWordHeaderWithImage {
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
XWPFHeader header = doc.createHeader(HeaderFooterType.DEFAULT);
// header's first paragraph
paragraph = header.getParagraphArray(0);
if (paragraph == null) paragraph = header.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
run = paragraph.createRun();
FileInputStream in = new FileInputStream("samplePict.jpeg");
run.addPicture(in, Document.PICTURE_TYPE_JPEG, "samplePict.jpeg", Units.toEMU(100), Units.toEMU(50));
in.close();
run.setText("HEADER");
FileOutputStream out = new FileOutputStream("CreateWordHeaderWithImage.docx");
doc.write(out);
doc.close();
out.close();
}
}
结果: