Page 1 of 1

How to create docx document with Watermark?

PostPosted: Wed Dec 02, 2009 6:27 pm
by AnbuChezhian
Hi !
I need to create docx document containing watermark through docx4j.
Is it possible to do it?
If so ,can you give me some ideas ?.

Thanks in advance.

Re: How to create docx document with Watermark?

PostPosted: Thu Dec 03, 2009 11:15 am
by jason
Its pretty much the reverse of what was needed in your post from a couple of weeks ago about extracting an image from a watermark.

In other words, you need to add a header with a watermark (which is an image).

To add a header, you have to add the header part, and insert a reference to it in w:sectPr.

You want to add the header part to the main document part. So you do something like:

Code: Select all
Relationship relationship = wordprocessingMLPackage.getMainDocumentPart().addTargetPart(headerPart)


Same general idea for adding an image part to the header part.

Now, you have a couple of ways in which to set up the contents for the header part.

1. You can do it programmatically, or

2. You can use an existing XML representation of the part (created in Word for example, and saved as a file or a string).

Which works best for you will depend on your specific circumstances.

Attached below is some code I had lying around which you could adapt for your purposes.

cheers .. Jason

Code: Select all
import java.io.File;
import org.docx4j.dml.Inline;
import org.docx4j.openpackaging.exceptions.InvalidFormatException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.Part;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
import org.docx4j.openpackaging.parts.WordprocessingML.HeaderPart;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.relationships.Relationship;
import org.docx4j.wml.Hdr;
import org.docx4j.wml.HdrFtrRef;
import org.docx4j.wml.HeaderReference;
import org.docx4j.wml.ObjectFactory;
import org.docx4j.wml.SectPr;

public class HeaderFooter {

   private static ObjectFactory objectFactory = new ObjectFactory();

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

      WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
            .createPackage();
      MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart();
      
      Relationship relationship = createHeaderPart(wordMLPackage);
      
      createHeaderReference(wordMLPackage, relationship);

      wordMLPackage.save(new File(System.getProperty("user.dir"),
            "headerFooter.docx"));
//      mainDocumentPart.marshal(new FileOutputStream(new File(System
//            .getProperty("user.dir"), "headerfooter.xml")));

   }

   public static Relationship createHeaderPart(
         WordprocessingMLPackage wordprocessingMLPackage)
         throws Exception {
      
      HeaderPart headerPart = new HeaderPart();
      headerPart.setPackage(wordprocessingMLPackage);
      headerPart.setJaxbElement(getHdr(wordprocessingMLPackage, headerPart));
      return wordprocessingMLPackage.getMainDocumentPart()
            .addTargetPart(headerPart);

   }
   
   public static Hdr getHdr(WordprocessingMLPackage wordprocessingMLPackage,
         Part sourcePart) throws Exception {

      Hdr hdr = objectFactory.createHdr();
      hdr.getEGBlockLevelElts().add(
            newImage(wordprocessingMLPackage,
                  sourcePart, getBytes(), "filename", "alttext", 1, 2
                  )
      );
      return hdr;

   }
   
   public static byte[] getBytes() throws Exception {
      
      File file = new File("/home/dev/test.png" );
            
      java.io.InputStream is = new java.io.FileInputStream(file );
        long length = file.length();   
        // You cannot create an array using a long type.
        // It needs to be an int type.
        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 in
        if (offset < bytes.length) {
            System.out.println("Could not completely read file "+file.getName());
        }
        is.close();
       
        return bytes;            
      
   }

   
//   public static P getP() {
//      P headerP = objectFactory.createP();
//      R run1 = objectFactory.createR();
//      Text text = objectFactory.createText();
//      text.setValue("123head123");
//      run1.getRunContent().add(text);
//      headerP.getParagraphContent().add(run1);
//      return headerP;
//   }
   
   public static org.docx4j.wml.P newImage( WordprocessingMLPackage wordMLPackage,
         Part sourcePart,
         byte[] bytes,
         String filenameHint, String altText,
         int id1, int id2) throws Exception {
      
        BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage,
              sourcePart, bytes);
      
        Inline inline = imagePart.createImageInline( filenameHint, altText,
             id1, id2);
       
        // Now add the inline in w:p/w:r/w:drawing
      org.docx4j.wml.ObjectFactory factory = new org.docx4j.wml.ObjectFactory();
      org.docx4j.wml.P  p = factory.createP();
      org.docx4j.wml.R  run = factory.createR();      
      p.getParagraphContent().add(run);       
      org.docx4j.wml.Drawing drawing = factory.createDrawing();      
      run.getRunContent().add(drawing);      
      drawing.getAnchorOrInline().add(inline);
      
      return p;
      
   }   
   
   
   public static void createHeaderReference(
         WordprocessingMLPackage wordprocessingMLPackage,
         Relationship relationship )
         throws InvalidFormatException {

      SectPr sectPr = objectFactory.createSectPr();

      HeaderReference headerReference = objectFactory.createHeaderReference();
      headerReference.setId(relationship.getId());
      headerReference.setType(HdrFtrRef.DEFAULT);
      sectPr.getEGHdrFtrReferences().add(headerReference);// add header or
      // footer references

      wordprocessingMLPackage.getMainDocumentPart().addObject(sectPr);

   }
   
}