简体   繁体   中英

How can I embed images using path to python-docx, iteratively add the images to a .DOCX template, and save each unique .DOCX?

I'm trying to solve a problem using Python involving a directory path to image files and the python-docx library.

I have a directory containing 100 *.png files that are unique QR codes, created from a separate process:

  codes_dir
    ├── qr_code001.png
    ├── qr_code002.png
    ├── qr_code003.png
    ├── qr_code004.png
    ├── qr_code005.png
    etc

I need to embed each *.png QR code into a standard .DOCX file, and then save the unique results. The .DOCX template looks like this:

在此处输入图片说明

After the fact, each file needs to look like this:

在此处输入图片说明

And then in a separate directory I would have a list of unique .DOCX files which correspond to the basenames of each unique QR code, like so:

  codes_dir
    ├── qr_code001.png
    ├── qr_code002.png
    ├── qr_code003.png
    ├── qr_code004.png
    ├── qr_code005.png
    etc
   docx_dir
    ├── qr_code001.docx
    ├── qr_code002.docx
    ├── qr_code003.docx
    ├── qr_code004.docx
    ├── qr_code005.docx
    etc

Here's what I've tried, running from within docx_dir :

from docx import Document
import glob
import os

def embed_qr_code():
    doc = Document("path/to/template.docx")
    qr_images = glob.glob("path/to/codes_dir")
    for image in qr_images:
        image_name = os.path.basename(image)
        doc.add_picture(image)
        doc.save(f"{image_name}.docx")

embed_qr_code()

I end up with 100 files that appear like this:

   docx_dir
    ├── qr_code001.png.docx
    ├── qr_code002.png.docx
    ├── qr_code003.png.docx
    ├── qr_code004.png.docx
    ├── qr_code005.png.docx
    etc

Seems to work, but instead of one QR code image per one .DOCX file, the .DOCX files contain... well, not one QR code. I don't understand how this could be when each QR image file name is unique. 在此处输入图片说明

Can you help me understand what I am doing incorrectly? Thank you for any help you can provide.

You have to open a new file for each image. So move your Document() call down inside the loop like this:

def embed_qr_code():
    qr_images = glob.glob("path/to/codes_dir")
    for image in qr_images:
        image_name = os.path.basename(image)
        doc = Document("path/to/template.docx")
        doc.add_picture(image)
        doc.save(f"{image_name}.docx")

Otherwise doc accumulates the images as they are added, so the first saved doc gets one, the second gets that one plus another, and so on like 1, 2, 3, ... images for as may images as there are in qr_images .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM