Add image at specific position in document (.docx) using Python?

I am using Python-docx to create a Microsoft Word document. The user wants, when he wrote, for example: "Good morning, every body, this is my% (profile_img), do you like it?" in the HTML field, I create a word document and I restore the user image from the database, and I replace the keyword% (profile_img) s with the user image NOT at the END OF THE DOCUMENT . With Python-docx, we use this instruction to add an image:

document.add_picture('profile_img.png', width=Inches(1.25))

The image is added to the document, but the problem is that it is added at the end of the document. Is it not possible to add an image at a specific position in a Microsoft Word document using python? I did not find any answers to this on the net, but I saw people asking the same thing elsewhere without a solution.

Thank you (note: I'm not a very experienced programmer and apart from this awkward part, the rest of my code will be very simple)

+6
source share
5 answers

Quote python-docx documentation :

Document.add_picture() . , API, , .

" ", API Run.add_picture().

:

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')
+10

, , , , docx: docx ( ). , . , . , , , .

from docx import Document
from docx.shared import Inches

doc = Document('addImage.docx')
tables = doc.tables
p = tables[0].rows[0].cells[0].add_paragraph()
r = p.add_run()
r.add_picture('resized.png',width=Inches(4.0), height=Inches(.7))
p = tables[1].rows[0].cells[0].add_paragraph()
r = p.add_run()
r.add_picture('teste.png',width=Inches(4.0), height=Inches(.7))
doc.save('addImage.docx')
+6

. , ( 1) . , , Word.

, .

from docx import Document
from docx.shared import Inches

# ------- initial code -------

document = Document()

p = document.add_paragraph()
r = p.add_run()
r.add_text('Good Morning every body,This is my ')
picPath = 'D:/Development/Python/aa.png'
r.add_picture(picPath)
r.add_text(' do you like it?')

document.save('demo.docx')

# ------- improved code -------

document = Document()

p = document.add_paragraph('Picture bullet section', 'List Bullet')
p = p.insert_paragraph_before('')
r = p.add_run()
r.add_picture(picPath)
p = p.insert_paragraph_before('My picture title', 'Heading 1')

document.save('demo_better.docx')
+1

:

 document.add_picture(settings.MEDIA_ROOT+'/image/cta-header3-min.png', width=Inches(5.8))

settings.MEDIA_ROOT

0

I have the same problem, I don’t know why, but after many attempts, I think I found another way to solve the problem. You can open the word file, copy and paste it into the newly created word file, and then rename the name of the new created word file to the old one.

0
source

Source: https://habr.com/ru/post/1610153/


All Articles