pdf转图片加水印压缩

时间:2021-07-27 17:38:27   收藏:0   阅读:0
‘‘‘
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("-", ""))

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!