用python删除pdf文件的特定页码

#pip install PyPDF2模块

#代码文件写好源文件和目标文件完整路径

#调用函数,参数写好要删除的页码即可

from PyPDF2 import PdfFileWriter,PdfFileReader

fn1=r'C:\Users\asus\Desktop\s\零起点PYTHON机器学习快速入门2.pdf'
fn2=r'C:\Users\asus\Desktop\s\零起点PYTHON机器学习快速入门3.pdf'


def PDF_delete(index):
    #参数是一个整数列表,列表里是要删除的页码
    output = PdfFileWriter()  # 声明一个用于输出PDF的实例
    input1 = PdfFileReader(open(fn1, "rb"))  # 读取本地PDF文件
    pages = input1.getNumPages()  # 读取文档的页数
    for i in range(pages):
        if i + 1 in index:
            continue  # 待删除的页面
        output.addPage(input1.getPage(i))  # 读取PDF的第i页,添加到输出Output实例中
    outputStream = open(fn2, "wb")
    output.write(outputStream)  # 把编辑后的文档保存到本地

PDF_delete(list(range(2)))
 

### 使用 Python 处理 Docx 文件移除页眉和页码 对于 `.docx` 文件,可以利用 `python-docx` 库来操作文档。然而需要注意的是,`python-docx` 并不直接支持删除已有的页眉或页脚内容;可以通过修改其内部结构间接实现这一功能。 #### 修改 Page Header/Footer XML 来清除内容 由于无法通过常规 API 删除现有页眉页脚,一种方法是访问并清空这些部分对应的XML节点数据: ```python from docx import Document import zipfile import os def remove_headers_footers(doc_path, output_path): # 创建临时压缩包读取原始文件 with zipfile.ZipFile(doc_path) as zin: with zipfile.ZipFile(output_path, 'w') as zout: for item in zin.infolist(): if not (item.filename.startswith('word/header') or item.filename.startswith('word/footer')): data = zin.read(item.filename) zout.writestr(item, data) # 示例调用函数 remove_headers_footers('./example.docx', './output_no_header_footer.docx') ``` 此代码片段会创建一个新的不含任何原有页眉页脚的新 DOCX 文件[^2]。 #### PDF 文件处理方式不同 针对PDF格式,则需借助其他专门库如 PyMuPDF 或者 PyPDF2 。这里给出基于PyMuPDF的一个简单例子用于去掉每一页上的固定位置文字(假设为页码),这可能不是最精确的办法因为实际应用中页码的位置可能会变化: ```python import fitz # 导入 pymupdf 的别名 def clear_fixed_text_from_pdf(input_file, output_file, text_to_remove="Page"): document = fitz.open(input_file) for page_num in range(len(document)): page = document.load_page(page_num) # 获取页面上所有的文本块 blocks = page.get_text("dict")["blocks"] new_blocks = [] for block in blocks: lines = [line for line in block['lines'] if text_to_remove.lower() not in ''.join([span['text'].lower() for span in line['spans']])] if len(lines)>0: block['lines']=lines new_blocks.append(block) page.set_rect(-1,-1,*page.rect.size).add_redact_annot() page.apply_redactions() document.save(output_file) clear_fixed_text_from_pdf("./sample.pdf", "./cleaned_sample.pdf") ``` 这段程序尝试定位并移除包含特定字符串(比如 "Page")的文本片段,从而达到清理目的[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值