Solomon Raja
Solomon Raja

Reputation: 103

Is there an attribute 'fit-to-page' in add_picture() using python docx

I have added a picture in a doc by using python docx. It looks good as long as it's small. But the picture goes next page or it's displayed half of it if the size is too big. How to make my picture 'fit-to-page'. I dont want to give any constants like Inches-5.5 or something.

    p1 = doc.add_paragraph(' ')
    pic = doc.add_picture(os.path.join(base_path, fi),
          width=Inches(5.0))
    para = doc.paragraphs[-1]

Upvotes: 5

Views: 3333

Answers (1)

FilipeTavares
FilipeTavares

Reputation: 63

It's possible to get the text width, which is the page width minus the left and right margins, and pass this value to the width argument of add_picture().

An example of a function to get the text width is:


def get_text_width(document):
    """
    Returns the text width in mm.
    """
    section = document.sections[0]
    return (section.page_width - section.left_margin - section.right_margin) / 36000

You can then call the function when adding a new picture:

r.add_picture(image, width=Mm(get_text_width(doc)))

If you need to add pictures in different sections of a document, it's necessary to improve the function to address this.

References:

How to change page size to A4 in python-docx

https://www.trichview.com/help/units_of_measurement.html#:~:text=English%20metric%20unit%20(EMU)%20is,%2C%201%20mm%20%3D%2036000%20EMU

Upvotes: 4

Related Questions