How to Add Text to PDF in Python (Create & Edit with Examples)

How to Add Text to PDF in Python (Create & Edit with Examples)

2025-07-10 08:51:40 Written by  zaki zou
Rate this item
(0 votes)

Illustration showing Python code adding text to a PDF file

Adding text to a PDF is a common task in Python — whether you're generating reports, adding annotations, filling templates, or labeling documents. This guide will walk you through how to write text in a PDF file using Python, including both creating new PDF documents and updating existing ones.

We’ll be using a dedicated Python PDF library - Spire.PDF for Python, which allows precise control over text placement, font styling, and batch processing. The examples are concise, beginner-friendly, and ready for real-world projects.

Sections Covered

  1. Setup: Install the PDF Library in Python
  2. Add Text to a New PDF
  3. Add Text to an Existing PDF
  4. Control Text Style, Position, Transparency, and Rotation
  5. Common Pitfalls and Cross-Platform Tips
  6. Conclusion
  7. FAQ

Setup: Install the PDF Library in Python

To get started, install Spire.PDF for Python, a flexible and cross-platform PDF library.

pip install Spire.PDF

Or use Free Spire.PDF for Python:

pip install spire.pdf.free

Why use this library?

  • Works without Adobe Acrobat or Microsoft Office
  • Add and format text at exact positions
  • Supports both new and existing PDF editing
  • Runs on Windows, macOS, and Linux

Add Text to a New PDF Using Python

If you want to create a PDF from text using Python, the example below shows how to insert a line of text into a blank PDF page using custom font and position settings.

Example: Create and write text to a blank PDF

from spire.pdf import PdfDocument, PdfTrueTypeFont, PdfFontStyle, PdfSolidBrush, PdfRGBColor, PointF, RectangleF, \
    PdfStringFormat, PdfTextAlignment, PdfVerticalAlignment

# Create a new PDF document and add a new page
pdf = PdfDocument()
page = pdf.Pages.Add()

text = ("This report summarizes the sales performance of various products in the first quarter of 2025. " +
        "Below is a breakdown of the total sales by product category, " +
        "followed by a comparison of sales in different regions.")

# Set the font, brush, and point
font = PdfTrueTypeFont("Arial", 14.0, PdfFontStyle.Regular, True)
brush = PdfSolidBrush(PdfRGBColor(0, 0, 0))  # black
point = PointF(50.0, 100.0)

# Set the layout area and string format
layoutArea = RectangleF(50.0, 50.0, page.GetClientSize().Width - 100.0, page.GetClientSize().Height)
stringFormat = PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Top)

page.Canvas.DrawString(text, font, brush, layoutArea, stringFormat, False)

pdf.SaveToFile("output/new.pdf")
pdf.Close()

Technical Notes

  • PdfTrueTypeFont() loads a TrueType font from the system with customizable size and style (e.g., regular, bold). It ensures consistent text rendering in the PDF.
  • PdfSolidBrush() defines the fill color for text or shapes using RGB values. In this example, it's set to black ((0, 0, 0)).
  • RectangleF(x, y, width, height) specifies a rectangular layout area for drawing text. It enables automatic line wrapping and precise control of text boundaries.
  • PdfStringFormat() controls the alignment of the text inside the rectangle. Here, text is aligned to the top-left (Left and Top).
  • DrawString() draws the specified text within the defined layout area without affecting existing content on the page.

Example output PDF showing wrapped black text starting at coordinates (50, 50).

Generated PDF showing wrapped black text block starting at position (50, 50)

Tip: To display multiple paragraphs or line breaks, consider adjusting the Y-coordinate dynamically or using multiple DrawString() calls with updated positions.

If you want to learn how to convert TXT files to PDF directly using Python, please check: How to Convert Text Files to PDF Using Python.


Add Text to an Existing PDF in Python

Need to add text to an existing PDF using Python? This method lets you load a PDF, access a page, and write new text anywhere on the canvas.

This is helpful for:

  • Adding comments or annotations
  • Labeling document versions
  • Filling pre-designed templates

Example: Open an existing PDF and insert text

from spire.pdf import PdfDocument, PdfFontStyle, PdfSolidBrush, PdfRGBColor, PointF, PdfFont, PdfFontFamily

pdf = PdfDocument()
pdf.LoadFromFile("input.pdf")
page = pdf.Pages[0]

font = PdfFont(PdfFontFamily.TimesRoman, 12.0, PdfFontStyle.Bold)
brush = PdfSolidBrush(PdfRGBColor(255, 0, 0))  # red
location = PointF(150.0, 110.0)

page.Canvas.DrawString("This document is approved.", font, brush, location)

pdf.SaveToFile("output/modified.pdf")
pdf.Close()

Technical Notes

  • LoadFromFile() loads an existing PDF into memory.
  • You can access specific pages via pdf.Pages[index].
  • New content is drawn on top of the existing layout, non-destructively.
  • The text position is again controlled via PointF(x, y).

Modified PDF page with newly added red text annotation on the first page.

Modified PDF with added red text label on the first page

Use different x, y coordinates to insert content at custom positions.

Related article: Replace Text in PDF with Python


Control Text Style, Positioning, Transparency, and Rotation

When adding text to a PDF, you often need more than just plain content—you may want to customize the font, color, placement, rotation, and transparency, especially for annotations or watermarks.

Spire.PDF for Python offers fine-grained control for these visual elements, whether you’re building structured reports or stamping dynamic text overlays.

Set Font Style and Color

# Create PdfTrueTypeFont
font = PdfTrueTypeFont("Calibri", 16.0, PdfFontStyle.Italic, True)

# Create PdfFont
font = PdfFont(PdfFontFamily.TimesRoman, 16.0, PdfFontStyle.Italic)

# Create PdfBrush to specify text drawing color
brush = PdfSolidBrush(PdfRGBColor(34, 139, 34))  # forest green

PdfTrueTypeFont will embed the font into the PDF file. To reduce file size, you may use PdfFont, which uses system fonts without embedding them.

Apply Transparency and Rotation

You can adjust transparency and rotation when drawing text to achieve effects like watermarks or angled labels.

# Save the current canvas state
state = page.Canvas.Save()

# Set semi-transparency (0.0 = fully transparent, 1.0 = fully opaque)
page.Canvas.SetTransparency(0.4)

# Move the origin to the center of the page
page.Canvas.TranslateTransform(page.Size.Width / 2, page.Size.Height / 2)

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

# Draw text at new origin
page.Canvas.DrawString("DRAFT", font, brush, PointF(-50, -20))

Example: Add a Diagonal Watermark to the Center of the Page

The following example demonstrates how to draw a centered, rotated, semi-transparent watermark using all the style controls above:

from spire.pdf import PdfDocument, PdfTrueTypeFont, PdfFontStyle, PdfSolidBrush, PdfRGBColor, PointF
from spire.pdf.common import Color

pdf = PdfDocument()
pdf.LoadFromFile("input1.pdf")
page = pdf.Pages[0]

text = "Confidential"
font = PdfTrueTypeFont("Arial", 40.0, PdfFontStyle.Bold, True)
brush = PdfSolidBrush(PdfRGBColor(Color.get_DarkBlue()))  # gray

# Measure text size to calculate center
size = font.MeasureString(text)
x = (page.Canvas.ClientSize.Width - size.Width) / 2
y = (page.Canvas.ClientSize.Height - size.Height) / 2

state = page.Canvas.Save()
page.Canvas.SetTransparency(0.3)
page.Canvas.TranslateTransform(x + size.Width / 2, y + size.Height / 2)
page.Canvas.RotateTransform(-45.0)
page.Canvas.DrawString(text, font, brush, PointF(-size.Width / 2, -size.Height / 2))
page.Canvas.Restore(state)

pdf.SaveToFile("output/with_watermark.pdf")
pdf.Close()

PDF page displaying a centered, rotated, semi-transparent watermark text.

Screenshot showing several PDF files with uniform footer text added programmatically

This approach works well for dynamic watermarking, diagonal stamps like "VOID", "COPY", or "ARCHIVED", and supports full automation.

Make sure all files are closed and not in use to avoid PermissionError.

For more details on inserting watermarks into PDF with Python, please refer to: How to Insert Text Watermarks into PDFs Using Python.


Common Pitfalls and Cross-Platform Considerations

Even with the right API, issues can arise when deploying PDF text operations across different environments or font configurations. Here are some common problems and how to resolve them:

Issue Cause Recommended Fix
Text appears in wrong position Hardcoded coordinates not accounting for page size Use ClientSize and MeasureString() for dynamic layout
Font not rendered Font lacks glyphs or isn't supported Use PdfTrueTypeFont to embed supported fonts like Arial Unicode
Unicode text not displayed Font does not support full Unicode range Use universal fonts (e.g., Arial Unicode, Noto Sans)
Text overlaps existing content Positioning too close to body text Adjust Y-offsets or add padding with MeasureString()
Watermark text appears on output You are using the paid version without a license Use the free version or apply for a temporary license
Font file too large Embedded font increases PDF size Use PdfFont for system fonts (non-embedded), if portability is not a concern
Inconsistent results on macOS/Linux Fonts not available or different metrics Ship fonts with your application, or use built-in cross-platform fonts

Conclusion

With Spire.PDF for Python, adding text to PDFs—whether creating new files, updating existing ones, or automating batch edits—can be done easily and precisely. From annotations to watermarks, the library gives you full control over layout and styling.

You can start with the free version right away, or apply for a temporary license to unlock full features.


FAQ

How to add text to a PDF using Python?

Use a PDF library such as Spire.PDF to insert text via the DrawString() method. You can define font, position, and styling.

Can I write text into an existing PDF file with Python?

Yes. Load the file with LoadFromFile(), then use DrawString() to add text at a specific location.

How do I generate a PDF from text using Python?

Create a new document and use drawing methods to write content line by line with precise positioning.

Can I add the same text to many PDFs automatically?

Yes. Use a loop to process multiple files and insert text programmatically using a template script.

Additional Info

  • tutorial_title:
Last modified on Thursday, 10 July 2025 09:02