py --version
查看python环境情况pip install PyPDF2 reportlab Pillow
import os from PyPDF2 import PdfReader, PdfWriter from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter from reportlab.lib import colors from PIL import Image def create_stamp_pdf(stamp_path, output_path, width=None, height=None, x=0, y=0): # 创建一个 PDF 文件 c = canvas.Canvas(output_path, pagesize=letter) # 打开公章图像 stamp_image = Image.open(stamp_path) # 如果没有指定宽度和高度,则使用图像的原始尺寸 if width is None or height is None: width, height = stamp_image.size # 在 PDF 中绘制图像,保持透明背景 c.drawImage(stamp_path, x, y, width=width, height=height, mask='auto') c.save() def add_stamp_to_pdf(pdf_path, stamp_pdf_path, output_path): # 打开 PDF 文件 pdf_reader = PdfReader(pdf_path) pdf_writer = PdfWriter() # 读取公章 PDF stamp_reader = PdfReader(stamp_pdf_path) stamp_page = stamp_reader.pages[0] # 遍历 PDF 的每一页 for page in pdf_reader.pages: # 合并公章页面 page.merge_page(stamp_page) # 将修改后的页面添加到写入器 pdf_writer.add_page(page) # 写入输出 PDF with open(output_path, 'wb') as output_pdf: pdf_writer.write(output_pdf) def process_pdfs_in_folder(folder_path, stamp_path, output_folder, stamp_width=None, stamp_height=None, stamp_x=0, stamp_y=0): if not os.path.exists(output_folder): os.makedirs(output_folder) # 创建临时公章 PDF stamp_pdf_path = "temp_stamp.pdf" create_stamp_pdf(stamp_path, stamp_pdf_path, stamp_width, stamp_height, stamp_x, stamp_y) for filename in os.listdir(folder_path): if filename.endswith('.pdf'): pdf_path = os.path.join(folder_path, filename) output_path = os.path.join(output_folder, f"stamped_{filename}") add_stamp_to_pdf(pdf_path, stamp_pdf_path, output_path) print(f"Processed: {filename}") # 删除临时公章 PDF 文件 os.remove(stamp_pdf_path) if __name__ == "__main__": folder_path = "C:/Users/ZTXD64/Desktop/docks" # 替换为你的 PDF 文件夹路径 stamp_path = "C:/Users/ZTXD64/Desktop/gongzhang/test.png" # 替换为你的公章 PNG 文件路径 output_folder = "C:/Users/ZTXD64/Desktop/done" # 替换为输出文件夹路径 stamp_width = 100 # 替换为你想要的公章宽度 stamp_height = 100 # 替换为你想要的公章高度 stamp_x = 400 # 替换为你想要的公章 X 位置 stamp_y = 365 # 替换为你想要的公章 Y 位置 process_pdfs_in_folder(folder_path, stamp_path, output_folder, stamp_width, stamp_height, stamp_x, stamp_y)
本文作者:ZTXD
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!