Search code examples
c#.netpdfwatermarkaspose

How to add image watermarks to pdf using Aspose ?


The following code adds a watermark of the specified image at the center of the pdf page. I want the image to be repeated as the watermark on the entire pdf page instead of only being at the center. The watermark should repeat the way background-repeat property works in css.

static void Main(string[] args)
{
    Document pdfDocument = new Document(@"C:\Users\code.wines\Downloads\old.pdf");
    pdfDocument.Pages.Add();

    ImageStamp imageStamp = new ImageStamp(@"C:\Users\code.wines\Desktop\image.jpg");
    imageStamp.Background = true;

    imageStamp.Height = 350;
    imageStamp.Width = 350;
    imageStamp.Opacity = 0.5;

    imageStamp.HorizontalAlignment = HorizontalAlignment.Center;
    imageStamp.VerticalAlignment = VerticalAlignment.Center;

    for (int j = 1; j <= pdfDocument.Pages.Count; j++)
    {
        pdfDocument.Pages[j].AddStamp(imageStamp);
    }

    pdfDocument.Save(@"C:\Users\code.wines\Desktop\new.pdf");
}

Solution

  • You can add an image stamp on a PDF page by using nested loop. Below code snippet iterates through the page and adds image stamps as per your requirements. It assumes the page margins to be zero, in case your document includes margins then you can initialize X and Y variables with the values of respective margins instead of zero, and margins value will also affect conditional statement of For loop. Below code snippet explains how you can repeat the watermark on whole page of a PDF document.

    //load source document
    Document pdfDocument = new Document();
    //add a page
    pdfDocument.Pages.Add();
    //load source image
    ImageStamp imageStamp = new ImageStamp(dataDir + @"aspose-logo.jpg");
    imageStamp.Background = true;
    //set different values
    imageStamp.Height = 100;
    imageStamp.Width = 100;
    imageStamp.Opacity = 0.5;
    
    foreach (Page page in pdfDocument.Pages)
    {
        //assuming margins as zero
        page.PageInfo.Margin.Top = 0;
        page.PageInfo.Margin.Bottom = 0;
        page.PageInfo.Margin.Left = 0;
        page.PageInfo.Margin.Right = 0;
        for (double y = 0; y < page.PageInfo.Height; y = y + imageStamp.Height)
        {
            for (double x = 0; x < page.PageInfo.Width; x = x + imageStamp.Width)
            {
                imageStamp.XIndent = x;
                imageStamp.YIndent = y;
                page.AddStamp(imageStamp);
            }
        }
    }
    //save generated PDF document
    pdfDocument.Save( dataDir + @"New_18.5.pdf");
    

    I hope this will be helpful. Please feel free to contact us if you need any further assistance.

    PS: I work with Aspose as Developer Evangelist.