简体   繁体   English

使用 POI XWPF 将图像添加到 word .docx 文档标题中

[英]Add image into a word .docx document header using POI XWPF

I've been trying to add .png image to .docx file header with Apache POI.我一直在尝试使用 Apache POI 将 .png 图像添加到 .docx 文件头。 I did´t find a method that help me.我没有找到对我有帮助的方法。 someone know how do it?有人知道怎么做吗? Whith this code I could add only text.有了这段代码,我只能添加文本。

XWPFDocument docc = new XWPFDocument(); 
CTP ctpHeader = CTP.Factory.newInstance(); 
CTR ctrHeader = ctpHeader.addNewR(); 
CTText ctHeader = ctrHeader.addNewT(); 
String headerText = "mi encabezado"; 
ctHeader.setStringValue(headerText); 

XWPFParagraph headerParagraph = new XWPFParagraph(ctpHeader, docc); XWPFParagraph[] parsHeader = new XWPFParagraph[1]; 
parsHeader[0] = headerParagraph; header.createHeader(XWPFHeaderFooterPolicy.DEFAULT, parsHeader);

Example for creating a Word document with header and footer and an image in the header:创建带有页眉和页脚以及页眉中的图像的Word文档的示例:

import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.util.Units;

import org.apache.poi.xwpf.usermodel.*;

import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTabStop;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTabJc;

import java.math.BigInteger;

public class CreateWordHeaderFooter {

 public static void main(String[] args) throws Exception {

  XWPFDocument doc= new XWPFDocument();

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

  paragraph = doc.createParagraph();
  run=paragraph.createRun();  
  run.setText("Lorem ipsum....");

  // create header start
  CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
  XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(doc, sectPr);

  XWPFHeader header = headerFooterPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT);

  paragraph = header.getParagraphArray(0);
  paragraph.setAlignment(ParagraphAlignment.LEFT);

  CTTabStop tabStop = paragraph.getCTP().getPPr().addNewTabs().addNewTab();
  tabStop.setVal(STTabJc.RIGHT);
  int twipsPerInch =  1440;
  tabStop.setPos(BigInteger.valueOf(6 * twipsPerInch));

  run = paragraph.createRun();  
  run.setText("The Header:");
  run.addTab();

  run = paragraph.createRun();  
  String imgFile="Koala.png";
  run.addPicture(new FileInputStream(imgFile), XWPFDocument.PICTURE_TYPE_PNG, imgFile, Units.toEMU(50), Units.toEMU(50));


  // create footer start
  XWPFFooter footer = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);

  paragraph = footer.getParagraphArray(0);
  paragraph.setAlignment(ParagraphAlignment.CENTER);

  run = paragraph.createRun();  
  run.setText("The Footer:");


  doc.write(new FileOutputStream("test.docx"));

 }
}

Edit Mar 29 2016: 2016 年 3 月 29 日编辑:

This had worked until apache poi 3.13.这一直工作到 apache poi 3.13。 Now with 3.14 it works not more.现在有了 3.14,它就不再起作用了。 Reason: POI will not save the blip reference for images in header paragraphs anymore.原因:POI 将不再在标题段落中保存图像的 blip 参考。

/word/header1.xml : /word/header1.xml

Code compiled and run with 3.13:使用 3.13 编译并运行的代码:

...
<pic:blipFill><a:blip r:embed="rId1"/>
...

Same code compiled and run with 3.14:使用 3.14 编译并运行相同的代码:

...
<pic:blipFill><a:blip r:embed=""/>
...

Edit Mar 31 2016: 2016 年 3 月 31 日编辑:

Found the problem.发现问题了。 Someone was the opinion the public final PackageRelationship getPackageRelationship() needs to be deprecated.有人认为public final PackageRelationship getPackageRelationship()需要弃用。 So in XWPFRun.java the code in public XWPFPicture addPicture(...) was changed所以在XWPFRun.javapublic XWPFPicture addPicture(...)的代码被改变了

from version 3.13:从 3.13 版开始:

...
            CTBlipFillProperties blipFill = pic.addNewBlipFill();
            CTBlip blip = blipFill.addNewBlip();
            blip.setEmbed(picData.getPackageRelationship().getId());
...

to version 3.14:到 3.14 版:

...
            CTBlipFillProperties blipFill = pic.addNewBlipFill();
            CTBlip blip = blipFill.addNewBlip();
            blip.setEmbed(parent.getDocument().getRelationId(picData));
...

But parent.getDocument() is the XWPFDocument always while the picData possible is related to the XWPFHeaderFooter .但是parent.getDocument()始终是XWPFDocumentpicData可能与XWPFHeaderFooter相关。

At the beginning of the public XWPFPicture addPicture(...) the programmers have already know this.public XWPFPicture addPicture(...) ,程序员已经知道这一点。

...
        if (parent.getPart() instanceof XWPFHeaderFooter) {
            XWPFHeaderFooter headerFooter = (XWPFHeaderFooter)parent.getPart();
            relationId = headerFooter.addPictureData(pictureData, pictureType);
            picData = (XWPFPictureData) headerFooter.getRelationById(relationId);
        } else {
            XWPFDocument doc = parent.getDocument();
            relationId = doc.addPictureData(pictureData, pictureType);
            picData = (XWPFPictureData) doc.getRelationById(relationId);
        }
...

So if the depreciation should really be enforced, this if..else must also be used while setting the blipID.因此,如果确实应该强制执行折旧,则在设置 blipID 时也必须使用if..else But why the depreciation at all?但为什么要贬值呢?

The apache poi 3.14 version lol apache poi 3.14 版本哈哈

import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.util.Units;

import org.apache.poi.xwpf.usermodel.*;

import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTabStop;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTabJc;

import java.math.BigInteger;

public class CreateWordHeaderFooter {

 public static void main(String[] args) throws Exception {

  XWPFDocument doc= new XWPFDocument();

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

  paragraph = doc.createParagraph();
  run=paragraph.createRun();  
  run.setText("Lorem ipsum....");

  // create header start
  CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
  XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(doc, sectPr);

  XWPFHeader header = headerFooterPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT);

  paragraph = header.getParagraphArray(0);
  paragraph.setAlignment(ParagraphAlignment.LEFT);

  CTTabStop tabStop = paragraph.getCTP().getPPr().addNewTabs().addNewTab();
  tabStop.setVal(STTabJc.RIGHT);
  int twipsPerInch =  1440;
  tabStop.setPos(BigInteger.valueOf(6 * twipsPerInch));

  run = paragraph.createRun();  
  run.setText("The Header:");
  run.addTab();

  run = paragraph.createRun();  
  String imgFile="Koala.png";
  XWPFPicture picture = run.addPicture(new FileInputStream(imgFile), XWPFDocument.PICTURE_TYPE_PNG, imgFile, Units.toEMU(50), Units.toEMU(50));
  System.out.println(picture); //XWPFPicture is added
  System.out.println(picture.getPictureData()); //but without access to XWPFPictureData (no blipID)

  String blipID = "";
  for(XWPFPictureData picturedata : header.getAllPackagePictures()) {
   blipID = header.getRelationId(picturedata);
   System.out.println(blipID); //the XWPFPictureData are already there
  }
  picture.getCTPicture().getBlipFill().getBlip().setEmbed(blipID); //now they have a blipID also
  System.out.println(picture.getPictureData());

  // create footer start
  XWPFFooter footer = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);

  paragraph = footer.getParagraphArray(0);
  paragraph.setAlignment(ParagraphAlignment.CENTER);

  run = paragraph.createRun();  
  run.setText("The Footer:");


  doc.write(new FileOutputStream("test.docx"));

 }
}

Edit Mar 28 2017: 2017 年 3 月 28 日编辑:

In apache poi version 3.16 Beta 2 this seems to be fixed since the following code works using apache poi version 3.16 Beta 2:apache poi 3.16 Beta 2 版中,这似乎是固定的,因为以下代码使用apache poi 3.16 Beta 2 版工作:

import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.util.Units;

import org.apache.poi.xwpf.usermodel.*;

import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTabStop;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTabJc;

import java.math.BigInteger;

public class CreateWordHeaderFooter2 {

 public static void main(String[] args) throws Exception {

  XWPFDocument doc= new XWPFDocument();

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

  paragraph = doc.createParagraph();
  run=paragraph.createRun();  
  run.setText("Lorem ipsum....");

  // create header start
  CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
  XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(doc, sectPr);

  XWPFHeader header = headerFooterPolicy.createHeader(XWPFHeaderFooterPolicy.DEFAULT);

  paragraph = header.createParagraph();
  paragraph.setAlignment(ParagraphAlignment.LEFT);

  CTTabStop tabStop = paragraph.getCTP().getPPr().addNewTabs().addNewTab();
  tabStop.setVal(STTabJc.RIGHT);
  int twipsPerInch =  1440;
  tabStop.setPos(BigInteger.valueOf(6 * twipsPerInch));

  run = paragraph.createRun();  
  run.setText("The Header:");
  run.addTab();

  run = paragraph.createRun();  
  String imgFile="Koala.png";
  run.addPicture(new FileInputStream(imgFile), XWPFDocument.PICTURE_TYPE_PNG, imgFile, Units.toEMU(50), Units.toEMU(50));


  // create footer start
  XWPFFooter footer = headerFooterPolicy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);

  paragraph = footer.createParagraph();
  paragraph.setAlignment(ParagraphAlignment.CENTER);

  run = paragraph.createRun();  
  run.setText("The Footer:");


  doc.write(new FileOutputStream("test.docx"));

 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM