gpt4 book ai didi

python - 使用 python-docx 合并包含图像的 docx 文件

转载 作者:行者123 更新时间:2023-11-28 19:00:39 28 4
gpt4 key购买 nike

我需要合并两个包含图像的 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

最佳答案

将文档转换为 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()

关于python - 使用 python-docx 合并包含图像的 docx 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52947271/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com