pdf轉圖片加水印壓縮

WellBay 1月前


標籤:jpg   切圖   count   pos   tran   %s   win   加水印   pre   

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

 

pdf轉圖片加水印壓縮

標籤:jpg   切圖   count   pos   tran   %s   win   加水印   pre   

原文地址:https://www.cnblogs.com/wujf/p/15064861.html


上一篇:設計模式-代理模式
下一篇:DOS基本命令