写一个python程序遍历pdf中的每一页使pdf里的所有除白色的像素点变为纯黑色保存为pdf。路径为CUsers94553OneDrive考研资料多设备共享408图书·进程与线程pdf请说明python的版本及库的版本
以下是Python 3.x版本的代码,使用了PyPDF2和Pillow库:
import PyPDF2
from PIL import Image
# 打开PDF文件
pdf_file = open('C:/Users/94553/OneDrive/考研资料多设备共享/408图书/·/进程与线程.pdf', 'rb')
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
# 遍历每一页
for page_num in range(pdf_reader.numPages):
# 获取当前页
page = pdf_reader.getPage(page_num)
# 将当前页转换为Pillow的Image对象
page_image = page.toImage()
# 遍历像素点
for x in range(page_image.width):
for y in range(page_image.height):
# 获取当前像素点的颜色
pixel = page_image.getpixel((x, y))
# 如果不是白色,则将其变为黑色
if pixel != (255, 255, 255):
page_image.putpixel((x, y), (0, 0, 0))
# 将处理后的Image对象保存为PDF
output_pdf = PyPDF2.PdfFileWriter()
output_pdf.addPage(page_image.toPdf())
output_file = open('output.pdf', 'wb')
output_pdf.write(output_file)
output_file.close()
pdf_file.close()
需要安装的库的版本:
- PyPDF2 >= 1.26.0
- Pillow >= 8.2.
原文地址: https://www.cveoy.top/t/topic/dCUL 著作权归作者所有。请勿转载和采集!