pdf轉圖片加水印壓縮

'''
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("-", ""))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章