我想用ApachePOI在现有的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();
我错过了什么?
以下完整的示例适用于我使用当前的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
。