I am facing a problem while adding a watermark at the center of each page of a pdf file.
What i have tried so far :
PdfStamper inputPdfStamper = null;
try {
PdfReader inputPdfReader = new PdfReader(new FileInputStream(input));
inputPdfStamper = new PdfStamper(inputPdfReader, new FileOutputStream(input));
Font font = new Font(fontFamily, fontSize, fontStyle, color);
for (int pageNumber = 1 ;pageNumber <=inputPdfStamper.getReader().getNumberOfPages() ; pageNumber++){
if(isWatermarkAbove){
ColumnText.showTextAligned(inputPdfStamper.getOverContent(pageNumber), Element.ALIGN_CENTER, new Phrase(watermark, font), inputPdfReader.getPageSize(pageNumber).getRight()/2, inputPdfReader.getPageSize(pageNumber).getTop()/2, 45);
// Updated Code
// ColumnText.showTextAligned(inputPdfStamper.getUnderContent(pageNumber), Element.ALIGN_CENTER, new Phrase(watermark, font), inputPdfReader.getCropBox(pageNumber).getLeft()/2, inputPdfReader.getCropBox(pageNumber).getBottom()/2, 45);
}else{
ColumnText.showTextAligned(inputPdfStamper.getUnderContent(pageNumber), Element.ALIGN_CENTER, new Phrase(watermark, font), inputPdfReader.getPageSize(pageNumber).getRight()/2, inputPdfReader.getPageSize(pageNumber).getTop()/2, 45);
}
}
inputPdfStamper.close();
} catch (Exception e){
throw new RuntimeException(e);
}finally {
if (inputPdfStamper!=null) {
try {
inputPdfStamper.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Issue:
The above code works fine for pdf file which has same dimensions(height and width) for all the pages. But when I provide pdf pages with different dimensions , watermark is placing in different positions not in the center.
What I Known :
ColumnText.showTextAligned(inputPdfStamper.getUnderContent(pageNumber), Element.ALIGN_CENTER, new Phrase(watermark, font), inputPdfReader.getPageSize(pageNumber).getRight()/2, inputPdfReader.getPageSize(pageNumber).getTop()/2, 45)
After I debug and evaluate the above code I am getting the same page size value for all the pages of the pdf which are in different dimensions.
inputPdfReader.getPageSize(pageNumber).getRight()
gives the same page size value for all the pages of the pdf.
and also inputPdfReader.getPageSize(pageNumber).getTop()
gives the same value for all the pages which are in different dimensions(hieght and width)
Question :
How to get the page size of each pages of the pdf file which are in different dimensions