This tutorial introduces how to add an image stamp to a PDF document using Spire.PDF for Java.
import com.spire.pdf.annotations.PdfRubberStampAnnotation; import com.spire.pdf.annotations.appearance.PdfAppearance; import com.spire.pdf.graphics.PdfImage; import com.spire.pdf.graphics.PdfTemplate; import java.awt.geom.Rectangle2D; public class ImageStamp { public static void main(String[] args) { //create a PdfDocument object PdfDocument doc = new PdfDocument(); //load a PDF document doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf"); //get the first page PdfPageBase page = doc.getPages().get(0); //load an image file PdfImage image = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\quality-control-stamp.png"); //get the width and height of the image int width = image.getWidth(); int height = image.getHeight(); //create a PdfTemplate object based on the size of the image PdfTemplate template = new PdfTemplate(width, height); //draw image on the template template.getGraphics().drawImage(image, 0, 0, width, height); //create a rubber stamp annotation, specifying its location and position Rectangle2D rect = new Rectangle2D.Float((float) (page.getActualSize().getWidth() - width - 50), (float) (page.getActualSize().getHeight() - height - 80), width, height); PdfRubberStampAnnotation stamp = new PdfRubberStampAnnotation(rect); //create a PdfAppearance object PdfAppearance pdfAppearance = new PdfAppearance(stamp); //set the template as the normal state of the appearance pdfAppearance.setNormal(template); //apply the appearance to the stamp stamp.setAppearance(pdfAppearance); //add the stamp annotation to PDF page.getAnnotationsWidget().add(stamp); //save the file doc.saveToFile("ImageStamp.pdf"); doc.close(); } }
Output: