本文共 2691 字,大约阅读时间需要 8 分钟。
本示例将介绍如何为PDF文件添加文字水印的实现方法。我们将使用两个第三方库:pyPdf和ReportLab。以下是实现代码的详细说明。
pip install PIL
)from pyPdf import PdfFileWriter, PdfFileReaderfrom reportlab.pdfgen import canvasfrom PIL import Image, ImageDraw, ImageFontimport os
# 指定字体和字号font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf', 45)
def add_text_to_image(image_name, text, font=font): # 打开目标图片 image = Image.open(image_name) # 转换为RGBA格式 rgba_image = image.convert('RGBA') # 创建透明的文本覆盖层 text_overlay = Image.new('RGBA', rgba_image.size, (255, 255, 255, 0)) # 创建绘图对象 image_draw = ImageDraw.Draw(text_overlay) # 计算文本大小 text_size_x, text_size_y = image_draw.textsize(text, font=font) # 确定文本位置(这里采用底部居中) text_xy = ((rgba_image.size[0] - text_size_x) // 2, (rgba_image.size[1] - text_size_y) // 2) # 绘制文本 image_draw.text(text_xy, text, font=font, fill=(0, 0, 0)) # 合成图片 image_with_text = Image.alpha_composite(rgba_image, text_overlay) return image_with_text
def add_mark(info_name, text): # 创建水印PDF文件 c = canvas.Canvas("watermark.pdf") c.setFont("Courier", 35) c.setFillGray(0.0, 1) # 设置灰度 c.saveState() # 保存绘图状态 c.translate(280, 750) # 平移坐标 c.rotate(0) # 旋转角度 c.drawCentredString(0, 0, text) # 中心绘制文本 c.restoreState() # 恢复绘图状态 c.save() # 保存PDF文件
def run(): # 创建结果目录 os.mkdir("results") # 获取当前目录下的文件列表 file_name = "info" files = os.listdir(file_name) r = 0 # 初始化计数器 for t_file in files: file_all_img = os.path.join(file_name, t_file) if os.path.isfile(file_all_img): continue # 遍历文件夹中的所有图片文件 for file_img in os.listdir(file_all_img): file_img_all_img_all = os.path.join(file_all_img, file_img) if file_img_all_img_all.endswith('pdf'): # 为PDF文件添加水印 output = add_mark(file_img_all_img_all, t_file) # 保存结果 with open(os.path.join('results', f'{r}.pdf'), 'wb') as outStream: output.write(outStream) # 删除临时水印文件 os.remove("watermark.pdf") else: # 为图片文件添加文字水印 im_after = add_text_to_image(file_img_all_img_all, t_file) im_after.save(os.path.join('results', f'{r}.png')) r += 1
.py
文件,并确保所有依赖库已安装。results
目录下。通过以上方法,您可以轻松为PDF文件和图片文件添加文字水印,实现文件的版权保护。
转载地址:http://ljmcz.baihongyu.com/