/**
* 页眉插入图片
* @param file jpeg,jpg格式文件
* @param first 首页不同
* @param width 图片宽度
* @param height 图片高度
* @param left 图片距离左边
* @param top 图片距离右边
* @throws Exception
*/
public void insertPhotoToHeader( File file,boolean first,double width,double height,double left ,double top) throws Exception {
try(InputStream is = new FileInputStream(file)){
XWPFHeader header = null;
if(first){
header = document.createHeader(HeaderFooterType.FIRST);
}else{
header = document.createHeader(HeaderFooterType.DEFAULT);
}
XWPFParagraph paragraph = header.createParagraph();
paragraph.setAlignment(ParagraphAlignment.RIGHT);
paragraph.setBorderBottom(Borders.THICK);
XWPFRun run = paragraph.createRun();
XWPFPicture picture = run.addPicture( is, XWPFDocument.PICTURE_TYPE_JPEG, "a.jpg", Units.toEMU( 80 ), Units.toEMU( 45 ) );
String blipID = "";
for( XWPFPictureData picturedata : header.getAllPackagePictures() ) { // 这段必须有,不然打开的logo图片不显示
blipID = header.getRelationId( picturedata );
picture.getCTPicture().getBlipFill().getBlip().setEmbed( blipID );
}
run.addTab();
// 2. 获取到图片数据
CTDrawing drawing = run.getCTR().getDrawingArray(0);
CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic();
//拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性
CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "TEST1",
Units.toEMU(width), Units.toEMU(height),//图片大小
Units.toEMU(left), Units.toEMU(top), false);//相对当前段落位置 需要计算段落已有内容的左偏移
drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性
drawing.removeInline(0);//删除行内属性
}
}
/**
* @param ctGraphicalObject 图片数据
* @param deskFileName 图片描述
* @param width 宽
* @param height 高
* @param leftOffset 水平偏移 left
* @param topOffset 垂直偏移 top
* @param behind 文字上方,文字下方
* @return
* @throws Exception
*/
public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject,
String deskFileName, int width, int height,
int leftOffset, int topOffset, boolean behind) {
String anchorXML =
"<wp:anchor xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
+ "simplePos=\"0\" relativeHeight=\"0\" behindDoc=\"" + ((behind) ? 1 : 0) + "\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"
+ "<wp:simplePos x=\"0\" y=\"0\"/>"
+ "<wp:positionH relativeFrom=\"column\">"
+ "<wp:posOffset>" + leftOffset + "</wp:posOffset>"
+ "</wp:positionH>"
+ "<wp:positionV relativeFrom=\"paragraph\">"
+ "<wp:posOffset>" + topOffset + "</wp:posOffset>" +
"</wp:positionV>"
+ "<wp:extent cx=\"" + width + "\" cy=\"" + height + "\"/>"
+ "<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/>"
+ "<wp:wrapNone/>"
+ "<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\"" + deskFileName + "\"/><wp:cNvGraphicFramePr/>"
+ "</wp:anchor>";
CTDrawing drawing = null;
try {
drawing = CTDrawing.Factory.parse(anchorXML);
} catch (XmlException e) {
e.printStackTrace();
}
CTAnchor anchor = drawing.getAnchorArray(0);
anchor.setGraphic(ctGraphicalObject);
return anchor;
}
poi word设置页眉图片,控制首页不同
于 2021-12-23 11:45:43 首次发布