Adding Watermark to PDF using Python

Programming Samples: How To Add Watermark On PDF Files

Add a watermark artifact to a PDF Document using Aspose.PDF for Python via .NET. A watermark is a visual overlay applied to pages for branding, security, or informational purposes. The example shows how to configure TextState appearance, positioning with HorizontalAlignment and VerticalAlignment, rotation, and transparency before applying the watermark to a Page.

  1. Create a watermark artifact (see WatermarkArtifact).
  2. Configure text state (see TextState).
  3. Bind text to the watermark.
  4. Define positioning and style using HorizontalAlignment and VerticalAlignment.
  5. Attach watermark to a Page via the page’s Artifacts collection (see ArtifactCollection).
  6. Save the updated Document using Document.save().

import aspose.pdf as ap

def add_watermark(input_pdf, output_pdf):
    # Load the existing PDF document
    document = ap.Document(input_pdf)

    # Create a watermark artifact
    watermark = ap.WatermarkArtifact()

    # Configure text state for the watermark
    text_state = ap.text.TextState()
    text_state.font_size = 72
    text_state.foreground_color = ap.Color.blue
    text_state.font = ap.text.FontRepository.find_font("Courier")

    # Apply text and style to the watermark
    watermark.set_text_and_state("WATERMARK", text_state)

    # Position and style settings
    watermark.artifact_horizontal_alignment = ap.HorizontalAlignment.CENTER
    watermark.artifact_vertical_alignment = ap.VerticalAlignment.CENTER
    watermark.rotation = 45
    watermark.opacity = 0.5
    watermark.is_background = True

    # Add watermark to the first page
    document.pages[1].artifacts.append(watermark)

    # Save the updated PDF
    document.save(output_pdf)