java pdf to add a text watermark

Dependencies used:

<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.11</version>
</dependency>

<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>

 

Code implementation;

 

com.gxever.zvn Package; 

Import com.itextpdf.text.BaseColor;
Import com.itextpdf.text.Element;
Import com.itextpdf.text.Rectangle;
Import com.itextpdf.text.pdf *;.

Import the java.io. a FileOutputStream;

/ **
* @author Lys
* @date 2019/8/15 13:39
* @Version V1.0
* @Description:
* /
public class Test {

public static void main (String [] args) throws Exception {

Watermark ( "D: \\ pdf \\ 123.pdf ", "D: \\ pdf \\ 123Demo.pdf", " Chi Heng Rui only use the occasion, other invalid");
}

/ **
* @param you inputFile address PDF file
* @param outputFile generate PDF stored after adding a watermark address
* @param waterMarkName your watermark
* @return
* /
Watermark static Boolean public (inputFile String,
String the outputFile, String waterMarkName) {
the try {
PdfReader Reader = new new PdfReader (inputFile);
PdfStamper Stamper = new new PdfStamper (Reader, new new a FileOutputStream (
the outputFile));
// font settings where more critical, this setting supports the Chinese written
BaseFont BaseFont.createFont Base = ( "Light-STSong",
"the UCS2-H-UniGB", BaseFont.NOT_EMBEDDED); // system font
int reader.getNumberOfPages Total = () +. 1;

PdfContentByte an under;
the Rectangle pageRect = null;
for (int I =. 1; I <Total; I ++) {
= stamper.getReader pageRect ().
getPageSizeWithRotation (I);
// calculate watermark X, Y coordinates
a float pageRect.getWidth X = () / 10;
a float pageRect.getHeight Y = () / 10-10 of;
// get the most PDF top
an under stamper.getOverContent = (I);
under.saveState ();
// sET transparency
PdfGState new new PdfGState GS = ();
// set transparency 0.2
gs.setFillOpacity (1.f);
under.setGState (GS);
under.restoreState ();
under.beginText ();
under.setFontAndSize (Base, 60);
under.setColorFill (BaseColor.ORANGE);

// Text watermark inclined at an angle of 45 degrees
under.showTextAligned (Element.ALIGN_CENTER
, waterMarkName, X,
Y, 55);
// add watermarks text
under.endText ();
under.setLineWidth ( 1F);
under.stroke ();
}
stamper.close ();
return to true;
} the catch (Exception E) {
e.printStackTrace ();
return to false;
}
}

}

Guess you like

Origin www.cnblogs.com/yishuo/p/11357473.html