Sample Code:
Running code for add text water mark on PDF in java using iText , the water mark drawing on center horizontally.
import java.io.FileOutputStream;
Running code for add text water mark on PDF in java using iText , the water mark drawing on center horizontally.
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.GrayColor;
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 TextWaterMarkOnPDF {
public static void main(String args[]) {
try {
PdfReader reader = new PdfReader("originalFilePath/file.pdf");
PdfStamper stamper = new PdfStamper(reader,
new FileOutputStream("outputPath/watermarked.pdf"));
// text watermark
Font FONT = new Font(Font.FontFamily.HELVETICA, 50, Font.BOLD, new GrayColor(0.5f));
Phrase p = new Phrase("Checked", FONT);
// properties
PdfContentByte over;
Rectangle pagesize;
float x, y;
// add water on every page
int n = reader.getNumberOfPages();
for (int i = 1; i <= n; i++) {
// get page size and position
pagesize = reader.getPageSizeWithRotation(i);
x = (pagesize.getLeft() + pagesize.getRight()) / 2;
y = (pagesize.getTop() + pagesize.getBottom()) / 2;
over = stamper.getOverContent(i);
over.saveState();
// set transparency of watermark : if opacity less then it more transparent
PdfGState state = new PdfGState();
state.setFillOpacity(0.2f);
over.setGState(state);
// add watermark text in center horizontal
ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, x, y, 0);
over.restoreState();
}
stamper.close();
reader.close();
}catch (IOException e) {
// TODO: handle exception
}catch (DocumentException e) {
// TODO: handle exception
}
}}
Add watermark diagonally:
ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, x, y, 45);
Add watermark diagonally:
ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, x, y, 45);
No comments:
Post a Comment