Объедините docx-файлы, содержащие изображения, используя python-docx - PullRequest
0 голосов
/ 23 октября 2018

Мне нужно объединить два docx-файла, содержащих изображения.Следующий код объединяет файлы (текст, таблицы), но не может объединять изображения.

Есть идеи, как это исправить, пожалуйста?:)

import os
from docx import Document

files = ['sub_doc1.docx', 'sub_doc2.docx']


def merge_docs(files):
    res_doc = Document()

    for file in files:
        sub_doc = Document(file)
        for element in sub_doc.element.body:
            res_doc.element.body.append(element)

    res_doc.save('res_doc.docx')
    os.startfile('res_doc.docx')

merge_docs(files)

Документы для слияния и файл результатов находятся здесь:

  1. Файл результатов https://drive.google.com/file/d/1sYOUFQn1At16XWVlrH4OqV7L_jmfaEHH/view?usp=sharing

  2. Первый подфайл https://drive.google.com/file/d/1ScVcNGuR-P0giRCCFQZ_Ne4Oj45eDANQ/view?usp=sharing

  3. Второй вложенный файл https://drive.google.com/file/d/1X_PLAarhTTHDrjUALumA5WPtLVLGQxQw/view?usp=sharing

1 Ответ

0 голосов
/ 27 июня 2019

Преобразует документы в PDF, а затем объединяет PDF в один файл.

import os
import glob
import comtypes.client
from PyPDF2 import PdfFileMerger


def docxs_to_pdf():
    """Converts all word files in pdfs and append them to pdfslist"""
    word = comtypes.client.CreateObject('Word.Application')
    pdfslist = PdfFileMerger()
    x = 0
    for f in glob.glob("*.docx"):
        input_file = os.path.abspath(f)
        output_file = os.path.abspath("demo" + str(x) + ".pdf")
        # loads each word document
        doc = word.Documents.Open(input_file)
        doc.SaveAs(output_file, FileFormat=16+1)
        doc.Close() # Closes the document, not the application
        pdfslist.append(open(output_file, 'rb'))
        x += 1
    word.Quit()
    return pdfslist

def joinpdf(pdfs):
    """Unite all pdfs"""
    with open("result.pdf", "wb") as result_pdf:
        pdfs.write(result_pdf)

def main():
    """docxs to pdfs: Open Word, create pdfs, close word, unite pdfs"""
    pdfs = docxs_to_pdf()
    joinpdf(pdfs)

main()
...