5

I am trying to create a file.doc (Microsoft Word Document format) and write some text into it and also, insert an image into it via command shell. I have no idea what or how should I do it.

Any suggestions? Thanks

αғsнιη
  • 36,350

1 Answers1

2

You may use python-docx to create MS Word document by creating an intermediate script to handle the shell arguments.

  1. Install required libraries:

    sudo apt-get install python-pip libxslt1-dev python-lxml
    sudo pip install python-docx
    
  2. Write the intermediate script and let's name it docx-gen

    #!/usr/bin/env python
    
    import sys
    
    from docx import Document
    from docx.shared import Inches
    
    
    if __name__=="__main__":
        document = Document()
        document.add_heading(sys.argv[2], 0)
        document.add_paragraph(sys.argv[3])
        document.add_picture(sys.argv[4],width=Inches(6.0))
        document.add_page_break()
        document.save(sys.argv[1])
        sys.exit(0)
    
  3. Give it the right permissions

    chmod +x docx-gen
    
  4. Use it locally

    ./docx-gen demo.docx "Title" "A paragraph with few words." ~/Pictures/snapshot1.png
    

    or copy it to the system bin folder:

    sudo cp docx-gen /usr/local/bin/
    

    then to use it:

    docx-gen demo.docx "Title" "A paragraph with few words." ~/Pictures/snapshot1.png
    

Reference:

I just modified its example, see its official documentation.

Notes:

  • The script does not include any input check, just to keep it simple.
  • Used fixed width of 6 inches, you may add it to input arguments too.

demo document for python-docx

user.dz
  • 49,176