Adding Watermark to PDF using Python
Contents
[
Hide
]
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.
- Create a watermark artifact (see
WatermarkArtifact). - Configure text state (see
TextState). - Bind text to the watermark.
- Define positioning and style using
HorizontalAlignmentandVerticalAlignment. - Attach watermark to a
Pagevia the page’sArtifactscollection (seeArtifactCollection). - Save the updated
DocumentusingDocument.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)