DEV Community

jelizaveta
jelizaveta

Posted on

Easily Add Background Color or Image to PDFs Using Python

Adding a background color or image to PDF files is a common task in office work and document processing, whether to enhance visual appearance or highlight important content. This article demonstrates how to use a free PDF library to add both background colors and background images to PDFs with just a few lines of code.

Preparation

First, install the Free Spire.PDF for Python library. Open a command-line terminal and run:

pip install spire.pdf.free
Enter fullscreen mode Exit fullscreen mode

After installation, you can start writing code. Note that Free Spire.PDF is the free version and has a page limit (up to 10 pages per document). This is usually sufficient for everyday small-scale document processing.

Add a Background Color to a PDF

Adding a background color to a PDF is very simple. Iterate through each page of the PDF and set its BackgroundColor property. Here is a complete example:

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

# Create a PdfDocument object
doc = PdfDocument()

# Load the PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.pdf")

# Iterate through all pages in the document
for i in range(doc.Pages.Count):
    # Get the current page
    page = doc.Pages.get_Item(i)

    # Set the background color to light green
    page.BackgroundColor = Color.get_LightGreen()

# Save the document
doc.SaveToFile("output.pdf")
Enter fullscreen mode Exit fullscreen mode

Key Code Explanation

  • Create the document object: PdfDocument() instantiates a PDF document object on which all subsequent operations are based.
  • Load the source file: LoadFromFile() loads the PDF file to be processed; the argument is the file path.
  • Iterate pages: Use doc.Pages.Count to get the total number of pages and loop through each page.
  • Set background color: The page.BackgroundColor property sets the background color for the current page. Color.get_LightGreen() returns a light green color object. The Color class offers many predefined colors such as get_LightBlue(), get_LightYellow(), get_Pink(), etc., which you can choose as needed.
  • Save the file: SaveToFile() saves the modified document to the specified path.

Add a Background Image to a PDF

If you want to add a background image to a PDF, use the BackgroundImage property. The code is as follows:

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

# Create a PdfDocument object
doc = PdfDocument()

# Load the PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.pdf")

# Load the image
image = Stream("C:\\Users\\Administrator\\Desktop\\img.jpg")

# Iterate through all pages in the document
for i in range(doc.Pages.Count):
    # Get the current page
    page = doc.Pages.get_Item(i)

    # Set the background image
    page.BackgroundImage = image

# Save the document
doc.SaveToFile("output.pdf")
Enter fullscreen mode Exit fullscreen mode

Key Code Explanation

  • Create and load: As with adding a background color, first create a PdfDocument object and load the target PDF file.
  • Iterate pages: Loop through every page so that the same background image is applied to all pages.
  • Set the background image: The page.BackgroundImage property accepts a Stream object; pass the image file path to create the image stream. Common formats such as JPG, PNG, BMP are supported. After setting, the image will automatically scale to fill the entire page as the background.
  • Save the result: Finally, save the processed document as a new file; the original file remains unchanged.

Notes and Tips

  • Path format: On Windows, use double backslashes \ or a raw string r"..." for file paths to avoid escape issues.
  • Image size: Background images automatically adapt to the page size, so manual scaling is not always required. However, very large images take longer to process and increase generation time.
  • Multi-page documents: The example code applies the same background image to every page. To set different backgrounds for different pages, use page-number checks and handle them individually.

Summary

With Free Spire.PDF for Python, you can add background colors or background images to PDFs with minimal code. The library provides an intuitive API that helps developers get started quickly. Whether you need to batch-process documents or add customized backgrounds to specific files, the methods above can help you accomplish the task efficiently.

I hope this article is helpful! If you have further PDF-processing needs, feel free to explore other features of Free Spire.PDF.

Top comments (0)