This will help if we see the PDF file. Then we did not need to guess, we would know.
However, I suspect that your “existing image overlay” is part of the annotation. Nothing you put in the content of the page will ever appear above the annotation.
Options (if I'm right):
Add your own annotation
For this, I would use a PushbuttonField with LAYOUT_ICON_ONLY. Draw an image in PdfTemplate and use it for the icon button.
The z-order for annotations is determined by the order of the page annotation array. New annotations are added to this array. No problems.
PushbuttonField fld = new PushbuttonField(stamper.getWriter(), box, name); fld.setLayout(PushbuttonField.LAYOUT_ICON_ONLY); fld.setImage(myImage); stamper.addAnnotation(fld.getField(), 1);
You may need to use setScaleIcon (), setHorizontalAdjustment (), setVerticalAdjustment (), setProportionalIcon () and maybe a couple others to make your image look exactly the way you want it to.
Flatten in one pass, add your image to another
If the existing image annotation is something that iText can smooth out (maybe not), you can do what you want in two passes. The first pass will be just "setFormFlattening (true); close ();" and the second will be all that you are doing now.
ByteArrayOutputStream output = new ByteArrayOutputStream(); PdfStamper stamper = new PdfStamper( firstReader, output ); stamper.setFormFlattening(true); stamper.setFreeTextFlatten(true); // probably not needed. stamper.close(); PdfReader secondReader = new PdfReader(output.toByteArray()); FileOutputStream finalOutput = new FileOutputStream( outputPath ); stamper = new PdfStamper(secondReader, finalOutput); // do your thing here. stamper.getOverContent(1).addImage(image);
source share