坑啊.....PHP实现不了才出此下策:
首先声明使用Python2.7版本!!! Python2.7版本! Python2.7版本! Python2.7版本! 重要的事情说三遍!说三遍!说三遍!
安装包:
pip2 install pypdf2
pip2 install reportlab
废话少说,上代码!
# -*- coding: utf-8 -*-
from PyPDF2 import PdfFileWriter, PdfFileReader
from reportlab.pdfgen import canvas
from reportlab.lib.units import cm
import sys
def create_watermark(content):
# 默认大小为21cm*29.7cm
c = canvas.Canvas("mark.pdf", pagesize=(30 * cm, 30 * cm))
# 移动坐标原点(坐标系左下为(0,0))
c.translate(3 * cm, 5 * cm)
c.setFont("Helvetica", 60)
# 指定描边的颜色
# c.setStrokeColorRGB(0, 1, 0)
# 指定填充颜色
c.setFillColorRGB(0, 1, 0)
# 画一个矩形
# c.rect(cm, cm, 7 * cm, 17 * cm, fill=1)
# 旋转45度,坐标系被旋转
c.rotate(45)
# 指定填充颜色
# c.setFillColorRGB(0.6, 0, 0)
# 设置透明度,1为不透明
c.setFillAlpha(0.3)
# 画几个文本,注意坐标系旋转的影响
c.drawString(3 * cm, 0 * cm, content)
c.setFillAlpha(1.0)
# c.drawString(6 * cm, 3 * cm, content)
# c.setFillAlpha(1)
# c.drawString(9 * cm, 6 * cm, content)
# 关闭并保存pdf文件
c.save()
def watermark(input_pdf, output, watermark):
watermark_obj = PdfFileReader(watermark)
watermark_page = watermark_obj.getPage(0)
pdf_reader = PdfFileReader(input_pdf)
pdf_writer = PdfFileWriter()
# 给所有页面添加水印
for page in range(pdf_reader.getNumPages()):
page = pdf_reader.getPage(page)
page.mergePage(watermark_page)
pdf_writer.addPage(page)
with open(output, 'wb') as f:
pdf_writer.write(f)
if __name__ == '__main__':
origin_file = sys.argv[1]
out_file = sys.argv[2]
mark = sys.argv[3]
# create_watermark('水印文字') # 生成mark文件
watermark(input_pdf=origin_file,output=out_file,watermark=mark)
需要注意的点:
水印文件不能自己制作,调用create_watermark('水印文字')生成;
打码吧.......
标签:__,cm,watermark,Python,水印,pdf,PDF,page From: https://blog.51cto.com/u_13940603/5886331