Adding Custom Text to PDF Documents with Python

작성자

카테고리:

← 피드로
DEV Community · Jack9012 · 2026-09-17 개발(SW)

When processing documents, it is often necessary to append text to existing PDF files for purposes such as supplementary notes, explanatory labels, watermark text, and page number annotations. Python boasts an extensive collection of PDF processing libraries. Among them, Free Spire.PDF for Python stands out with its streamlined APIs, comprehensive style customization, and independence from local Adobe components. It enables efficient PDF text editing with support for personalized effects including custom fonts, colors, transparency, and text rotation.

Python Add Text to PDF

This tutorial provides an objective and complete walkthrough of adding text to PDFs using Free Spire.PDF, covering basic executable code and advanced style customization to meet diverse PDF text editing requirements.

1. Environment Setup

1.1 Library Installation

First, install the Free Spire.PDF dependency via pip by running the following command:

pip install spire-pdf-free

Enter fullscreen mode Exit fullscreen mode

This library supports Python 3.7 and above, and is cross-platform compatible with Windows, macOS and Linux. After installation, you may directly call its APIs to edit PDF files.

1.2 Overview of Core Modules

Below is a breakdown of key modules used in this practical project and their core functionalities:

  • PdfDocument : The core class for PDF file operations, responsible for loading, saving and closing documents
  • Font-related classes : PdfCjkStandardFont, PdfTrueTypeFont, PdfFont — designed for CJK fonts, custom system fonts, and built-in standard PDF fonts respectively
  • PdfSolidBrush & PdfRGBColor : Used to configure text drawing colors and brush styles
  • PointF : Defines the coordinate position for rendering text on PDF pages

2. Basic Implementation: Insert Plain Text into a PDF

This basic workflow loads an existing PDF file and inserts custom text at a specified coordinate on a target page, alongside basic font and color configuration. Below is fully runnable code with detailed comments.

from spire.pdf import PdfDocument, PdfFontStyle, PdfSolidBrush, PdfRGBColor, PointF, PdfCjkStandardFont, PdfCjkFontFamily

# Initialize a PDF document object and load the local PDF file
pdf = PdfDocument()
pdf.LoadFromFile("input.pdf")  

# Retrieve the first page of the PDF (index starts at 0)
page = pdf.Pages.get_Item(0) 

# Configure CJK font: Monotype Hei Medium, size 16, bold weight
font = PdfCjkStandardFont(PdfCjkFontFamily.MonotypeHeiMedium, 16.0, PdfFontStyle.Bold)

# Create a brush and set text color to light orange
brush = PdfSolidBrush(PdfRGBColor(255,200, 180)) 

# Define coordinates for text rendering (unit: point)
location = PointF(72.0, 300.0)

# Draw custom text at the specified position
page.Canvas.DrawString("This is newly added text.", font, brush, location)

# Save the modified PDF file
pdf.SaveToFile("AddedText.pdf")
# Close the document to release occupied resources
pdf.Close()

Enter fullscreen mode Exit fullscreen mode

Core Workflow of the Code

Load document → Select target page → Configure font and color styles → Set rendering coordinates → Draw text → Save file and release resources. The workflow is concise and free of redundant logic.

3. Advanced Style Customization

Spire.PDF offers abundant text styling extensions to accommodate various layout scenarios, including multiple font types, custom colors, text transparency, and rotated text. Practical implementations of each feature are covered below.

3.1 Multi-Font & Custom Color Configuration

Three mainstream font initialization methods are available for CJK text, third-party system fonts, and built-in PDF standard fonts. Custom RGB colors of any shade are also supported.

# Method 1: Load system TrueType font (Calibri), italic, size 16, embed font into PDF
font1 = PdfTrueTypeFont("Calibri", 16.0, PdfFontStyle.Italic, True)

# Method 2: Use PDF built-in Times Roman standard font, italic, size 16
font2 = PdfFont(PdfFontFamily.TimesRoman, 16.0, PdfFontStyle.Italic)

# Create a brush with forest green text color
brush = PdfSolidBrush(PdfRGBColor(34, 139, 34))

Enter fullscreen mode Exit fullscreen mode

Enabling font embedding ensures consistent font rendering across all devices when opening the PDF, making it ideal for documents shared cross-platform.

3.2 Adjust Text Transparency

The SetTransparency canvas method creates semi-transparent text, commonly used for subtle watermarks and light annotations. The transparency value ranges from 0.0 (fully transparent) to 1.0 (fully opaque).

# Set text to 40% opacity (transparency = 0.4)
page.Canvas.SetTransparency(0.4)

# Render semi-transparent text
page.Canvas.DrawString("Semi-transparent text", font, brush, PointF(100.0, 100.0))

Enter fullscreen mode Exit fullscreen mode

3.3 Create Rotated Text

You may rotate the canvas coordinate system to render text at any tilt angle, perfect for diagonal watermarks and marginal notes. Negative values rotate counterclockwise, while positive values rotate clockwise.

# Rotate canvas 45 degrees counterclockwise
page.Canvas.RotateTransform(-45)

# Draw rotated text
page.Canvas.DrawString("Rotated text", font, brush, PointF(100.0, 100.0))

Enter fullscreen mode Exit fullscreen mode

Note: Canvas rotation applies globally. Reset canvas transformations after drawing if you need to revert to the default orientation.

4. Key Development Notes

  • Resource Release : Always call the Close() method after completing PDF operations to free file handles and avoid file locks or memory leaks.
  • Coordinate System : PDF coordinates use points as units, with the top-left corner of a page serving as the origin. Adjust rendering coordinates based on page dimensions as needed.
  • CJK Text Compatibility : Prioritize PdfCjkStandardFont or system Chinese fonts for Chinese text to prevent garbled characters or missing font errors.
  • Combined Styling : Transparency, rotation and font styles can be combined freely to build complex text display effects.

5. Conclusion

Spire.PDF for Python delivers lightweight yet powerful PDF text editing capabilities, enabling developers to implement core features including basic text insertion, multi-font compatibility, custom color schemes, transparent text and rotated text with minimal code. Compared with traditional PDF libraries, its key advantages lie in intuitive APIs, full styling support, and native Chinese & English compatibility. It is well-suited for use cases such as automated PDF editing, batch document processing and watermark generation.

원문에서 계속 ↗