Image watermarks are frequently found on shared documents. Unlike text watermarks, image watermarks provide a simpler and less intrusive way to emphasize copyright, ownership, and confidentiality by displaying company logos, trademarks, warning icons, etc. In addition, adding image watermarks to PDF documents can also help brand promotion and enhance the visual appeal of the documents. This article will explain how to insert image watermarks to PDF documents using Spire.PDF for Python in Python programs.

Install Spire.PDF for Python

This scenario requires Spire.PDF for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip commands.

pip install Spire.PDF

If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python on Windows

Add Single Image Watermarks to PDF Documents

Single image watermarks are transparent images at the center of PDF pages. With Spire.PDF for Python, users can draw a specified image as a watermark on any PDF page. The detailed steps are as follows:

  • Create an object of PdfDocument class.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Load the watermark image using PdfImage.FromFile() method.
  • Loop through the pages in the document to add the watermark.
  • Get a page using PdfDocument.Pages.get_Item() method.
  • Set the transparency of the watermark using PdfPageBase.Canvas.SetTransparency() method.
  • Draw the watermark image in the center of the page using PdfPageBase.Canvas.DrawImage() method.
  • Save the document using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf import *
from spire.pdf.common import *

# Create an object of PdfDocument class
pdf = PdfDocument()

# Load a PDF document
pdf.LoadFromFile("Sample.pdf")

# Load the watermark image
image = PdfImage.FromFile("watermark.png")

# Get the width and height of the image
imageWidth = float(image.Width)
imageHeight = float(image.Height)

# Loop through the pages in the document
for i in range(pdf.Pages.Count):
    # Get a page
    page = pdf.Pages.get_Item(i)
    # Set the transparency of the watermark
    page.Canvas.SetTransparency(0.3)
    # Get the width and height of the page
    pageWidth = page.ActualSize.Width
    pageHeight = page.ActualSize.Height
    # Draw the watermark image on the page
    page.Canvas.DrawImage(image, pageWidth/2 - imageWidth/2, pageHeight/2 - imageHeight/2, imageWidth, imageHeight)

# Save the document
pdf.SaveToFile("output/SingleImageWatermark.pdf")
pdf.Close()

Python: Add Image Watermarks to PDF Documents

Add Repeating Image Watermarks to PDF Documents

Repeating image watermarks are images repeated regularly on PDF pages. Drawing repeated image watermarks on PDF pages with Spire.PDF for Python involves the use of the PdfTillingBrush class. Below are the detailed steps:

  • Create an object of PdfDocument class.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Load the watermark image using PdfImage.FromFile() method.
  • Loop through the pages in the document to add the watermark.
  • Get a page using PdfDocument.Pages.get_Item() method.
  • Create an object of PdfTilingBrush class and set its size to determine the number of repetitions of the watermark.
  • Set the transparency of the watermark using PdfTillingBrush.Graphics.SetTransparency() method.
  • Translate the coordinate system to the specified position using PdfTillingBrush.Graphics.TranslateTransform() method to make the watermark displayed in the center of each repetition.
  • Draw the watermark image on the tilling brush using PdfTillingBrush.Graphics.DrawImage() method.
  • Draw the watermark on the page using PdfPageBase.Canvas.DrawRectangle() method.
  • Save the document using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create an object of PdfDocument class
pdf = PdfDocument()

# Load a PDF document
pdf.LoadFromFile("Sample.pdf")

# Load the watermark image
image = PdfImage.FromFile("watermark.png")

# Loop through the pages of the document
for i in range(pdf.Pages.Count):
    # Get a page
    page = pdf.Pages.get_Item(i)
    # Create an object of PdfTilingBrush class and set its size
    brush = PdfTilingBrush(SizeF(page.Canvas.Size.Width / float(3), page.Canvas.Size.Height / float(3)))
    # Set the transparency of the watermark
    brush.Graphics.SetTransparency(0.3)
    brush.Graphics.Save()
    # Translate the coordinate to the specified position
    brush.Graphics.TranslateTransform(brush.Size.Width/2 - image.Width/2, brush.Size.Height/2 - image.Height/2)
    # Draw the watermark image on the brush
    brush.Graphics.DrawImage(image, 0.0, 0.0, float(image.Width), float(image.Height))
    brush.Graphics.Restore()
    # Draw the watermark on the page
    page.Canvas.DrawRectangle(brush, RectangleF(PointF(0.0, 0.0), page.Canvas.Size))

# Save the PDF document
pdf.SaveToFile("output/RepeatingImageWatermark.pdf", FileFormat.PDF)
pdf.Close()

Python: Add Image Watermarks to PDF Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Python: Add Headers and Footers to Excel

2023-10-19 06:51:56 Written by Koohji

Headers and footers are areas located at the top and bottom of each page in a document, used to add additional information or elements. Headers typically include document titles, company names, dates, and other information, while footers often contain page numbers, file paths, copyright statements, and other details. By setting headers and footers in Excel, documents can be made more professional and organized. In this article, we will show you how to add headers and footers to Excel by using Spire.XLS for Python.

Spire.XLS for Python provides the PageSetup class to work with the page setup in Excel including headers and footers. Specifically, it contains LeftHeader property, CenterHeader property, RightHeader property, LeftFooter property, etc. to represent the left section, center section and right section of a header or footer. To add fields to headers or footers, or to apply formatting to text, you'll need to use the scripts listed in the following table.

Script Description
&P The current page numbers.
&N The total number of pages.
&D The current data.
&T The current time.
&G A picture.
&A The worksheet name.
&F The file name.
&B Make text bold.
&I Italicize text.
&U Underline text.
&"font name" Represents a font name, for example, &"Arial".
& + Integer Represents font size, for example, &12.
&K + Hex color code Represents font color, for example, &KFF0000.

Install Spire.XLS for Python

This scenario requires Spire.XLS for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.XLS

If you are unsure how to install, please refer to this tutorial: How to Install Spire.XLS for Python on Windows

Add Text to the Header or Footer in Excel

Spire.XLS for Python allows you to add formatted text to the certain section of the header or footer. In this way, you can set different elements in Excel, such as file titles, page numbers or date. Here are the detailed steps.

  • Create an object of Workbook class.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get the specific worksheet by Workbook.Worksheets[index] property.
  • Add text to the left header by setting PageSetup.LeftHeader property as you like.
  • Add page number to the center footer by setting PageSetup.CenterFooter property to &P.
  • Add the current date to the right footer by setting PageSetup.RightFooter property to &D.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "sample.xlsx"
outputFile = "TextHeaderFooter.xlsx"

#Create an object of Workbook class
workbook = Workbook()

#Load a sample file from disk
workbook.LoadFromFile(inputFile)

#Get the first worksheet of this file
Worksheet = workbook.Worksheets[0]

#Add text to the left header
Worksheet.PageSetup.LeftHeader = "&\"Calibri\"&14 Sales Volume"

#Add page number to the center footer 
Worksheet.PageSetup.CenterFooter = "&P"

#Add the current date to the right footer
Worksheet.PageSetup.RightFooter = "&D"

#Set the view mode of the sheet
Worksheet.ViewMode = ViewMode.Layout

#Save the result file
workbook.SaveToFile(outputFile, ExcelVersion.Version2010)
workbook.Dispose()

Python: Add Headers and Footers to Excel

Add Images to the Header or Footer in Excel

What's more, Spire.XLS for Python also supports adding images to the header or footer. The following are detailed steps.

  • Create an object of Workbook class.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get the specific worksheet by Workbook.Worksheets[index] property.
  • Load an image and set it as the image source of the left header by PageSetup.LeftHeaderImage property.
  • Display the image in the left header section by setting PageSetup.LeftHeader property to “&G”.
  • Set it as the image source of the center footer by PageSetup.CenterFooterImage property.
  • Display the image in the center footer section by setting PageSetup.CenterFooter property to “&G”.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.common import *

inputFile = "sample.xlsx"
inputImage = "Logo.png"
outputFile = "ImageHeaderFooter.xlsx"

#Create an object of workbook class
workbook = Workbook()

#Load a sample file from disk
workbook.LoadFromFile(inputFile)

#Get the first sheet of this file
sheet = workbook.Worksheets[0]

#Load an image from disk
image = Image.FromFile(inputImage)

#Add the image to the left header
sheet.PageSetup.LeftHeaderImage = image
sheet.PageSetup.LeftHeader = "&G"

#Add the image to the center footer
sheet.PageSetup.CenterFooterImage = image
sheet.PageSetup.CenterFooter = "&G"

#Set the view mode of the sheet
sheet.ViewMode = ViewMode.Layout

#Save the result file
workbook.SaveToFile(outputFile, ExcelVersion.Version2010)
workbook.Dispose()

Python: Add Headers and Footers to Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Python Add watermarks to PDF

Watermarking is a critical technique for securing documents, indicating ownership, and preventing unauthorized copying. Whether you're distributing drafts or branding final deliverables, applying watermarks helps protect your content effectively. In this tutorial, you’ll learn how to add watermarks to a PDF in Python using the powerful and easy-to-use Spire.PDF for Python library.

We'll walk through how to insert both text and image watermarks , handle transparency and positioning, and resolve common issues — all with clean, well-documented code examples.

Table of Contents:

Python Library for Watermarking PDFs

Spire.PDF for Python is a robust library that provides comprehensive PDF manipulation capabilities. For watermarking specifically, it offers:

  • High precision in watermark placement and rotation.
  • Flexible transparency controls.
  • Support for both text and image watermarks.
  • Ability to apply watermarks to specific pages or entire documents.
  • Preservation of original PDF quality.

Before proceeding, ensure you have Spire.PDF installed in your Python environment:

pip install spire.pdf

Adding a Text Watermark to a PDF

This code snippet demonstrates how to add a diagonal "DO NOT COPY" watermark to each page of a PDF file. It manages the size, color, positioning, rotation, and transparency of the watermark for a professional result.

from spire.pdf import *
from spire.pdf.common import *
import math

# Create an object of PdfDocument class
doc = PdfDocument()

# Load a PDF document from the specified path
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf")

# Create an object of PdfTrueTypeFont class for the watermark font
font = PdfTrueTypeFont("Times New Roman", 48.0, 0, True)

# Specify the watermark text
text = "DO NOT COPY"

# Measure the dimensions of the text to ensure proper positioning
text_width = font.MeasureString(text).Width
text_height = font.MeasureString(text).Height

# Loop through each page in the document
for i in range(doc.Pages.Count):

    # Get the current page
    page = doc.Pages.get_Item(i)
    
    # Save the current canvas state
    state = page.Canvas.Save()
 
    # Calculate the center coordinates of the page
    x = page.Canvas.Size.Width  / 2
    y = page.Canvas.Size.Height / 2

    # Translate the coodinate system to the center so that the center of the page becomes the origin (0, 0)
    page.Canvas.TranslateTransform(x, y)
    
    # Rotate the canvas 45 degrees counterclockwise for the watermark
    page.Canvas.RotateTransform(-45.0)

    # Set the transparency of the watermark
    page.Canvas.SetTransparency(0.7)
    
    # Draw the watermark text at the centered position using negative offsets 
    page.Canvas.DrawString(text, font, PdfBrushes.get_Blue(), PointF(-text_width / 2, -text_height / 2))
    
    # Restore the canvas state to prevent transformations from affecting subsequent drawings
    page.Canvas.Restore(state)

# Save the modified document to a new PDF file
doc.SaveToFile("output/TextWatermark.pdf")

# Dispose resources
doc.Dispose()

Breakdown of the Code :

  1. Load the PDF Document : The script loads an input PDF file from a specified path using the PdfDocument class.
  2. Configure Watermark Text : A watermark text ("DO NOT COPY") is set with a specific font (Times New Roman, 48pt) and measured for accurate positioning.
  3. Apply Transformations : For each page, the script:
    • Centers the coordinate system.
    • Rotates the canvas by 45 degrees counterclockwise.
    • Sets transparency (70%) for the watermark.
  4. Draw the Watermark : The text is drawn at (-text_width / 2, -text_height / 2), which aligns the text perfectly around the center point of the page, regardless of the rotation applied.
  5. Save the Document : The modified document is saved to a new PDF file.

Output:

Add a text watermark to PDF

Adding an Image Watermark to a PDF

This code snippet adds a semi-transparent image watermark to each page of a PDF, ensuring proper positioning and a professional appearance.

from spire.pdf import *
from spire.pdf.common import *

# Create an object of PdfDocument class
doc = PdfDocument()

# Load a PDF document from the specified path
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf")

# Load the watermark image from the specified path
image = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\logo.png")

# Get the width and height of the loaded image for positioning
imageWidth = float(image.Width)
imageHeight = float(image.Height)

# Loop through each page in the document to apply the watermark
for i in range(doc.Pages.Count):
    # Get the current page
    page = doc.Pages.get_Item(i)

    # Set the transparency of the watermark to 50%
    page.Canvas.SetTransparency(0.5)

    # Get the dimensions of the current page
    pageWidth = page.ActualSize.Width
    pageHeight = page.ActualSize.Height

    # Calculate the x and y coordinates to center the image on the page
    x = (pageWidth - imageWidth) / 2
    y = (pageHeight - imageHeight) / 2

    # Draw the image at the calculated center position on the page
    page.Canvas.DrawImage(image, x, y, imageWidth, imageHeight)

# Save the modified document to a new PDF file
doc.SaveToFile("output/ImageWatermark.pdf")

# Dispose resources
doc.Dispose()

Breakdown of the Code :

  1. Load the PDF Document : The script loads an input PDFfile from a specified path using the PdfDocument class.
  2. Configure Watermark Image : The watermark image is loaded from a specified path, and its dimensions are retrieved for accurate positioning.
  3. Apply Transformations : For each page, the script:
    • Sets the watermark transparency (50%).
    • Calculates the center position of the page for the watermark.
  4. Draw the Watermark : The image is drawn at the calculated center coordinates, ensuring it is centered on each page.
  5. Save the Document : The modified document is saved to a new PDF file.

Output:

Add an image watermark to PDF

Apart from watermarks, you can also add stamps to PDFs. Unlike watermarks, which are fixed in place, stamps can be freely moved or deleted, offering greater flexibility in document annotation.

Troubleshooting Common Issues

  1. Watermark Not Appearing :
    • Verify file paths are correct.
    • Check transparency isn't set to 0 (fully transparent).
    • Ensure coordinates place the watermark within page bounds.
  2. Quality Issues :
    • For text, use higher-quality fonts.
    • For images, ensure adequate resolution.
  3. Rotation Problems :
    • Remember that rotation occurs around the current origin point.
    • The order of transformations matters (translate then rotate).

Wrapping Up

With Spire.PDF for Python, adding watermarks to PDF documents becomes a simple and powerful process. Whether you need bold "Confidential" text across every page or subtle branding with logos, the library handles it all efficiently. By combining coordinate transformations, transparency settings, and drawing commands, you can create highly customized watermarking workflows tailored to your document's purpose.

FAQs

Q1. Can I add both text and image watermarks to the same PDF?

Yes, you can combine both approaches in a single loop over the PDF pages.

Q2. How can I rotate image watermarks?

Use Canvas.RotateTransform(angle) before drawing the image, similar to the text watermark example.

Q3. Does Spire.PDF support transparent PNGs for watermarks?

Yes, Spire.PDF preserves the transparency of PNG images when used as watermarks.

Q4. Can I apply different watermarks to different pages?

Absolutely. You can implement conditional logic within your page loop to apply different watermarks based on page number or other criteria.

Get a Free License

To fully experience the capabilities of Spire.PDF for Python without any evaluation limitations, you can request a free 30-day trial license.

page 70