我正在尝试创建一个组合 docx 文件,它将是 2 个 docx 文件的串联。我有以下 python 代码:
from docx import Document
files = ['Doc2.docx', 'Doc3.docx']
def combine_word_documents(files):
combined_document = Document('empty.docx')
count, number_of_files = 0, len(files)
for file in files:
sub_doc = Document(file)
# Don't add a page break if you've
# reached the last file.
if count < number_of_files - 1:
sub_doc.add_page_break()
for element in sub_doc._document_part.body._element:
combined_document._document_part.body._element.append(element)
count += 1
combined_document.save('both_docx_files.docx')
combine_word_documents(files)
问题是:
我尝试了给定的Python代码。 docx 文件应在新的 docx 文件中一个接一个地串联。
您要在第一个文件的开头而不是末尾添加分页符:
if count < number_of_files - 1:
sub_doc.add_page_break()
for element in sub_doc._document_part.body._element:
combined_document._document_part.body._element.append(element)
count += 1
将测试和分页符移到
for
循环之后,如下所示:
for element in sub_doc._document_part.body._element:
combined_document._document_part.body._element.append(element)
if count < number_of_files - 1:
sub_doc.add_page_break()
count += 1
您需要提供有关第二个问题的更多信息,因为不清楚您的意思。
第一个问题与分页有关;这个问题已经在之前的回复中,当你考虑第二个问题时,这个问题就不那么重要了。
图像不直接存储在文档的XML正文中;它们单独存储在文档的媒体文件夹中,并在 XML 中引用。简单地附加 XML 元素将无法正确复制图像或其引用,从而导致组合文档中缺少它们。
对于图像,情况比较复杂,因为您需要从源文档中提取图像并将它们插入到组合文档中的正确位置。 正确处理图像需要手动将图像文件从源文档的媒体目录复制到组合文档的媒体目录中,并修复文档 XML 中的引用。截至我上次更新,python-docx 没有提供内置方法来执行此操作。此过程可能涉及直接操作底层 opc 包部分,这可能会变得相当技术性。
图像的可能解决方法: 解决方案可能是将文档转换为 PDF,合并 PDF,然后(如果绝对必要)转换回 DOCX。有一些可用于 PDF 操作的库和工具可以更优雅地处理此类任务。