Search code examples
pythonpython-3.xpython-docx

how to add a png file into a word document in python 3


The goal is to copy images I have as png's into a document (preferably a word document). I have found python-docx, but that only works for python 2.x (successfully downloaded) but it didn't run. The only thing I could find about it in this stack overflow question. It waspython-2.7 tagged. I don't mind if the pictures have to be in the same directory as the word document.

Sorry if I don't mentioning anything I should have, I am still fairly new at asking questions.


Solution

  • Proper python-docx installation:

    • from command-line: pip install python-docx

    You should get 0.8.10 as latest. Approx 5.5mb large.

    Below is the python-docx example code used from here. Look at the location where the files are located. if you adjust that to your liking than you should get a docx file.

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    from docx import Document
    from docx.shared import Inches
    
    document = Document()
    
    document.add_heading('Document Title', 0)
    
    p = document.add_paragraph('A plain paragraph having some ')
    p.add_run('bold').bold = True
    p.add_run(' and some ')
    p.add_run('italic.').italic = True
    
    document.add_heading('Heading, level 1', level=1)
    document.add_paragraph('Intense quote', style='Intense Quote')
    
    document.add_paragraph(
        'first item in unordered list', style='List Bullet'
    )
    document.add_paragraph(
        'first item in ordered list', style='List Number'
    )
    
    document.add_picture('D:\test\monty-truth.png', width=Inches(1.25))
    
    records = (
        (3, '101', 'Spam'),
        (7, '422', 'Eggs'),
        (4, '631', 'Spam, spam, eggs, and spam')
    )
    
    table = document.add_table(rows=1, cols=3)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = 'Qty'
    hdr_cells[1].text = 'Id'
    hdr_cells[2].text = 'Desc'
    for qty, id, desc in records:
        row_cells = table.add_row().cells
        row_cells[0].text = str(qty)
        row_cells[1].text = id
        row_cells[2].text = desc
    
    document.add_page_break()
    
    document.save('D:\test\demo.docx')
    

    The monthy-truth.png file is here:

    image