pdf转图片加水印压缩
2024-10-20 16:36:58
'''
pip install pymupdf
pip install pillow
''' import os
import uuid
import fitz
from PIL import Image, ImageDraw, ImageFont
import zipfile basedir = "E:\\1\\"
pdf = "1.pdf"
text = "海豚传媒版权所有" def addzip(dir):
zipname = str(uuid.uuid4()).replace("-", "") + ".zip"
zipfilepath = os.path.abspath(os.path.dirname(dir)) + "\\" + zipname
f = zipfile.ZipFile(zipfilepath, 'w', zipfile.ZIP_STORED)
filelist = os.listdir(dir)
for p in filelist:
f.write(os.path.join(dir, p), p)
f.close()
return # 添加水印
def waterMark(imgfile, idx):
image = Image.open(imgfile)
font = ImageFont.truetype('C:\Windows\Fonts\STXINGKA.TTF', 36)
# 添加背景
new_img = Image.new('RGBA', (image.size[0] * 3, image.size[1] * 3), (0, 0, 0, 0))
new_img.paste(image, image.size)
# 添加水印
font_len = len(text)
rgba_image = new_img.convert('RGBA')
text_overlay = Image.new('RGBA', rgba_image.size, (255, 255, 255, 0))
image_draw = ImageDraw.Draw(text_overlay)
# text_overlay = text_overlay.rotate(-45)
image_draw.text((image.size[0], image.size[1]), text, font=font, fill=(0, 0, 0, 10))
image_with_text = Image.alpha_composite(rgba_image, text_overlay)
# 裁切图片
image_with_text = image_with_text.crop((image.size[0], image.size[1], image.size[0] * 2, image.size[1] * 2))
im_after = image_with_text.convert('RGB')
# 保存文件
dest = basedir + "jpg"
if not os.path.exists(dest):
os.mkdir(dest)
im_after.save(dest + "\\" + str(idx) + ".jpg", quality=70) def pdf2img(pdffile):
idx = 1
doc = fitz.open(pdffile)
count = doc.pageCount
for pg in range(count):
# 第一页和最后一页不要
if pg == 0:
continue
if pg == count - 1:
continue
page = doc[pg]
rotate = int(0)
# 每个尺寸的缩放系数为2,这将为我们生成分辨率提高四倍的图像。
zoom_x = 1
zoom_y = 1
trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
pm = page.getPixmap(matrix=trans, alpha=False)
pngFilePath = '%s%s.png' % (basedir, idx)
pm.writePNG(pngFilePath)
waterMark(pngFilePath, idx)
idx = idx + 1 pdf2img(os.path.join(basedir, pdf))
addzip(os.path.join(basedir, "jpg"))
# print(str(uuid.uuid4()).replace("-", ""))
最新文章
- Linux 进程与线程六
- 如何使用grunt工具
- [LeetCode]题解(python):064-Minimum Path Sum
- java concurrency in practice读书笔记---ThreadLocal原理
- Arrays.asList()使用注意点
- LinearLayout 控件
- Elastic Search(一)
- 小米2及其他Android手机无法连接mac解决方案
- Struts2多文件上传
- poj 2686 Traveling by Stagecoach ---状态压缩DP
- java之jvm学习笔记四(安全管理器)
- POJ 2533-Longest Ordered Subsequence(DP)
- 【Hdu3652】B-number(数位DP)
- Populating Next Right Pointers in Each Node(I and II)
- 使Python走向Effective系列目录
- ubuntu下zip文件操作
- spring boot2.0(二 ) lettcute访问redis
- 在Linux下部署mysql时,使用group by碰到的问题
- JavaScript高级编程(1)——JavaScript初识
- Python2.7-datetime