Saturday, 11 November 2017

Add image water mark on PDF in JAVA using iText

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

links for Data Structure

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