企业的文控中心发放文件的时候一般需要盖受控章,表示文件版本和发放数量受到了控制.
传统操作方式:人工盖章+手工记录
本文先解决人工盖章问题
需要使用的python模块PyPDF2, reportlab
需要建文件夹:
pic_source 保存原文件,存放以.pdf 结尾的文件
pic_chop 保存盖章文件
# -*- coding:utf-8 -*-
import PyPDF2
import os
from reportlab.lib.units import inch #Convert a string or number to a floating point number, if possible.
from reportlab.pdfgen import canvas
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
import time
import datetime
def create_chop(): #生成电子印章
pdfmetrics.registerFont(TTFont('SimHei', 'SimHei.TTF'))
c = canvas.Canvas("stamp.pdf")
c.translate(inch,inch) # move the origin from the current (0,0) point to the (dx,dy) point 起始点位置
c.setStrokeColorRGB(255,0,0) #边框颜色
c.setFillColorRGB(0,0,0) #颜色填充
#c.setFillAlpha(True)
c.rect(0,0,2*inch,1*inch, fill=0) #边框的位置和大小fill=0不填充
c.rotate(0)
c.setFillColorRGB(255,0,0)
c.setFont('SimHei', 20)
c.drawString(35, 50, "受 控") #drawString(self, x, y, text, mode=None, charSpace=0, direction=None, wordSpace=None)
c.setFont("Helvetica", 20)
c.drawString(25, 5, "Controlled")
c.setFont("Helvetica", 13)
createdate=(datetime.datetime.now()).strftime("%Y-%m-%d")
c.drawString(35, 30, createdate)
c.setFont("Helvetica", 4)
tag=str(int(time.time())) #给文件加时间戳
c.drawString(5, 65 ,tag)
c.showPage()
c.save()
return tag
def pdf_chop(source,watermark,ID): #合并pdf
reader=PyPDF2.PdfFileReader(open(source,"rb"))
#print("reader",reader)
watermark=PyPDF2.PdfFileReader(open(watermark,"rb"))
#print("watermark",watermark)
writer=PyPDF2.PdfFileWriter()
for i in range( reader.getNumPages()):
page= reader.getPage(i)
page.mergePage(watermark.getPage(0))
writer.addPage(page)
filename=(source.split(".")[0]).split("\\")[-1]
#print("filename",filename)
outputStream=open("pic_chop\\"+filename+"_"+ID+".pdf","wb")
writer.write(outputStream)
outputStream.close()
if __name__ == "__main__":
path=os.getcwd()
rawfie_dir=os.path.join(path,"pic_source")
#print(rawfie_dir)
for i in os.listdir(rawfie_dir):
if i.endswith("pdf"):
ID=create_chop()
sourcefile=os.path.join(rawfie_dir,i)
print("正在编辑原文件:"+sourcefile+"请等待....")
pdf_chop(sourcefile,"stamp.pdf",ID)
print("文件完成")