You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现Word/PDF内容批量复制的功能异常问题求助

一、解决python-docx复制Word全内容(含表格)的问题

原代码仅保留首页内容,是因为未遍历文档所有Section及其中的表格、段落等元素。以下是完整复制文档内容(含格式)并按指定次数重复的实现:

from docx import Document

def duplicate_word_content(input_path, output_path, copy_times):
    original_doc = Document(input_path)
    new_doc = Document()

    # 同步原文档样式,确保格式一致
    for style in original_doc.styles:
        new_style = new_doc.styles.add_style(style.name, style.type)
        new_style.font = style.font
        new_style.paragraph_format = style.paragraph_format

    # 按指定次数复制全部内容
    for _ in range(copy_times):
        # 遍历原文档每个Section,同步页面设置
        for section in original_doc.sections:
            new_section = new_doc.add_section()
            new_section.start_type = section.start_type
            new_section.page_width = section.page_width
            new_section.page_height = section.page_height
            new_section.left_margin = section.left_margin
            new_section.right_margin = section.right_margin
            new_section.top_margin = section.top_margin
            new_section.bottom_margin = section.bottom_margin

            # 复制Section内所有元素(段落、表格等)
            for element in section.body._element:
                new_doc._body._element.append(element.copy())

    new_doc.save(output_path)

核心逻辑:遍历原文档的每个Section,同步页面设置后,逐个复制Section内的段落、表格等节点到新文档,确保所有内容和格式都被完整复制。

二、解决PyPDF2复制PDF内容仅生成一份的问题

此类问题多因循环逻辑错误导致,比如仅添加一次原PDF页面就保存。以下是正确的重复复制实现:

from PyPDF2 import PdfReader, PdfWriter

def duplicate_pdf_content(input_path, output_path, copy_times):
    reader = PdfReader(input_path)
    writer = PdfWriter()

    # 循环指定次数,每次添加原PDF的全部页面
    for _ in range(copy_times):
        for page in reader.pages:
            writer.add_page(page)

    # 写入新PDF文件
    with open(output_path, "wb") as out_file:
        writer.write(out_file)

核心逻辑:每次循环都遍历原PDF的所有页面并添加到Writer对象中,确保指定次数的内容重复。

内容的提问来源于stack exchange,提问作者GameOverZeus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 05:52:37