python去除文档水印,删除页眉页脚

处理前效果

在这里插入图片描述

处理后

在这里插入图片描述

读取doc文档报错:raise ValueError(tmpl % (docx, document_part.content_type))

from docx import Document
path = r"D:\\demo\\2011年北京高考文数试题及答案2.doc"
doc = Document(path)

ValueError: file ‘D:\2011年北京高考文数试题及答案2.doc’ is not a Word file, content type is ‘application/vnd.openxmlformats-officedocument.themeManager+xml’**

首先确定了文档是存在且有内容,路径也没问题,
wps可以正常打开,但是doc是旧版本的格式读取
在这里插入图片描述
可用win32com.client包打开

import win32com.client as wc
word = wc.Dispatch("Word.Application")
doc = word.Documents.Open(file_path, Encoding='utf-8')

原本是想着先转换格式为docx再读取,太麻烦
直接上代码了

代码方式1

"""去除水印"""
import comtypes.client

word = comtypes.client.CreateObject('Word.Application')
doc = word.Documents.Open(path)

clean_text = []

# 删除页眉,页脚
for section in doc.Sections:
    for header in section.Headers:
        if header.Range.Text and len(header.Range.Text) > 2:
            clean_text += str(header.Range.Text).strip().split()
        header.Range.Delete()

    for footer in section.Footers:
        if footer.Range.Text and len(footer.Range.Text) > 2:
            clean_text += str(footer.Range.Text).strip().split()
        footer.Range.Delete()

## 替换文档内容
if clean_text:
    for target_text in set(clean_text):
    	## 不想替换页码
        if str(target_text).isdigit() or len(target_text) < 5:
            continue
        for content_range in doc.StoryRanges:
            content_range.Find.Execute(target_text, False, False, False, False, False, True, 1, False, '',
                                       2)
# doc.SaveAs()
doc.SaveAs('{}x'.format(path), 16)  # 16 表示保存为docx格式
doc.Close()
word.Quit()

代码方式2

    
from docx import Document

def clean_words(self, file_path, target_text):
     """ 清洗文档:替换页眉页脚内容         """
     doc = Document(file_path)

     # 获取所有节的页眉和页脚
     for section in doc.sections:
         # 获取页眉
         header = section.header
         if header is not None:
             # 获取页眉的段落
             for p in header.paragraphs:
                 # 替换页眉中的目标文字为空
                 p.text = p.text.replace(p.text, "")

         # 获取页脚
         footer = section.footer
         if footer is not None:
             # 获取页脚的段落
             for p in footer.paragraphs:
                 logger.info(p.text)
                 # 替换页脚中的目标文字为空
                 p.text = p.text.replace(p.text, "")

     # 替换文档内容的方式2:使用Document.paragraphs属性和Paragraph.text属性
     for i, p in enumerate(doc.paragraphs):
         for w in target_text:
             if w in p.text:
                 p.text = p.text.replace(w, "")

     doc.save(file_path)
     doc.close()```

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
去除PDF文件中的页眉页脚,可以使用Python中的第三方库PyPDF2来实现。 首先,我们需要安装PyPDF2库。可以使用以下命令在命令行中安装库: ``` pip install PyPDF2 ``` 安装完成后,我们可以编写Python代码来去除PDF文件的页眉页脚。具体代码如下: ```python import PyPDF2 # 打开PDF文件 pdf_file = open('example.pdf', 'rb') # 创建PDF阅读器对象 pdf_reader = PyPDF2.PdfReader(pdf_file) # 创建PDF写入器对象 pdf_writer = PyPDF2.PdfWriter() # 遍历PDF页面 for page_num in range(pdf_reader.numPages): # 获取当前页面 page = pdf_reader.getPage(page_num) # 从页面中提取内容框 content_box = page.mediaBox # 更新内容框的上边界和下边界 content_box.upperRight = (content_box.upperRight[0], content_box.upperRight[1]-50) # 更新上边界 content_box.lowerLeft = (content_box.lowerLeft[0], content_box.lowerLeft[1]+50) # 更新下边界 # 创建新页面,并将内容框更新后的页面添加到PDF写入器中 new_page = pdf_writer.add_blank_page(width=page.mediaBox.getWidth(), height=page.mediaBox.getHeight()) # 创建新页面 new_page.mergeTranslatedPage(page, tx=0, ty=-50) # 添加内容框更新后的页面 # 将处理后的 PDF 页面写入新文件 output_file = open('new_example.pdf', 'wb') pdf_writer.write(output_file) # 关闭文件 pdf_file.close() output_file.close() ``` 以上代码将打开`example.pdf`文件,并遍历每个页面,通过更新内容框的上边界和下边界来去除页眉页脚。然后将处理后的页面写入一个新的PDF文件`new_example.pdf`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值