Below code for add image water mark on PDF using iText:
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
public class ImageWaterMarkOnPdf {
public static void main(String... args) {
try {
PdfReader reader = new PdfReader("originalfilepath/otiginal.pdf");
PdfStamper stamper = new PdfStamper(reader,
new FileOutputStream("outputfilepath/output.pdf"));
// image watermark
Image img = Image.getInstance("watermarkfilepath/watermark.png");
float w = img.getScaledWidth();
float h = img.getScaledHeight();
// properties
PdfContentByte over;
Rectangle pagesize;
float x, y;
// add water mark on all pages
int n = reader.getNumberOfPages();
for (int i = 1; i <= n; i++) {
// get page size and position for add water mark
pagesize = reader.getPageSizeWithRotation(i);
x = (pagesize.getLeft() + pagesize.getRight()) / 2;
y = (pagesize.getTop() + pagesize.getBottom()) / 2;
over = stamper.getOverContent(i);
over.saveState();
// set transparency
PdfGState state = new PdfGState();
state.setFillOpacity(0.2f); //more transparent
over.setGState(state);
// add image water mark center
over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
over.restoreState();
}
stamper.close();
reader.close();
}catch (IOException e) {
// TODO: handle exception
}catch (DocumentException e) {
// TODO: handle exception
}
}
}
No comments:
Post a Comment