day9 PDF操作作业
1. 创建个人水印
"""
Author:TianGuoHui
Create Time:2023/2/16 16:28
"""
from reportlab.pdfgen.canvas import Canvas
# 注册字体
from reportlab.pdfbase.pdfmetrics import registerFont
from reportlab.pdfbase.ttfonts import TTFont
# 1.创建一个空白画布
# 在指定位置新建空白的pdf文件
file = Canvas('files/MyWater.pdf')
# 2.添加文字
# 1)注册字体
registerFont(TTFont("F1", "files/font1.ttf"))
# 2)设置字体
file.setFont("F1", 30)
# alpha表示透明度
file.setFillColorRGB(0.3, 0.4, 0.6, 0.5)
# 旋转
file.rotate(20)
# file.drawString(x坐标,y坐标, 水印名)
file.drawString(360, 380, "专业数据分析DataTian")
# 3.渲染图片
file.drawImage("image/data_image.png", 320, 375, mask="auto", width=40, height=40)
# 保存
file.save()
2. 遍历一个文件下的所有PDF每一页都添加水印
"""
Author:TianGuoHui
Create Time:2023/2/16 17:04
"""
from PyPDF2 import PdfWriter,PdfReader
import os
pdf_files = os.listdir("input")
# 1.准备水印页面
reader1 = PdfReader("files/MyWater.pdf")
water = reader1.getPage(0)
# 添加水印
for file_name in pdf_files:
reader2 = PdfReader("input/" + file_name)
writer = PdfWriter()
for i in range(reader2.getNumPages()):
page = reader2.getPage(i)
page.mergePage(water)
writer.addPage(page)
writer.write("out/" + file_name)