Saturday, 11 November 2017

Add Text Water Mark on PDF JAVA using iText

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;
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.BOLDnew             GrayColor(0.5f));
Phrase p = new Phrase("Checked"FONT);

// properties
PdfContentByte over;
Rectangle pagesize;
float xy;

// add water on every page
int n = reader.getNumberOfPages();
for (int i = 1; i <= ni++) {

// 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_CENTERpxy, 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_CENTERpxy, 45);



No comments:

Post a Comment

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...