Add watermark in the center of every PDF page using Aspose.PDF for .NET

I’m using the following code to apply an image file as a watermark stamp across all pages of a pdf.
It works fine my issue is when I have pages of differing widths the image isn’t placed in the center.

Dim PDFlicense As Aspose.Pdf.Kit.License = New Aspose.Pdf.Kit.License
PDFlicense.SetLicense(“Aspose.Pdf.Kit.lic”)
Dim inFile As String = sourceFile
Dim outFile As String = destFile
Dim imageFile As String = wMark
Dim fileInfo As PdfFileInfo = New PdfFileInfo(inFile)
Dim aStamp As Stamp = New Stamp()
aStamp.BindImage(imageFile)
aStamp.IsBackground = False
aStamp.SetImageSize(120, 45)
aStamp.SetOrigin((fileInfo.GetPageWidth(1) / 2) - 60, 10)
Dim stamper As PdfFileStamp = New PdfFileStamp(inFile, outFile)
stamper.AddStamp(aStamp)
stamper.Close()

I understand why it’s doing this because I’m using the page width of the first page to set the x coordinate in the aStamp.SetOrigin, but I’m wondering if there’s a better way to do this so that the image gets centered across all pages regardless of page width.
You’ll notice in my attached sample the stamp on the last two pages is off to the left somewhat and I’d like to get it centered on those as well.

Thanks so much!

Hi Jason,

In order to apply a watermark at the center of different sized pages in a PDF file, you will have to navigate through the pages and add watermark on individual page as shown below:


Dim viewer As New PdfViewer

viewer.OpenPdfFile("…input file path…")

Dim pagecount As Integer

pagecount = viewer.PageCount


Dim inFile As String = “…input file path…”

Dim outFile As String = “…output file path…”

Dim i As Integer

Dim stamper As PdfFileStamp = New PdfFileStamp(inFile, outFile)

Dim fileInfo As PdfFileInfo = New PdfFileInfo(inFile)


For i = 1 To pagecount


Dim aStamp As Stamp = New Stamp()

aStamp.BindImage(imageFile)

aStamp.IsBackground = False

aStamp.SetImageSize(120, 45)

aStamp.SetOrigin((fileInfo.GetPageWidth(i) / 2) - 60, 10)


Dim arr(1) As Integer

arr(0) = i

aStamp.Pages = arr

stamper.AddStamp(aStamp)


Next


stamper.Close()


I hope this helps. If you have any further questions, please do let us know.
Regards,