Page 1 of 1

Resize Image in Page Header

PostPosted: Thu Dec 11, 2014 11:43 am
by aduri
I have added an image as an anchor to the page header but the image is large and I wanted to reduce the size of the image to fit nicely in the header below are the code snippets.

Code: Select all
public class WordDoc {

    private ObjectFactory objectFactory = new ObjectFactory();
    private WordprocessingMLPackage wordMLPackage;
    private Relationship relationship;
    File file;
    byte[] bytes;
    private Integer HEADER_TOP_OFFSET = 0;

    public WordDoc() throws IOException {
        file = new File("src/resources/images/logo.jpg");
        bytes = convertImageToByteArray(file);
    }

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

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

        relationship = createHeaderPart(wordMLPackage);
        System.out.println("relationship id  " + relationship.getId());
        createHeaderReference(wordMLPackage, relationship);

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

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

    }

    public Relationship createHeaderPart(
            WordprocessingMLPackage wordprocessingMLPackage)
            throws Exception {

        HeaderPart headerPart = new HeaderPart();

        // Have to do this so that the next line can
        // add an image
        headerPart.setPackage(wordprocessingMLPackage);

        headerPart.setJaxbElement(getHdr(wordprocessingMLPackage, headerPart));
        return wordprocessingMLPackage.getMainDocumentPart()
                .addTargetPart(headerPart);

    }

    private Hdr getHdr(WordprocessingMLPackage wordprocessingMLPackage,
            Part sourcePart) throws Exception {

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

    }

    private void createHeaderReference(
            WordprocessingMLPackage wordprocessingMLPackage,
            Relationship relationship)
            throws InvalidFormatException {

        List<SectionWrapper> sections = wordprocessingMLPackage.getDocumentModel().getSections();

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

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

    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;
    }
   

    public 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, false);
       
         // convert the inline to an anchor (xml contents are essentially the same)
    String anchorXml = XmlUtils.marshaltoString(inline, true, false, Context.jc, Namespaces.NS_WORD12, "anchor",
        Inline.class);
   
     org.docx4j.dml.ObjectFactory dmlFactory = new org.docx4j.dml.ObjectFactory();
    org.docx4j.dml.wordprocessingDrawing.ObjectFactory wordDmlFactory = new org.docx4j.dml.wordprocessingDrawing.ObjectFactory();

     Anchor anchor = (Anchor) XmlUtils.unmarshalString(anchorXml, Context.jc, Anchor.class);
   
     anchor.setSimplePos(dmlFactory.createCTPoint2D());
    anchor.getSimplePos().setX(0L);
    anchor.getSimplePos().setY(0L);
    anchor.setSimplePosAttr(false);
    anchor.setPositionH(wordDmlFactory.createCTPosH());
    anchor.getPositionH().setAlign(STAlignH.CENTER);
    anchor.getPositionH().setRelativeFrom(STRelFromH.MARGIN);
    anchor.setPositionV(wordDmlFactory.createCTPosV());
    anchor.getPositionV().setPosOffset(HEADER_TOP_OFFSET);
    anchor.getPositionV().setRelativeFrom(STRelFromV.PAGE);
    anchor.setWrapNone(wordDmlFactory.createCTWrapNone());
     
   
     // Now add the inline in w:p/w:r/w:drawing
     ObjectFactory factory = new ObjectFactory();
     org.docx4j.wml.P p = factory.createP();
    org.docx4j.wml.Drawing drawing = factory.createDrawing();
    R run = factory.createR();
    p.getParagraphContent().add(run);
    run.getContent().add(drawing);
    drawing.getAnchorOrInline().add(anchor);
   
    return p;

    }


any suggestions.

Re: Resize Image in Page Header

PostPosted: Thu Dec 11, 2014 9:52 pm
by jason
BinaryPartAbstractImage contains 2 methods you can try:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
        /**
         * Create a <wp:inline> element suitable for this image,
         * which can be _embedded_ in w:p/w:r/w:drawing.
         * @param filenameHint Any text, for example the original filename
         * @param altText  Like HTML's alt text
         * @param id1   An id unique in the document
         * @param id2   Another id unique in the document
         * @param cx    Image width in twip
         * @param link  true if this is to be linked not embedded
         * None of these things seem to be exposed in Word 2007's
         * user interface, but Word won't open the document if
         * any of the attributes these go in (except @ desc) aren't present!
         * @throws Exception
         */

        public Inline createImageInline(String filenameHint, String altText,
                        int id1, int id2, long cx, boolean link)  throws Exception {
               
                ImageSize size = imageInfo.getSize();

                Dimension2D dPt = size.getDimensionPt();
                double imageWidthTwips = dPt.getWidth() * 20;
                log.debug("imageWidthTwips: " + imageWidthTwips);

                long cy;

                log.debug("Scaling image height to retain aspect ratio");
                cy = UnitsOfMeasurement.twipToEMU(dPt.getHeight() * 20 * cx / imageWidthTwips);

                // Now convert cx to EMU
                cx = UnitsOfMeasurement.twipToEMU(cx);
               

                log.debug("cx=" + cx + "; cy=" + cy);

                return createImageInline(filenameHint, altText, id1, id2, cx, cy, link);               
        }

        /**
         * Create a <wp:inline> element suitable for this image, which can be
         * linked or embedded in w:p/w:r/w:drawing, specifying height and width.  Note
         * that you'd ordinarily use one of the methods which don't require
         * you to specify height (cy).
         *
         * @param filenameHint
         *            Any text, for example the original filename
         * @param altText
         *            Like HTML's alt text
         * @param id1
         *            An id unique in the document
         * @param id2
         *            Another id unique in the document None of these things seem to
         *            be exposed in Word 2007's user interface, but Word won't open
         * the document if any of the attributes these go in (except @ desc) aren't
         *            present!
         * @param cx    Image width in EMU
         * @param cy    Image height in EMU
         * @param link  true if this is to be linked not embedded
         * @throws Exception
         */

        public Inline createImageInline(String filenameHint, String altText,
                        int id1, int id2, long cx, long cy, boolean link) throws Exception {

 
Parsed in 0.016 seconds, using GeSHi 1.0.8.4

Re: Resize Image in Page Header

PostPosted: Fri Dec 12, 2014 1:09 am
by aduri
thanks tried it and it worked just fine :D :D