简体   繁体   中英

Inserting an image to a particular position in a word document using docx4j

I want to add an image to particular position in my word document using docx4j. I don't want inline insertion. The code below performs adding the image inline with text. But I want floating insertion where I can explicitly give the location of where the image should be placed in the page. Please help me.

    public R addUserPic(P parag, WordprocessingMLPackage wordMLPackage)
                throws Exception {

            File file = new File("src/main/resources/PictureNew.png");
            byte[] bytes = convertImageToByteArray(file);   
            BinaryPartAbstractImage imagePart = BinaryPartAbstractImage
                    .createImagePart(wordMLPackage, bytes);
            int docPrId = 1;
            int cNvPrId = 2;

            Inline inline = imagePart.createImageInline("Filename hint",
                    "Alternative text", docPrId, cNvPrId, false);   

            ObjectFactory factory = new ObjectFactory();
            R run = factory.createR();
            org.docx4j.wml.Drawing drawing = factory.createDrawing();
            run.getContent().add(drawing);
            drawing.getAnchorOrInline().add(inline);

            return run;

        }

        private static byte[] convertImageToByteArray(File file)
                throws FileNotFoundException, IOException {
            InputStream is = new FileInputStream(file);
            long length = file.length();

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

            if (offset < bytes.length) {
                System.out.println("Could not completely read file "
                        + file.getName());
            }
            is.close();
            return bytes;


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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