Adding Watermarks - Emmanuel Katto Uganda

Hello everyone, My name is Emmanuel Katto. What is the best way to add a watermark to a PDF document using Aspose.PDF? I’d like the watermark to be semi-transparent and positioned in the center of each page.

Any examples or tips would be much appreciated!

Thanks,
Emmanuel Katto

@emmanuelkatto

To add a semi-transparent watermark to a PDF document using Aspose.PDF, you can utilize the Artifact class to create and position the watermark. Below is a step-by-step guide along with a code example that demonstrates how to achieve this.

Steps to Add a Watermark

  1. Load the PDF Document: Start by loading the existing PDF file into your project.
  2. Create the Watermark: Use the Artifact class to create a watermark. You can set properties such as text, opacity, and position.
  3. Add the Watermark to Each Page: Iterate through each page of the PDF and add the watermark to the center.

Code Example

Here’s a sample code snippet in C# that illustrates how to add a semi-transparent watermark to the center of each page:

using Aspose.Pdf;
using Aspose.Pdf.Drawing;

public class WatermarkExample
{
    public static void AddWatermark(string inputFilePath, string outputFilePath)
    {
        // Load the PDF document
        Document pdfDocument = new Document(inputFilePath);

        // Create a watermark artifact
        Artifact watermark = new Artifact(Artifact.ArtifactType.Watermark);
        watermark.Text = "Sample Watermark";
        watermark.Opacity = 0.5; // Set opacity to 50%
        watermark.Rectangle = new Rectangle(100, 400, 500, 600); // Adjust the rectangle as needed

        // Add the watermark to each page
        foreach (Page page in pdfDocument.Pages)
        {
            page.Artifacts.Add(watermark);
        }

        // Save the updated PDF document
        pdfDocument.Save(outputFilePath);
    }
}

Explanation of the Code

  • Opacity: The Opacity property is set to 0.5, making the watermark semi-transparent.
  • Positioning: The Rectangle property defines the position of the watermark. You may need to adjust the coordinates to center it on the page.
  • Iterating Pages: The code loops through each page in the PDF document and adds the watermark artifact.

Conclusion

This approach allows you to effectively add a semi-transparent watermark to your PDF documents using Aspose.PDF. You can customize the text and positioning as per your requirements.

For more detailed information, you can refer to the official documentation on adding watermarks using Aspose.PDF here.

If you have any further questions or need additional examples, feel free to ask!