Search code examples
pythonms-wordpython-docx

Python-docx: how to add a picture border?


I have an image in document's paragraph:

    document.add_picture("image.png")
    last_paragraph = document.paragraphs[-1]
    last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

How can i add a 1px border to this picture with python-docx lib?


Solution

  • You can use Python's PIL library for all image editing tasks. To add a border,

    def add_border(input_image, output_image, border):
        img = Image.open(input_image)
        if isinstance(border, int) or isinstance(border, tuple):
            bimg = ImageOps.expand(img, border=border)
        else:
            raise RuntimeError('Border is not an image or tuple')
        bimg.save(output_image)
    

    You can now call the function as needed

        in_img = 'Demo_Image.png'
        add_border(in_img, output_image='DemoBorder.png', border=1)
    

    This will save the output image in your working directory in png format(jpg, if saved as DemoBorder.jpg)