We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

How do I make a watermark image fit a page without changing the aspect ratio?


I am trying to add an image watermark to PDF files using ImageStamp. The class allows me to set the height and width of a watermark, as well as its X and Y indentations for positioning. However, I was wondering: is there a way to automatically calculate the size and position of a watermark based on the information of a documents pages?


You can get different properties of page using the API and add the image stamp as per your requirements using the API. However, if you are facing some issue, please share some sample PDF document along with information of your expected results so that we can test the scenario in our environment and address it accordingly.

Thank you for the reply.

I was using getPagesInfo().getHeight() and getPagesInfo().getWidth() to calculate both the size of my ImageStamp and the X and Y indentations/positions. But, despite my document being only one page, the width/height I got from getPagesInfo() was different from the width/height I got from doc.getPages().get_Item(1).getHeight/Width().

So, I adjusted my program accordingly, and used this algorithm:
`for (Page page : doc.getPages()) {
//get the current page’s height and width
pageHeight = page.getMediaBox().getHeight();
pageWidth = page.getMediaBox().getWidth();

          	//Check orientation and calculate watermark size accordingly
	        if (pageHeight > pageWidth){
	        	imageStamp.setHeight((imageStamp.getHeight() / imageStamp.getWidth()) * pageWidth);
	        else {
	        	imageStamp.setWidth((imageStamp.getWidth() / imageStamp.getHeight()) * pageHeight);
	        //Position the watermark appropriately
	        imageStamp.setYIndent((pageHeight / 2) - (imageStamp.getHeight() / 2));
	        imageStamp.setXIndent((pageWidth / 2) - (imageStamp.getWidth() / 2));
	        //Apply watermark to page

Everything works as intended now, thanks to pointing me out to the page properties.


It is nice to hear that your requirements have been achieved. Please keep using our API and feel free to create a new topic in case you need further assistance.