简体   繁体   English

在Docx4j生成的Word文档的标题中显示图像

[英]Display Image in Header of Word Document Generated by Docx4j

am using Docx4j to generate a word document in a swing application.I want to add a picture to the header. 我正在使用Docx4j在swing应用程序中生成word文档。我想在页眉中添加图片。 The document is created successfully but the picture is not displayed. 文档创建成功,但未显示图片。 Below is the code snippets of the applications. 以下是应用程序的代码片段。 I am using the docx4j-nightly-20141016.jar file. 我正在使用docx4j-nightly-20141016.jar文件。

  import org.docx4j.wml.ObjectFactory;

  public class WordDoc {

      private WordprocessingMLPackage wordMLPackage;
      private ObjectFactory factory;
      private Hdr header;

       public WordDoc() {
      }

      public void createWordDoc() throws Docx4JException, IOException, Exception {

          wordMLPackage = WordprocessingMLPackage.createPackage();
          factory = Context.getWmlObjectFactory();

          Relationship relationship = createHeaderPart();
          createHeaderReference(relationship);

          wordMLPackage.getMainDocumentPart().addParagraphOfText("Hello Word!");

          File file = new File("src/resources/images/logo.jpg");
          byte[] bytes = convertImageToByteArray(file);
          addImageInline(bytes);

          wordMLPackage.save(new java.io.File("src/files/HelloWord14.docx"));

      }

      private Relationship createHeaderPart() throws InvalidFormatException {
          HeaderPart headerPart = new HeaderPart();
          headerPart.setPackage(wordMLPackage);

          headerPart.setJaxbElement(createHeader("Text"));

          return wordMLPackage.getMainDocumentPart().addTargetPart(headerPart);
      }

      private Hdr createHeader(String content) {
          header = factory.createHdr();
          P paragraph = factory.createP();
          R run = factory.createR();
          Text text = new Text();
          text.setValue(content);
          run.getContent().add(text);
          paragraph.getContent().add(run);
          header.getContent().add(paragraph);
          return header;
       }

      private void createHeaderReference(Relationship relationship) {
          List<SectionWrapper> sections
            = wordMLPackage.getDocumentModel().getSections();

           SectPr sectionProperties = sections.get(sections.size() - 1).getSectPr();
          // There is always a section wrapper, but it might not contain a sectPr
           if (sectionProperties == null) {
              sectionProperties = factory.createSectPr();
              wordMLPackage.getMainDocumentPart().addObject(sectionProperties);
              sections.get(0).setSectPr(sectionProperties);
           }

          HeaderReference headerReference = factory.createHeaderReference();
          headerReference.setId(relationship.getId());
          headerReference.setType(HdrFtrRef.DEFAULT);
          sectionProperties.getEGHdrFtrReferences().add(headerReference);
       }

       private byte[] convertImageToByteArray(File file)
              throws FileNotFoundException, IOException {
          InputStream is = new FileInputStream(file);
         long length = file.length();
         // You cannot create an array using a long, it needs to be an int.
           if (length > Integer.MAX_VALUE) {
              System.out.println("File too large!!");
           }
         byte[] bytes = new byte[(int) length];
          int offset = 0;
          int numRead = 0;
          while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length -  
                    offset)) >= 0) {
              offset += numRead;
          }
          // Ensure all the bytes have been read
          if (offset < bytes.length) {
              System.out.println("Could not completely read file "
                      + file.getName());
          }
          is.close();
           return bytes;
       }

      private void addImageInline(byte[] bytes) throws Exception {

          BinaryPartAbstractImage imagePart
                  = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);

            int docPrId = 1;
          int cNvPrId = 2;
           Inline inLine = imagePart.createImageInline("Filename hint",
                  "Alternative text", docPrId, cNvPrId, false);

           if (header != null) {

              addInlineImageToHeader(inLine);
          }
      }

       private void addInlineImageToHeader(Inline inline) {
       // Now add the in-line image to a paragraph
          ObjectFactory factory2 = new ObjectFactory();
             P paragraph2 = factory2.createP();
          R run = factory.createR();
          paragraph2.getContent().add(run);
          Drawing drawing = factory.createDrawing();
          run.getContent().add(drawing);
           drawing.getAnchorOrInline().add(inline);
          header.getContent().add(paragraph2);
      }

   }

the screen capture of the generated word document is displayed below 生成的word文档的屏幕截图显示在下面

在此处输入图片说明

Will be very glad to take any suggestions. 接受任何建议将非常高兴。

Instead of: 代替:

     BinaryPartAbstractImage imagePart
              = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);

you need to add the image part as a rel of your header part, so use: 您需要将图像部分添加为标题部分的相关部分,因此请使用:

public static BinaryPartAbstractImage createImagePart(
        OpcPackage opcPackage,
        Part sourcePart, byte[] bytes) throws Exception

passing it headerPart 传递给它headerPart

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

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