关于使用POI向word中添加图片的问题

 更新时间:2022年12月23日 10:17:04   作者:acmbb  
这篇文章主要介绍了关于使用POI向word中添加图片的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

使用POI向word中添加图片

由于一次需要向word中添加多张图片,其中有图片存在重复,一开始使用的创建图片代码为:

xwpf.createPicture(xwpf.getAllPictures().size()-1, 80, 30,pargraph); 
public void createPicture(int id, int width, int height,XWPFParagraph paragraph) {  
        final int EMU = 9525;  
        width *= EMU;  
        height *= EMU;  
        String blipId = getAllPictures().get(id).getPackageRelationship().getId();  
        CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline();  

        String picXml = ""  
                + "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"  
                + "   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"  
                + "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"  
                + "         <pic:nvPicPr>" + "            <pic:cNvPr id=\""  
                + id  
                + "\" name=\"Generated\"/>"  
                + "            <pic:cNvPicPr/>"  
                + "         </pic:nvPicPr>"  
                + "         <pic:blipFill>"  
                + "            <a:blip r:embed=\""  
                + blipId  
                + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"  
                + "            <a:stretch>"  
                + "               <a:fillRect/>"  
                + "            </a:stretch>"  
                + "         </pic:blipFill>"  
                + "         <pic:spPr>"  
                + "            <a:xfrm>"  
                + "               <a:off x=\"0\" y=\"0\"/>"  
                + "               <a:ext cx=\""  
                + width  
                + "\" cy=\""  
                + height  
                + "\"/>"  
                + "            </a:xfrm>"  
                + "            <a:prstGeom prst=\"rect\">"  
                + "               <a:avLst/>"  
                + "            </a:prstGeom>"  
                + "         </pic:spPr>"  
                + "      </pic:pic>"  
                + "   </a:graphicData>" + "</a:graphic>";  

        // CTGraphicalObjectData graphicData =   
        inline.addNewGraphic().addNewGraphicData();  
        XmlToken xmlToken = null;  
        try {  
            xmlToken = XmlToken.Factory.parse(picXml);  
        } catch (XmlException xe) {  
            xe.printStackTrace();  
        }  
        inline.set(xmlToken);  
        inline.setDistT(0);  
        inline.setDistB(0);  
        inline.setDistL(0);  
        inline.setDistR(0);  

        CTPositiveSize2D extent = inline.addNewExtent();  
        extent.setCx(width);  
        extent.setCy(height);  

        CTNonVisualDrawingProps docPr = inline.addNewDocPr();  
        docPr.setId(id);  
        docPr.setName("Picture" + id);  
        docPr.setDescr("Generated");  
    }  

上述代码对于重复的图片流不会第二次生成id,因此会造成第二次出现的图片被后续图片覆盖的情况。

因此,修改为如下处理方式,解决了重复图片的问题:

String ind = xwpf.addPictureData(is, XWPFDocument.PICTURE_TYPE_GIF);
int id =  xwpf.getNextPicNameNumber(XWPFDocument.PICTURE_TYPE_GIF);
xwpf.createPicture(ind, id, 80, 30,pargraph); 
public void createPicture(String blipId, int id, int width, int height,XWPFParagraph paragraph) {  
        final int EMU = 9525;  
        width *= EMU;  
        height *= EMU;  
        //String blipId = getAllPictures().get(id).getPackageRelationship().getId();  
        CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline();  

        String picXml = "" +  
                "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" +  
                "   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +  
                "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +  
                "         <pic:nvPicPr>" +  
                "            <pic:cNvPr id=\"" + id + "\" name=\"Generated\"/>" +  
                "            <pic:cNvPicPr/>" +  
                "         </pic:nvPicPr>" +  
                "         <pic:blipFill>" +  
                "            <a:blip r:embed=\"" + blipId + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" +  
                "            <a:stretch>" +  
                "               <a:fillRect/>" +  
                "            </a:stretch>" +  
                "         </pic:blipFill>" +  
                "         <pic:spPr>" +  
                "            <a:xfrm>" +  
                "               <a:off x=\"0\" y=\"0\"/>" +  
                "               <a:ext cx=\"" + width + "\" cy=\"" + height + "\"/>" +  
                "            </a:xfrm>" +  
                "            <a:prstGeom prst=\"rect\">" +  
                "               <a:avLst/>" +  
                "            </a:prstGeom>" +  
                "         </pic:spPr>" +  
                "      </pic:pic>" +  
                "   </a:graphicData>" +  
                "</a:graphic>";  

        // CTGraphicalObjectData graphicData =   
        inline.addNewGraphic().addNewGraphicData();  
        XmlToken xmlToken = null;  
        try {  
            xmlToken = XmlToken.Factory.parse(picXml);  
        } catch (XmlException xe) {  
            xe.printStackTrace();  
        }  
        inline.set(xmlToken);  
        inline.setDistT(0);  
        inline.setDistB(0);  
        inline.setDistL(0);  
        inline.setDistR(0);  

        CTPositiveSize2D extent = inline.addNewExtent();  
        extent.setCx(width);  
        extent.setCy(height);  

        CTNonVisualDrawingProps docPr = inline.addNewDocPr();  
        docPr.setId(id);  
        docPr.setName("Picture" + id);  
        docPr.setDescr("Generated");  
    }  

使用POI给Word添加水印

Maven 引入依赖

       <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

Java 代码:

package com.daydayup.study001.watermark;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFHeader;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class WatermarkForWord {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        XWPFDocument doc= new XWPFDocument();

          // the body content
          XWPFParagraph paragraph = doc.createParagraph();
          XWPFRun run=paragraph.createRun();  
          run.setText("The Body:");

          // create header-footer
          XWPFHeaderFooterPolicy headerFooterPolicy = doc.getHeaderFooterPolicy();
          if (headerFooterPolicy == null) headerFooterPolicy = doc.createHeaderFooterPolicy();

          // create default Watermark - fill color black and not rotated
          headerFooterPolicy.createWatermark("Watermark");

          // get the default header
          // Note: createWatermark also sets FIRST and EVEN headers 
          // but this code does not updating those other headers
          XWPFHeader header = headerFooterPolicy.getHeader(XWPFHeaderFooterPolicy.DEFAULT);
          paragraph = header.getParagraphArray(0);

          // get com.microsoft.schemas.vml.CTShape where fill color and rotation is set
          org.apache.xmlbeans.XmlObject[] xmlobjects = paragraph.getCTP().getRArray(0).getPictArray(0).selectChildren(
            new javax.xml.namespace.QName("urn:schemas-microsoft-com:vml", "shape"));

          if (xmlobjects.length > 0) {
           com.microsoft.schemas.vml.CTShape ctshape = (com.microsoft.schemas.vml.CTShape)xmlobjects[0];
           // set fill color
           ctshape.setFillcolor("#d8d8d8");
           // set rotation
           ctshape.setStyle(ctshape.getStyle() + ";rotation:315");
           //System.out.println(ctshape);
          }

          doc.write(new FileOutputStream("CreateWordHeaderFooterWatermark.docx"));
          doc.close();

    }

}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • SpringBoot之如何指定配置文件启动

    SpringBoot之如何指定配置文件启动

    这篇文章主要介绍了SpringBoot之如何指定配置文件启动问题,具有很好的参考价值,希望对大家有所帮助。
    2023-04-04
  • springboot如何使用logback-spring配置日志格式,并分环境配置

    springboot如何使用logback-spring配置日志格式,并分环境配置

    这篇文章主要介绍了springboot如何使用logback-spring配置日志格式,并分环境配置的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • RabbitMQ消息队列中多路复用Channel信道详解

    RabbitMQ消息队列中多路复用Channel信道详解

    这篇文章主要介绍了RabbitMQ消息队列中多路复用Channel信道详解,消息Message是指在应用间传送的数据,消息可以非常简单,比如只包含文本字符串,也可以更复杂,可能包含嵌入对象,需要的朋友可以参考下
    2023-08-08
  • 详解Spring Boot应用的启动和停止(start启动)

    详解Spring Boot应用的启动和停止(start启动)

    这篇文章主要介绍了详解Spring Boot应用的启动和停止(start启动),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-12-12
  • 使用Spring的StopWatch实现代码性能监控的方法详解

    使用Spring的StopWatch实现代码性能监控的方法详解

    在开发过程中,偶尔还是需要分析代码的执行时间,Spring 框架提供了一个方便的工具类 StopWatch,本文将介绍 StopWatch 的基本用法,并通过示例演示如何在项目中使用 StopWatch 进行代码性能监控
    2023-12-12
  • 解决Idea查看源代码警告Library source does not match the bytecode for class XXX问题

    解决Idea查看源代码警告Library source does not mat

    在使用IDEA开发时,遇到第三方jar包中的源代码和字节码不一致的问题,会导致无法正确打断点进行调试,这通常是因为jar包更新后源代码没有同步更新造成的,解决方法是删除旧的jar包,通过Maven重新下载或手动下载最新的源代码包,确保IDE中的源码与字节码版本一致
    2024-10-10
  • springboot整合nacos,如何读取nacos配置文件

    springboot整合nacos,如何读取nacos配置文件

    这篇文章主要介绍了springboot整合nacos,如何读取nacos配置文件问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • SpringBoot时间格式化的方法小结

    SpringBoot时间格式化的方法小结

    SpringBoot中的时间格式化通常指的是将Java中的日期时间类型转换为指定格式的字符串,或者将字符串类型的时间解析为Java中的日期时间类型,本文小编将给大家详细总结了SpringBoot时间格式化的方法,刚兴趣的小伙伴跟着小编一起来看看吧
    2023-10-10
  • SpringCloud声明式Feign客户端调用工具使用

    SpringCloud声明式Feign客户端调用工具使用

    这篇文章主要为大家介绍了SpringCloud声明式Feign客户端调用工具使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-08-08
  • Maven插件之Dependency:analyze的使用

    Maven插件之Dependency:analyze的使用

    在软件开发中,合理管理项目依赖是保证构建稳定性的关键,Maven作为流行的项目管理工具,提供了Dependency插件来帮助开发者分析和优化项目依赖,通过执行dependency:analyze指令,可以辨识项目中使用的、未声明的、和未使用的依赖项
    2024-10-10

最新评论