python - 使用 python-docx 合并包含图像的 docx 文件
问题描述
我需要合并两个包含图像的 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)
要合并的文档和结果文件在这里:
解决方案
将文档转换为 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()
推荐阅读
- java - 为什么 JMockit 期望阻塞会抛出 IllegalMonitorStateException?
- python - Getting AttributeError when using inherited class
- javascript - Javascript - 如何防止 localStorage 将数据存储为字符串?
- c# - 侦听器如何再次重新连接客户端
- xml - 使用 XSLT 更改单个元素的样式
- r - lapply (R) 的属性丢失
- python - 使用 subprocess.call() 时防止光标加载动画
- typescript - 是否可以按值类型过滤键?
- javascript - VueJS如何观察一个值并在它改变时进行动画处理
- google-cloud-platform - Cloud Composer $$$(获取 Firebase 文件的更好/更便宜的选择 > Cloud Storage > BigQuery > Few Python / SQL 查询)