Normal means can not add the image to the end of the file. Code
old_image = open('Pupils.png', 'r').read() new_image = open('new_pro.docx', 'a') new_image.write(old_image) new_image.close() What are the ways to solve this problem?
Python is good because there is a library for every occasion. In this case, it is docx. First install it (you need root privileges on Linux)
pip install python-docx And then just add the image.
from docx import Document document = Document("./foo.docx") document.add_picture('./image-filename.png') document.save("./foo.docx") I suggest adding docxtpl to the python-docx library. It works very simple. It is necessary to make a template and in it to mark the place where something to insert. On the gita you can see the markup examples. Examples
* .docx is a zip-archive with service files describing the document. The service files are in XML format , so you cannot add an image to the document in the manner described above (simply by adding the bytes to the archive). To solve, you need to use special libraries that take parsing of XML on themselves and guarantee the correctness of the resulting document according to the standard . An example of such a library: python-docx ( pip install python-docx ). Example from official documentation :
from docx import Document doc = Document("<PATH_TO_DOCX>") doc.add_picture('image-filename.png') Instead of the full path to the image, you can use a file-like object (for example, BytesIO ):
with open("yo.png", "rb") as img: doc.add_picture(img) If necessary, you can resize the image . In this case, the main thing to remember is that in the document all sizes are centimeters, inches and derivatives, not pixels.
Source: https://ru.stackoverflow.com/questions/654759/
All Articles
rb,wb- kitscribe