python一键去PDF水印,只需十行代码,超级简单...

前因后果

弟弟最近要考试,临时抱佛脚在网上找了一堆学习资料复习,这不刚就来找我了,说PDF上有水印,影响阅读效果,到时候考不好就怪资料不行,气的我差点当场想把他揍一顿!

算了,弟弟长大了,看在打不过他的份上,就不打他了~

稍加思索,我想起了Python不是可以去水印?说搞就搞!

去除水印原理

去除方法:

  1. 用 PyMuPDF 打开 pdf 文件,将 pdf 的每一页都转换为图片 pixmap
  2. pixmap 有它自己的RGB,只需要将 pdf 水印中的 RGB 改为(255, 255, 255),并保存图片 ;
  3. 按照生成的图片,插入到pdf文档中;

因为pfd文档无法直接去除水印,需要先将pfd文档转换成图片,在逐一对图片进行水印去除操作,最后在把图片插入到pdf文档中。

代码剖析

1、先查看PDF文档中的水印rgb值是多少

可以看到,RGB(179,179,179),因为这里要的是RGB色值总和,所以我们就认为,超过510,就认为是水印。

敲黑板

光学三原色是红绿蓝(RGB),也就是说它们是不可分解的三种基本颜色,其他颜色都可以通过这三种颜色混合而成,三种颜色等比例混合就是白色,没有光就是黑色。
在计算机中,可以用三个字节表示 RGB 颜色,1个字节能表示的最大数值是 255, 所以,(255, 0, 0)代表红色,(0, 255, 0)代表绿色,(0, 0, 255)代表蓝色。相应地,(255, 255, 255)代表白色,(0, 0, 0)代表黑色。从(0, 0, 0) ~ (255, 255, 255) 之间的任意组合都可以代表一个不同的颜色。
图片每个位置颜色由四元组表示,前三位分别是 RGB,第四位是 Alpha 通道

2、pdf转换成图片,并去除水印

代码示例:

from PIL import Image
from itertools import product
import fitz

# 去除pdf的水印
def remove_pdfwatermark():
    #打开源pfd文件
    pdf_file = fitz.open("源码找落落阿.pdf")

    #page_no 设置为0
    page_no = 0
    #page在pdf文件中遍历
    for page in pdf_file:
        #获取每一页对应的图片pix (pix对象类似于我们上面看到的img对象,可以读取、修改它的 RGB)
        #page.get_pixmap() 这个操作是不可逆的,即能够实现从 PDF 到图片的转换,但修改图片 RGB 后无法应用到 PDF 上,只能输出为图片
        pix = page.get_pixmap()

        #遍历图片中的宽和高,如果像素的rgb值总和大于510,就认为是水印,转换成255,255,255-->即白色
        for pos in product(range(pix.width), range(pix.height)):
            if sum(pix.pixel(pos[0], pos[1])) >= 510:
                pix.set_pixel(pos[0], pos[1], (255, 255, 255))
        #保存去掉水印的截图
        pix.pil_save(f"./{page_no}.png", dpi=(30000, 30000))
        #打印结果
        print(f'第 {page_no} 页去除完成')

        page_no += 1

if __name__ == '__main__':
    remove_pdfwatermark()

执行完成

查看生成图片:

查看图片内容

3、图片转为pdf

代码示例:

from PIL import Image
from itertools import product
import fitz

''' 图片转为pdf'''
#图片所在的文件夹
pic_dir = 'F:\123'

pdf = fitz.open()
#图片数字文件先转换成int类型进行排序
img_files = sorted(os.listdir(pic_dir), key=lambda x: int(str(x).split('.')[0]))
for img in img_files:
    print(img)
    imgdoc = fitz.open(pic_dir + '/' + img)
    #将打开后的图片转成单页pdf
    pdfbytes = imgdoc.convertToPDF()
    imgpdf = fitz.open("pdf", pdfbytes)
    #将单页pdf插入到新的pdf文档中
    pdf.insertPDF(imgpdf)
pdf.save("源码找落落阿_完成.pdf")
pdf.close()

执行代码

查看生成的pdf文档

代码整合

上面的内容都了解以后,我们就整合代码,直接运行就可以了。

from PIL import Image
from itertools import product
import fitz


# 去除pdf的水印
def remove_pdfwatermark():
    # 打开源pfd文件
    pdf_file = fitz.open("源码找落落阿.pdf")

    # page_no 设置为0
    page_no = 0
    # page在pdf文件中遍历
    for page in pdf_file:
        # 获取每一页对应的图片pix (pix对象类似于我们上面看到的img对象,可以读取、修改它的 RGB)
        # page.get_pixmap() 这个操作是不可逆的,即能够实现从 PDF 到图片的转换,但修改图片 RGB 后无法应用到 PDF 上,只能输出为图片
        pix = page.get_pixmap()

        # 遍历图片中的宽和高,如果像素的rgb值总和大于510,就认为是水印,转换成255,255,255-->即白色
        for pos in product(range(pix.width), range(pix.height)):
            if sum(pix.pixel(pos[0], pos[1])) >= 510:
                pix.set_pixel(pos[0], pos[1], (255, 255, 255))
        # 保存去掉水印的截图
        pix.pil_save(f"./{page_no}.png", dpi=(30000, 30000))
        # 打印结果
        print(f'第 {page_no} 页去除完成')

        page_no += 1


# 去除的pdf水印添加到pdf文件中
def pictopdf():
    # 水印截图所在的文件夹
    # pic_dir = input("请输入图片文件夹路径:")
    pic_dir = 'F:\123'

    pdf = fitz.open()
    # 图片数字文件先转换成int类型进行排序
    img_files = sorted(os.listdir(pic_dir), key=lambda x: int(str(x).split('.')[0]))
    for img in img_files:
        print(img)
        imgdoc = fitz.open(pic_dir + '/' + img)
        # 将打开后的图片转成单页pdf
        pdfbytes = imgdoc.convertToPDF()
        imgpdf = fitz.open("pdf", pdfbytes)
        # 将单页pdf插入到新的pdf文档中
        pdf.insertPDF(imgpdf)
    pdf.save("源码找落落阿_完成.pdf")
    pdf.close()


if __name__ == '__main__':
    remove_pdfwatermark()
    pictopdf()

兄弟们学习python,有时候不知道怎么学,从哪里开始学。掌握了基本的一些语法或者做了两个案例后,不知道下一步怎么走,不知道如何去学习更加高深的知识。
那么对于这些大兄弟们,我准备了大量的免费视频教程,PDF电子书籍,以及源代码!
直接在文末名片自取即可~








总结

需要理解的流程是:

  • pdf文档需要先转换成图片,进行水印去除;
  • 再转换成pdf ;
  • 最后插入到新的pdf文档中;

写到这里,今天的分享就差不多快结束了,咱们下次再见!

  • 15
    点赞
  • 95
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
Paperback: 172 pages Publisher: Packt Publishing (December 30, 2015) Language: English ISBN-10: 1785885995 ISBN-13: 978-1785885990 Key Features Write smarter, bug-free, high performance code with minimal effort Uncover the best tools and options available to Python developers today Deploy decorators, design patters, and various optimization techniques to use Python 3.5 effectively Book Description Python is a versatile programming language that can be used for a wide range of technical tasks―computation, statistics, data analysis, game development, and more. Though Python is easy to learn, it's range of features means there are many aspects of it that even experienced Python developers don't know about. Even if you're confident with the basics, its logic and syntax, by digging deeper you can work much more effectively with Python – and get more from the language. Python Unlocked walks you through the most effective techniques and best practices for high performance Python programming - showing you how to make the most of the Python language. You'll get to know objects and functions inside and out, and will learn how to use them to your advantage in your programming projects. You will also find out how to work with a range of design patterns including abstract factory, singleton, strategy pattern, all of which will help make programming with Python much more efficient. Finally, as the process of writing a program is never complete without testing it, you will learn to test threaded applications and run parallel tests. If you want the edge when it comes to Python, use this book to unlock the secrets of smarter Python programming. What you will learn Manipulate object creation processes for instances, classes, and functions Use the best possible language constructs to write data structures with super speed and maintainability Make efficient use of design patterns to decrease development time and make your code more maintainable Write better test cases with an impro

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值