Docx4j在页眉 同时加入图片和文字有两种实现方式,一种是用HTML写一个模板,通过模板一次加入,另一种是通过docx4j直接操作
一、Html方式 上代码
public class Docx4JSample {
public static void main(String []args) throws Exception{
Docx4JSample docx4jSample = new Docx4JSample();
WordprocessingMLPackage worMLPackage = docx4jSample.createWordpreocessMLPackage();
MainDocumentPart mpart = worMLPackage.getMainDocumentPart();
ObjectFactory factory = Context.getWmlObjectFactory();
Relationship relationship1 = docx4jSample.createHeaderPart(worMLPackage, mpart,
factory, true, "3");
docx4jSample.createHeaderReference(worMLPackage, mpart, factory, relationship1);
docx4jSample.saveWordPackage(worMLPackage, new File("./testpaper.docx"));
}
public void createHeaderReference(WordprocessingMLPackage wordprocessingMLPackage,MainDocumentPart t,
ObjectFactory factory, Relationship relationship) throws Exception{
List
SectPr sectPr =sections.get(sections.size()-1).getSectPr();
if (sectPr == null ){
sectPr = factory.createSectPr();
t.addObject(sectPr);
sections.get(sections.size()-1).setSectPr(sectPr);
}
HeaderReference headerReference = factory.createHeaderReference();
headerReference.setId(relationship.getId()); //这里关联RelationShip
headerReference.setType(HdrFtrRef.DEFAULT);
sectPr.getEGHdrFtrReferences().add(headerReference);
}
//创建页眉
public Relationship createHeaderPart(WordprocessingMLPackage wordprocessingMLPackage,
MainDocumentPart mpartDocumentPart , ObjectFactory factory , boolean isUnderLine ,
String underLineSize) throws Exception{
HeaderPart headerPart = new HeaderPart();
Relationship relationship = mpartDocumentPart.addTargetPart(headerPart);
String headerString="
+ "static/superman/img/logo/bd_logo1_31bdc765.png\"> | "
+ "页眉右边的文字 |
---|
headerPart.addAltChunk(AltChunkType.Xhtml, headerString.getBytes());
return relationship;
}
public void saveWordPackage(WordprocessingMLPackage wordPackage , File file) throws Exception{
wordPackage.save(file);
}
结果如下:
另一种方式 见下一篇文章