Java Poi Word 添加页眉文字和图片

代码

	public static void main( String[] args ) throws Exception {
		FileInputStream in = new FileInputStream( "C:/Users/Desktop/aaaab24.docx" );
		OPCPackage open = OPCPackage.open( in );
		XWPFDocument doc = new XWPFDocument( open );
		createHeader( doc, "a公司", "aaaa" );
	}
	
	public static void createHeader( XWPFDocument doc, String orgFullName, String logoFilePath ) throws Exception {
		CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
		XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy( doc, sectPr );
		XWPFHeader header = headerFooterPolicy.createHeader( headerFooterPolicy.DEFAULT );
		XWPFParagraph paragraph = header.createParagraph();
		paragraph.setAlignment( ParagraphAlignment.LEFT );
		paragraph.setBorderBottom( Borders.THICK );
		XWPFRun run = paragraph.createRun();
		if( StringUtils.isNotEmpty( logoFilePath ) ) {
			String imgFile = "C:\\Users\\Pictures\\GS\\1.jpg";
			File file = new File( imgFile );
			InputStream is = new FileInputStream( file );
			XWPFPicture picture = run.addPicture( is, XWPFDocument.PICTURE_TYPE_JPEG, imgFile, 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();
			is.close();
		}
		run.setText( "你好" );
		FileOutputStream fos = new FileOutputStream( "C:/Users/JYUAN/aaaab25.docx" );
		doc.write( fos );
		fos.close();
		
	}

pom文件



    4.0.0

    wordtest
    wordtest
    1.0-SNAPSHOT

    
        
            aliyun-repos
            Aliyun Repository
            http://maven.aliyun.com/nexus/content/groups/public
        
         

    
        
            commons-lang
            commons-lang
            2.4
        
        
            org.apache.commons
            commons-math3
            3.6.1
        
        
            org.apache.xmlbeans
            xmlbeans
            2.6.0
        
        
            commons-codec
            commons-codec
            1.10
        
        
            org.apache.commons
            commons-collections4
            4.0
        
        
            com.github.virtuald
            curvesapi
            1.04
        
        
            org.apache.poi
            poi-ooxml
            3.14
        
        
            org.apache.poi
            poi-scratchpad
            3.14
        
        
            org.apache.poi
            ooxml-schemas
            1.0
        
    

链接: 示例代码.

你可能感兴趣的:(Java,Poi,Word)