Python 3, 2 pieces of code, add watermarks to pdf files. It turns out that watermark can also play like this.

1. Introduction

Little loser: happy new year, brother fish!
Xiaoyu: everything goes to the three treasures hall. If there's anything, just tell me
Little loser: don't be so direct. It's for the new year
Xiaoyu: don't be useless. Just be careful. I don't know.
Loser:

Little loser: despise and despise. As long as you can help me solve the problem, I will despise Sanlian!
Xiaoyu:... It's OK. Let's talk about it. What's up?
Loser: just... Just
Xiaoyu: can you stop honing haw and make it cool immediately!!
Little loser: Yes, can you help me add a watermark to the pdf file
Xiaoyu: that's it
Loser: Yes, that's it!


Xiaoyu: don't make such an innocent and lovely expression.
Loser: who was not a cute girl^
Xiaoyu: I wipe and break the defense. I can't fix it!
Loser: ness ~~

Today, let's share how to add watermarks to pdf documents.
Xiaoyu shared the method of adding watermark to the picture. It's very simple. It's directly added to the watermark module_ Watermark can,

If you don't know, you can read this article< Python 3, 2 lines of code, add watermark, send a circle of friends, and the picture will no longer be afraid of being stolen!!!>

However, adding watermarks to pdf files requires two other libraries, namely:

  • reportlab
  • pikepdf

What are the special "magic" of these two libraries that can add watermarks to pdf?
Don't go away, come back later!

2. Specifies that the watermark content is output to a pdf file

2.1 module installation

Because the reportlab library is the third-party library of python, so,
Step 1: installation:

pip install reportlab

Other installation methods:

<Python 3, choose Python to automatically install the third-party library, and then say goodbye to pip!!>
<Python 3: I import all Python libraries with only one line of low-key code!!>

2.2 ideas

1. To set watermark font fill:
Therefore, we need to set some basic information for the font, such as:

  • Content: watermark text content
  • filename: the name of the exported watermark file
  • Width: Canvas width, unit: mm
  • Height: Canvas height, unit: mm
  • Font: the corresponding registered font code
  • fontsize: font size
  • Angle: rotation angle
  • text_stroke_color_rgb: text outline rgb color
  • text_fill_color_rgb: text fill color
  • text_fill_alpha: text transparency

2. Output watermark font to pdf document
canvas. Canvas. The save () method saves the output font to the pdf document

2.3 code examples

Direct code:

# -*- coding:utf-8 -*-
# @Time   : 2022-02-10
# @Author : carl_DJ


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

pdfmetrics.registerFont(TTFont('msyh',r'./msyh.ttc'))

'''

Used to generate include content Watermark of text content pdf file

content: Watermark text content
filename: Exported watermark file name
width: Canvas width, unit: mm
height: Canvas height, unit: mm
font: Corresponding registered font code
fontsize: Font size
angle: Rotation angle
text_stroke_color_rgb: Text outline rgb colour
text_fill_color_rgb: Text fill rgb colour
text_fill_alpha: Text transparency


'''

def create_wartmark(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:


    #Create a PDF file and specify the file name and size in pixels
    c = canvas.Canvas(f'{filename}.pdf',pagesize=(width*units.mm,height*units.mm))

    #Canvas translation ensures text integrity
    c.translate(0.1*width*units.mm,0.1*height*units.mm)

    #Set rotation angle
    c.rotate(angle)

    #Set font size
    c.setFont(font,fontsize)

    #Set font outline color
    c.setStrokeColorRGB(*text_stroke_color_rgb)

    #Set fill color
    c.setFillColorRGB(*text_fill_color_rgb)

    #Set font transparency
    c.setFillAlpha(text_fill_alpha)

    #Draw font content
    c.drawString(0,0,content)

    #Save file

    c.save()

@[TOC](pdf add to watermark)
# 1. Introduction
**Little loser**: Happy new year, brother fish!
**Small fish**: You can't go to the three treasures hall without doing anything. If you have anything, just tell me...
**Little loser**: Don't be so direct. It's the occasion of the Chinese New Year...
**Small fish**: If you don't know, don't worry.
**Little loser**: .....
![Insert picture description here](https://img-blog.csdnimg.cn/25dcb96f0f0e4f42b16b90d5c27b191b.png#pic_center)
**Little loser**: Despise me, as long as you can help me!
**Small fish**: ....It's OK. Let's talk about it. What's up?
**Little loser**: namely..namely...
**Small fish**: Can't you stop honing haw and make a cold start!!
**Little loser**: Yes, can you give it to me pdf Add a watermark to the file...
**Small fish**: That's it....
**Little loser**: Yes, that's it!

![Insert picture description here](https://img-blog.csdnimg.cn/d9b81942767e4736a6f35ccc9b673577.gif#pic_center)
**Small fish**: Don't make such an innocent and lovely expression.
**Little loser**: Who was not a little cute ^ ^ 
**Small fish**: I wipe and break the defense. I can't fix it!
**Little loser**: NAIS ~  ~

Let's share today pdf How to add watermarks to documents.
Xiaoyu shared the method of adding watermark to the picture, which is very simple and direct watermark Modular add_watermark Can,


>If you don't know, you can read this article<[**Python3,2 Add watermark in line code, send a circle of friends, and the picture will no longer be afraid of being stolen!!!**](https://blog.csdn.net/wuyoudeyuer/article/details/120957311)>

But, pdf To add a watermark to a file, you need to use two other libraries, namely:
 - reportlab
 - pikepdf

What's special about these two libraries"magic",Can give pdf Add watermark?
Don't go away, come back later!

# 2. Specifies that the watermark content is output to a pdf file
## 2.1 module installation
 because reportlab Library is python Third party libraries, so,
Step 1: installation:

```powershell
pip install reportlab

Other installation methods:

<Python 3, choose Python to automatically install the third-party library, and then say goodbye to pip!!>
<Python 3: I import all Python libraries with only one line of low-key code!!>

2.2 ideas

1. To set watermark font fill:
Therefore, we need to set some basic information for the font, such as:

  • Content: watermark text content
  • filename: the name of the exported watermark file
  • Width: Canvas width, unit: mm
  • Height: Canvas height, unit: mm
  • Font: the corresponding registered font code
  • fontsize: font size
  • Angle: rotation angle
  • text_stroke_color_rgb: text outline rgb color
  • text_fill_color_rgb: text fill color
  • text_fill_alpha: text transparency

2. Output watermark font to pdf document
canvas. Canvas. The save () method saves the output font to the pdf document

2.3 code examples

Direct code:

# -*- coding:utf-8 -*-
# @Time   : 2022-02-10
# @Author : carl_DJ


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

pdfmetrics.registerFont(TTFont('msyh',r'./msyh.ttc'))

'''

Used to generate include content Watermark of text content pdf file

content: Watermark text content
filename: Exported watermark file name
width: Canvas width, unit: mm
height: Canvas height, unit: mm
font: Corresponding registered font code
fontsize: Font size
angle: Rotation angle
text_stroke_color_rgb: Text outline rgb colour
text_fill_color_rgb: Text fill rgb colour
text_fill_alpha: Text transparency


'''

def create_wartmark(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:


    #Create a PDF file and specify the file name and size in pixels
    c = canvas.Canvas(f'{filename}.pdf',pagesize=(width*units.mm,height*units.mm))

    #Canvas translation ensures text integrity
    c.translate(0.1*width*units.mm,0.1*height*units.mm)

    #Set rotation angle
    c.rotate(angle)

    #Set font size
    c.setFont(font,fontsize)

    #Set font outline color
    c.setStrokeColorRGB(*text_stroke_color_rgb)

    #Set fill color
    c.setFillColorRGB(*text_fill_color_rgb)

    #Set font transparency
    c.setFillAlpha(text_fill_alpha)

    #Draw font content
    c.drawString(0,0,content)

    #Save file

    c.save()
    
create_wartmark(content='follow carl_Yiran, learn more interesting python knowledge',
                 filename='Small fish watermarkDemo',
                 width=200,
                 height=200,
                 font='msyh',
                 fontsize=35,
                 text_fill_alpha=0.3) 
    

Operation results:

3. Batch output of watermark content to pdf file

3.1 module installation

Because pikepdf library is the third-party library of python, so,
Step 1: installation:

pip install pikepdf

Other installation methods:

<Python 3, choose Python to automatically install the third-party library, and then say goodbye to pip!!>
<Python 3: I import all Python libraries with only one line of low-key code!!>

Little loser: brother fish, why do we need to install pikepdf?
Xiaoyu: because we want to cover the generated pdf watermark to the target pdf document.
Little loser: you mean, the above code just generates a watermark document, and there's nothing else?
Xiaoyu: Yes, you can use the pdf watermark document generated above, or you can find a pdf document as a watermark document to cover the target pdf document.
Loser: can you still play like this?
Xiaoyu: Yes, I'll show you later.

3.2 ideas

1. pdf files need to be prepared:

  • Target pdf file
  • pdf file with watermark generated

2. We overwrite the generated pdf document with the target pdf document. Similarly, the parameters to be set:

  • target_pdf_path: target PDF file path + file name
  • watermark_pad_path: watermark pdf file path + file name
  • nrow: number of rows of watermark tiles
  • ncol: number of columns of watermark tile
  • skip_pages: the number of pages without watermark needs to be skipped

Target pdf document:

When the above two are ready, start the whole code.

3.3 code example

# -*- coding:utf-8 -*-
# @Time   : 2022-02-10
# @Author : carl_DJ


from typing import List
from pikepdf import Pdf,Page,Rectangle


'''
To target pdf Add watermark to files in batch
target_pdf_path:target pdf File path+file name
watermark_pad_path:watermark pdf File path+file name
nrow:Number of watermark tiles
ncol:Number of watermark tiled columns
skip_pages:Need to skip pages without watermark

'''

def add_watemark(target_pdf_path:str,
                 watermark_pdf_path:str,
                 nrow:int,
                 ncol:int,
                 skip_pages:List[int] = []) -> None:

    #Select the pdf file that needs to be watermarked
    target_pdf = Pdf.open(target_pdf_path)

    #Read the watermark pdf file and extract the watermark
    watermark_pdf = Pdf.open(watermark_pdf_path)
    watermark_page = watermark_pdf.pages[0]

    #Traverse all pages in the target pdf file and add watermarks in batches
    for idx,target_page in enumerate(target_pdf.pages):
        for x in range(ncol):
            for y in range(nrow):
                #Adds a watermark to the specified range of the target page
                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
                                        ))
    #Save the PDF file, rename the PDF file at the same time, and write the suffix from the 7th position of the file name
    target_pdf.save(target_pdf_path[:6] + '_Watermark added.pdf')


add_watemark(target_pdf_path='Learn watermark from small fish.pdf',
             #Add the generated watermark example to the target watermark file
             watermark_pdf_path='Small fish watermarkDemo.pdf',
             nrow = 3,
             ncol = 2 ,
             skip_pages= [0])

Operation results:

4. Summary

Writing here, today's sharing is almost over.
Today, we mainly expand the reportlab library and pikepdf library to add watermarks without spending money.

follow Small fish Blog, learn more and more interesting python knowledge.

Keywords: Python

Added by siesmith on Fri, 11 Feb 2022 18:37:10 +0200