Add an Image in a Specific Position in the Document (.Docx)

Add an image in a specific position in the document (.docx)?

Quoting the python-docx documentation:

The Document.add_picture() method adds a specified picture to the end of the document in a paragraph of its own. However, by digging a little deeper into the API you can place text on either side of the picture in its paragraph, or both.

When we "dig a little deeper", we discover the Run.add_picture() API.

Here is an example of its use:

from docx import Document
from docx.shared import Inches

document = Document()

p = document.add_paragraph()
r = p.add_run()
r.add_text('Good Morning every body,This is my ')
r.add_picture('/tmp/foo.jpg')
r.add_text(' do you like it?')

document.save('demo.docx')

How to insert an Image in a specific position in a word document with python?

Looking at the implementation of Document.add_picture at the docs of python-docx here gives

def add_picture(self, image_path_or_stream, width=None, height=None):
run = self.add_paragraph().add_run()
return run.add_picture(image_path_or_stream, width, height)

Using this information, you can use

document.add_paragraph('Barcode : ')
.add_run()
.add_picture(df['Name'][i]+df['Vorname '] [i]+'.png',width=Inches(2.0))

to add the picture to the same paragraph. I haven't tested it, but I hope this does the trick.

Add a set of images after a specific text in a word file with Python docx

If the number is in a paragraph by itself, you can add a picture in a run following the text (but still in the same paragraph) like this:

if tag in paragraph.text:
run = paragraph.add_run()
run.add_picture("image.png", ...)

The details of the Run.add_picture() call are in the API documentation here:

https://python-docx.readthedocs.io/en/latest/api/text.html#run-objects

Set image position and tilt into a word .docx document using POI XWPF

I solved it myself. Basically word document is a kind of zip file. If we rename the word file extension as .zip and open the document.xml file, we could see how the image is actually positioned using xml format. Here are the steps I took.

  1. Create a word document with the required image and set image position manually ()
  2. Rename the file extension as .zip from .docx , extract the zip file.
  3. Navigate and open document.xml which is present in the word folder of the extracted zip.
  4. Search of the image name (here my image name is picture4)
  5. Get the Horizontal and Vertical offset , extent cx and cy, relative height and other parameters position from the xml, I have marked them in bold in the xml snippet below.
<w:body>
<w:p>
<w:bookmarkStart w:id="0" w:name="_GoBack"/>
<w:bookmarkEnd w:id="0"/>
<w:r>
<w:drawing>
<wp:anchor distT="0" distB="0" distL="**114300**" distR="**114300**" simplePos="0" relativeHeight="**251658240**" behindDoc="1" locked="0" layoutInCell="1" allowOverlap="1">
<wp:simplePos x="0" y="0"/>
<wp:positionH relativeFrom="column">
<wp:posOffset>**-2256790**</wp:posOffset>
</wp:positionH>
<wp:positionV relativeFrom="paragraph">
<wp:posOffset>**-1823085**</wp:posOffset>
</wp:positionV>
<wp:extent cx=**"3448050"** cy=**"3619500"**/>
<wp:effectExtent l="0" t="0" r="0" b="0"/>
<wp:wrapNone/>
<wp:docPr id="4" name="Drawing 0" descr="**Picture4**"/>
<wp:cNvGraphicFramePr>

  1. Set the same in anchor xml

    String anchorXML = "<wp:anchor xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" " +"distT=\"0\" distB=\"0\" distL=\"114300\" distR=\"114300\" simplePos=\"0\" relativeHeight=\"251658240\" behindDoc=\"1\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"

       +"<wp:simplePos x=\"0\" y=\"0\"/>"

    +"<wp:positionH relativeFrom=\"column\"><wp:posOffset>-1800000</wp:posOffset></wp:positionH>"
    +"<wp:positionV relativeFrom=\"paragraph\"><wp:posOffset>-1800000</wp:posOffset></wp:positionV>"

    + "<wp:extent cx=\"3448050\" cy=\"3619500\"/>"
    +"<wp:effectExtent l=\"0\" t=\"0\" r=\"6350\" b=\"6350\"/>"
    +" <wp:simplePos x=\"0\" y=\"0\"/><wp:positionH relativeFrom=\"column\"><wp:posOffset>-1800000</wp:posOffset></wp:positionH><wp:positionV relativeFrom=\"paragraph\"><wp:posOffset>-1800000</wp:posOffset></wp:positionV><wp:extent cx=\"3448050\" cy=\"3619500\"/><wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/><wp:wrapNone/> "
    +"<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\""+drawingDescr+"\"/><wp:cNvGraphicFramePr/>"
    +"</wp:anchor>";
  2. Here is sample code to add image and position, we can parameterize the method to set offset and other xml parameters.

     import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
    import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
    import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
    public class addImage extends XWPFDocument {
    public static void main(String[] args) throws IOException {`
    // Create a document file
    CustomXWPFDocument document = new CustomXWPFDocument();
    XWPFParagraph paragraphFourteenx = document.createParagraph();
    XWPFRun paragraphFourteenRunx = paragraphFourteenx.createRun();

    // add picture four
    //String imgFile = "C:\\pictures\\Picture4.jpeg";
    XWPFParagraph p3 = document.createParagraph();
    XWPFRun r3 = p3.createRun();
    imgFile = "C:\\Picture4.jpeg";
    try {
    r3.addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(250), Units.toEMU(250)); // 200x200 pixels
    }catch (Exception e){
    System.out.println (e.getMessage());
    }

    try{
    CTDrawing drawing = r3.getCTR().getDrawingArray(0);
    CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic();
    CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "Picture4",
    Units.toEMU(250), Units.toEMU(250),
    Units.toEMU(0), Units.toEMU(0),true);
    drawing.setAnchorArray(new CTAnchor[]{anchor});
    drawing.removeInline(0);

    }catch (Exception e){
    System.out.println (e.getMessage());
    }

    String anchorXML =
    "<wp:anchor xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
    +"distT=\"0\" distB=\"0\" distL=\"114300\" distR=\"114300\" simplePos=\"0\" relativeHeight=\"251658240\" behindDoc=\"1\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"

    +"<wp:simplePos x=\"0\" y=\"0\"/>"

    +"<wp:positionH relativeFrom=\"column\"><wp:posOffset>-1800000</wp:posOffset></wp:positionH>"
    +"<wp:positionV relativeFrom=\"paragraph\"><wp:posOffset>-1800000</wp:posOffset></wp:positionV>"

    + "<wp:extent cx=\"3448050\" cy=\"3619500\"/>"
    +"<wp:effectExtent l=\"0\" t=\"0\" r=\"6350\" b=\"6350\"/>"
    +" <wp:simplePos x=\"0\" y=\"0\"/><wp:positionH relativeFrom=\"column\"><wp:posOffset>-1800000</wp:posOffset></wp:positionH><wp:positionV relativeFrom=\"paragraph\"><wp:posOffset>-1800000</wp:posOffset></wp:positionV><wp:extent cx=\"3448050\" cy=\"3619500\"/><wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/><wp:wrapNone/> "
    +"<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\""+drawingDescr+"\"/><wp:cNvGraphicFramePr/>"
    +"</wp:anchor>";

    CTDrawing drawing = CTDrawing.Factory.parse(anchorXML);
    CTAnchor anchor = drawing.getAnchorArray(0);
    anchor.setGraphic(graphicalobject);

    // stream output to file
    FileOutputStream outStream = null;
    try {
    double x = Math.random();

    String fileName = "C:\\poi-3.9\\generateprequal\\output\\" + args[0] + ".docx";
    outStream = new FileOutputStream(fileName);
    } catch (FileNotFoundException e) {
    System.out.println("First Catch");
    e.printStackTrace();
    }
    try {
    document.write(outStream);
    outStream.close();
    } catch (FileNotFoundException e) {
    System.out.println("Second Catch");
    e.printStackTrace();
    } catch (IOException e) {
    System.out.println("Third Catch");
    e.printStackTrace();
    }
    }}

how to put images at a certain place in the Word(.docx) file by using DOCX4J in java

You're just appending the image to the end of the document using that code. If you need it in a certain place within the document, you need to get a handle on where (for example, you might locate a specific P node using MainDocumentPart.getJAXBNodesViaXPath()), and then simply insert the new content at that 'index' within the document like so:

package.getMainDocumentPart().getContent().add(index, imageParagraph);

(You would derive the value for 'index' by using something like MainDocumentPart.getContent().indexOf(oldParagraph), and presumably would want to also remove the node you found, which is possible via a remove() call).

add two images in same line in python-docx

Use Run.add_picture() instead of Paragraph.add_picture(). This will allow multiple images in the same paragraph, which, if they both fit within the page margins, will result in side-by-side images:

paragraph = document.add_paragraph()
run = paragraph.add_run()
run.add_picture(...)
run_2 = paragraph.add_run()
run_2.add_picture(...)

As far as alignment is concerned, when using paragraphs, inserting tabs is probably most reliable. The other alternative is to add a table and place the images in side-by-side cells.

Is it possible to insert an icon in Microsoft Word document at a specific position, using Aspose.Word in C#

I have found a solution to this by contacting the Aspose Support Team. And can refer in this below link: How to insert an icon in MS Word using Aspose.Word C#



Related Topics



Leave a reply



Submit