关于poi-jar包操作word,将图片定位在word右上角

之前做的在线office要插入二维码图片,但是插件提供的接口只能够将图片插入在光标位置,没办法定位。恐怕openoffice,pageoffice之类的也是如此。poi也没有定位接口,猜想本质原因是不是word从整体看没有行列这个概念。但是可以换一个概念,页眉的最右边不就是右上角了。

大体思路是创建word文档对象——创建XWPFHeaderFooterPolicy对象——创建页眉对象——在页眉上创建一个段落——把段落起始点设置在最右边——对这个段落做一个新的运行——插入图片

附加核心代码,用的poi官网最新的poi3.17jar包

System.out.println(flag+"aaaaaaaaaaaaaaaaaa"+imgFilePath);
		FileInputStream is = new FileInputStream(new File(flag));
		FileInputStream pic = new FileInputStream(new File(imgFilePath));
		
		XWPFDocument document = new XWPFDocument(is);
		System.out.println(document);
		XWPFHeaderFooterPolicy policy = document.getHeaderFooterPolicy();
		System.out.println("policy");
		XWPFHeader headerD = policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT);
		System.out.println("test3");
		headerD.createParagraph(); 
		//
		
		XWPFParagraph paragraph = headerD.getParagraphArray(0);
        paragraph.setAlignment(ParagraphAlignment.RIGHT);
        //paragraph.setBorderBottom(Borders.THICK);
        //
		 XWPFRun run=headerD.getParagraphArray(0).createRun();
         //run.setText("test");
         //FileInputStream pic = new FileInputStream(new File("E:\\test.png"));
		 
         run.addPicture(pic, XWPFDocument.PICTURE_TYPE_PNG, "test", Units.toEMU(50),Units.toEMU(50));
         
         FileOutputStream fos = new FileOutputStream(new File(flag));
		 document.write(fos);
		 fos.close();
		 document.close();
		 System.out.println("test");

网上有一些类似的标记位置插入数据都报了一个指针的错误,很明显,不创建段落,哪有第0段落获取。

后记,在之后做的word转pdf中出现了一个神奇的bug,插入图片转pdf就会报一个id越界的错误,但是不做任何改动重新保存word就bug消失,找到了几篇老外的文章,似乎是说poi本身的bug,就是一个从0开始,一个从1开始计数。需要重新保存word。没仔细看,如果需要转pdf打算把图片移到pdf做,不转就直接用了。

猜你喜欢

转载自blog.csdn.net/weixin_42727578/article/details/81744700