Add PDF watermark using PyMuPDF

A blog post on Adding PDF Watermarks Using Python.
C:\pythoncode\new\pdfwatermark.py
insert image description here
insert image description here

Add watermark to PDF using Python

In our daily work, we often need to process PDF files. One of the common needs is to add a watermark to a PDF file to protect the copyright of the file or to identify the source of the file. This article will introduce how to add watermark to PDF files using Python programming language and PyMuPDF library.

Preparation

Before starting, make sure the following components are installed:

  • Python programming environment
  • PyMuPDF library

The PyMuPDF library can be installed using the pip command:


pip install PyMuPDF

Write code

First, we need to import the required libraries:

import fitz

Next, we create a function to add a watermark to each page of the PDF file:

def add_watermark_to_pdf(pdf_path, watermark_text, output_path):
    try:
        doc = fitz.open(pdf_path)
        watermark_text = str(watermark_text)

        for page in doc:
            textbox = fitz.Rect(100, 100, 300, 200)  # 设置水印的位置和大小
            page.insert_textbox(textbox, watermark_text, fontsize=20, rotate=90)

        doc.save(output_path)
        doc.close()

        print("水印添加成功!")
    except Exception as e:
        print("添加水印时出错:", str(e))

In the above code, we open the PDF file, iterate over each page, and then use insert_textbox()the method to add the watermark to each page.

Example of use

Next, we can use the above function to add the watermark.

pdf_path = "input.pdf"
watermark_text = "我的水印"
output_path = "output.pdf"

add_watermark_to_pdf(pdf_path, watermark_text, output_path)

In the above example, we specified the path to the input PDF file, the watermark text to add, and the path to the output file. After running the code, a PDF file with a watermark will be generated in the output path.

all codes

import wx
import fitz

class WatermarkFrame(wx.Frame):
    def __init__(self, parent, title):
        super(WatermarkFrame, self).__init__(parent, title=title, size=(400, 200))
        
        panel = wx.Panel(self)
        
        # 创建选择文件按钮
        self.file_picker = wx.FilePickerCtrl(panel, style=wx.FLP_OPEN)
        
        # 创建水印文本输入框
        self.watermark_text = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER)
        
        # 创建保存文件夹按钮
        self.save_folder_picker = wx.DirPickerCtrl(panel, style=wx.DIRP_USE_TEXTCTRL)
        
        # 创建生成按钮
        generate_button = wx.Button(panel, label='生成')
        generate_button.Bind(wx.EVT_BUTTON, self.on_generate_button_click)
        
        # 创建布局
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.file_picker, proportion=0, flag=wx.ALL|wx.EXPAND, border=10)
        sizer.Add(self.watermark_text, proportion=0, flag=wx.ALL|wx.EXPAND, border=10)
        sizer.Add(self.save_folder_picker, proportion=0, flag=wx.ALL|wx.EXPAND, border=10)
        sizer.Add(generate_button, proportion=0, flag=wx.ALL|wx.CENTER, border=10)
        panel.SetSizer(sizer)
        
    def on_generate_button_click(self, event):
        file_path = self.file_picker.GetPath()
        watermark_text = self.watermark_text.GetValue()
        save_folder = self.save_folder_picker.GetPath()
        
        if file_path and watermark_text and save_folder:
            try:
                doc = fitz.open(file_path)
                # watermark_text = watermark_text.encode('utf-8')
                watermark_text = str(watermark_text)
                
                for page in doc:
                    textbox = fitz.Rect(100, 100, 300, 200)  # 水印的位置和大小
                    # page.insert_textbox(textbox, watermark_text, fontsize=20, rotate=45)
                    page.insert_textbox(textbox, watermark_text, fontsize=20, rotate=90)
                    
                # output_file_path = f"{save_folder}/watermarked_{file_path.split('/')[-1]}"
                output_file_path = f"outputwatermark.pdf"
                doc.save(output_file_path)
                doc.close()
                
                wx.MessageBox("水印添加成功!", "成功", wx.OK | wx.ICON_INFORMATION)
                
            except Exception as e:
                wx.MessageBox(str(e), "错误", wx.OK | wx.ICON_ERROR)
        
        else:
            wx.MessageBox("请选择文件、输入水印文本和保存文件夹!", "错误", wx.OK | wx.ICON_ERROR)

if __name__ == '__main__':
    app = wx.App()
    frame = WatermarkFrame(None, "添加水印")
    frame.Show()
    app.MainLoop()

Summarize

By using Python and the PyMuPDF library, we can easily add watermarks to PDF files. The position, size and rotation angle of the watermark can be customized according to requirements. This method is not only simple and efficient, but also can automate the processing of a large number of PDF files.

Guess you like

Origin blog.csdn.net/winniezhang/article/details/132400515