首页 > 解决方案 > Apache-poi:无法在 docx 标头中添加图像

问题描述

我想用 Apache POI 在现有的 docx 文档中创建一个标题(我已经尝试了 3.14 和 4.0.1 版本)。但是当我打开 docx 时,在标题中我得到了这个(“我们无法显示这个图像”):

在此处输入图像描述

我正在这样做:

document = new XWPFDocument(OPCPackage.open("C:\\users\\thomas\\withoutHeader.docx"));
CTSectPr sectPr1 = document.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document, sectPr1);

//Header content
CTP ctpHeader = CTP.Factory.newInstance();
CTR ctrHeader = ctpHeader.addNewR();
CTText ctHeader = ctrHeader.addNewT();
String headerText = "This is header";
ctHeader.setStringValue(headerText);
XWPFParagraph headerParagraph = new XWPFParagraph(ctpHeader, document);
XWPFParagraph[] parsHeader = new XWPFParagraph[1];
parsHeader[0] = headerParagraph;
policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, parsHeader);

//Header image
policy = new XWPFHeaderFooterPolicy(document);
XWPFHeader header = policy.getDefaultHeader();
System.out.println(header.getText());
XWPFParagraph paragraph = header.getParagraphArray(0);
if (paragraph == null) paragraph = header.createParagraph();
paragraph.setAlignment(ParagraphAlignment.CENTER);
XWPFRun r = paragraph.createRun();
FileInputStream in = new FileInputStream("C:\\Users\\thomas\\dev\\logo.png");
r.addPicture(in, Document.PICTURE_TYPE_JPEG, "C:\\Users\\thomas\\dev\\logo.png", Units.toEMU(100), Units.toEMU(50));
in.close();
FileOutputStream out = new FileOutputStream("C:\\users\\thomas\\withHeader.docx");
document.write(out);
document.close();
out.close();

我错过了什么?

在此处输入图像描述

标签: javaapache-poi

解决方案


以下完整示例适用于我使用 current apache poi 4.1.1

该示例打开了一个*.docx模板,该模板不应该有标题。然后它添加一个默认标题,其中包含文本和logo.png.

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(new FileInputStream("./Template.docx"));

  XWPFParagraph paragraph;
  XWPFRun run;

  // 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();
  run.setText("This is header "); 

  FileInputStream in = new FileInputStream("./logo.png");
  run.addPicture(in, Document.PICTURE_TYPE_PNG, "logo.png", Units.toEMU(100), Units.toEMU(50));
  in.close();  

  FileOutputStream out = new FileOutputStream("./CreateWordHeaderWithImage.docx");
  doc.write(out);
  doc.close();
  out.close();

 }
}

相同的代码apache poi 3.17也可以使用。


推荐阅读