本文完整示例代碼及檔案已上傳至我的 Github
倉庫https://github.com/CNFeffery/PythonPracticalSkills
這是我的系列文章「Python實用秘技」的第4期,本系列立足于筆者日常工作中使用
Python
積累的心得體會,每一期為大家帶來一個3分鐘即可學會的簡單小技巧。
作為系列第4期,我們即将學習的是:
為pdf檔案批量添加文字水印
。

有些情況下我們需要為單個或多個
pdf
檔案添加文字水印,尤其是那種需要在每一頁按照一定間距鋪滿的文字水印。而借助
reportlab
和
pikepdf
這兩個實用的
pdf
檔案操作庫,我們就可以很友善地實作批量文字水印添加工作。
利用
pip install reportlab pikepdf
完成安裝後,我們就可以按照步驟來實作需要的功能:
- 生成指定的文本水印pdf檔案
為了向目标
pdf
檔案添加水印,我們首先需要有單獨的
pdf
格式的文本水印檔案,我用
reportlab
編寫了一個友善易用的函數來生成水印檔案,你可以通過注釋來仔細學習其中的步驟,也可以直接調用即可:
from typing import Union, Tuple
from reportlab.lib import units
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
# 注冊字型,這裡的字型是我從windows的字型目錄下複制過來的
pdfmetrics.registerFont(TTFont('msyh', r'./msyh.ttc'))
def create_watermark(content: str,
filename: str,
width: Union[int, float],
height: Union[int, float],
font: str,
fontsize: int,
angle: Union[int, float] = 45,
text_stroke_color_rgb: Tuple[int, int, int] = (0, 0, 0),
text_fill_color_rgb: Tuple[int, int, int] = (0, 0, 0),
text_fill_alpha: Union[int, float] = 1) -> None:
'''
用于生成包含content文字内容的水印pdf檔案
content: 水印文本内容
filename: 導出的水印檔案名
width: 畫布寬度,機關:mm
height: 畫布高度,機關:mm
font: 對應注冊的字型代号
fontsize: 字号大小
angle: 旋轉角度
text_stroke_color_rgb: 文字輪廓rgb色
text_fill_color_rgb: 文字填充rgb色
text_fill_alpha: 文字透明度
'''
# 建立pdf檔案,指定檔案名及尺寸,這裡以像素機關為例
c = canvas.Canvas(f"{filename}.pdf", pagesize = (width*units.mm, height*units.mm))
# 進行輕微的畫布平移保證文字的完整
c.translate(0.1*width*units.mm, 0.1*height*units.mm)
# 設定旋轉角度
c.rotate(angle)
# 設定字型及字号大小
c.setFont(font, fontsize)
# 設定文字輪廓色彩
c.setStrokeColorRGB(*text_stroke_color_rgb)
# 設定文字填充色
c.setFillColorRGB(*text_fill_color_rgb)
# 設定文字填充色透明度
c.setFillAlpha(text_fill_alpha)
# 繪制文字内容
c.drawString(0, 0, content)
# 儲存水印pdf檔案
c.save()
下面我們就利用這個函數來生成水印檔案:
# 制造示例文字水印pdf檔案
create_watermark(content='公衆号【Python大資料分析】作者:費弗裡',
filename='水印示例',
width=200,
height=200,
font='msyh',
fontsize=35,
text_fill_alpha=0.3)
看看效果,非常的不錯,具體使用時,你可以自己動手調參以找到大小以及畫幅都令你滿意的水印導出結果:
- 将水印檔案批量覆寫到目标pdf檔案中
搞定了文本水印檔案的生成之後,接下來我們就可以把現成的水印檔案插入到目标
pdf
檔案中,這裡我們使用
pikepdf
中的相關功能就可以輕松實作,我寫了一個簡單的函數,大家在調用時隻需要傳入幾個必要參數即可:
from typing import List
from pikepdf import Pdf, Page, Rectangle
def add_watermark(target_pdf_path: str,
watermark_pdf_path: str,
nrow: int,
ncol: int,
skip_pages: List[int] = []) -> None:
'''
向目标pdf檔案中添加平鋪水印
target_pdf_path: 目标pdf檔案的路徑+檔案名
watermark_pdf_path: 水印pdf檔案的路徑+檔案名
nrow: 水印平鋪的行數
ncol:水印平鋪的列數
skip_pages: 需要跳過不添加水印的頁面序号(從0開始)
'''
# 讀入需要添加水印的pdf檔案
target_pdf = Pdf.open(target_pdf_path)
# 讀入水印pdf檔案并提取水印頁
watermark_pdf = Pdf.open(watermark_pdf_path)
watermark_page = watermark_pdf.pages[0]
# 周遊目标pdf檔案中的所有頁(排除skip_pages指定的若幹頁)
for idx, target_page in enumerate(target_pdf.pages):
if idx not in skip_pages:
for x in range(ncol):
for y in range(nrow):
# 向目标頁指定範圍添加水印
target_page.add_overlay(watermark_page, Rectangle(target_page.trimbox[2] * x / ncol,
target_page.trimbox[3] * y / nrow,
target_page.trimbox[2] * (x + 1) / ncol,
target_page.trimbox[3] * (y + 1) / nrow))
# 将添加完水印後的結果儲存為新的pdf
target_pdf.save(target_pdf_path[:-4]+'_已添加水印.pdf')
下面我們直接調用這個函數,對示例檔案
【吳恩達】機器學習訓練秘籍-中文版.pdf
中除了封面以外的每一頁,按照3行2列的平鋪密度,添加上我們的示例水印:
add_watermark(target_pdf_path='./【吳恩達】機器學習訓練秘籍-中文版.pdf',
watermark_pdf_path='./水印示例.pdf',
nrow=3,
ncol=2,
skip_pages=[0])
效果杠杠的,讀者朋友們可以自己多試試,得到更多心得體會~
本期分享結束,咱們下回見~👋