import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* <dependency>
* <groupId>com.itextpdf</groupId>
* <artifactId>itextpdf</artifactId>
* <version>5.5.13.1</version>
* </dependency>
* 需求:用户输入一个源pdf文件,一个用做水印的图片,程序负责生成一个新的pdf文件,内有图片水印,且图片旋转一个度数。
*/
public class TransparentWatermark34 {
public static final String SRC = "D:\\Dump\\TestDB\\watermark\\src\\main\\resources\\hero.pdf";
public static final String DEST = "D:\\Dump\\TestDB\\watermark\\src\\main\\resources\\hero_watermarked.pdf";
public static final String IMG = "D:\\img3.png";
public static void main(String[] args) throws IOException, DocumentException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new TransparentWatermark34().manipulatePdf(SRC, DEST);
}
public void manipulatePdf(String src, String dest) {
PdfReader reader = null;
PdfStamper stamper = null;
try {
reader = new PdfReader(src);
int pdfNumberOfPages = reader.getNumberOfPages();
stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.setRotateContents(false);
// 作为水印的图片
Image img = Image.getInstance(IMG);
// 设置绝对坐标
img.setAbsolutePosition(170, 380);
// 设置旋转弧度
img.setRotation(30);
// 设置旋转角度
img.setRotationDegrees(45);
// 设置缩放比例
img.scalePercent(60);
PdfGState gs1 = new PdfGState();
// 填充不透明度
gs1.setFillOpacity(0.5f);
PdfContentByte over;
for (int i = 1; i <= pdfNumberOfPages; i++) {
over = stamper.getOverContent(i);
over.saveState();
over.setGState(gs1);
over.addImage(img);
over.restoreState();
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (DocumentException de) {
de.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stamper != null) {
try {
stamper.close();
} catch (Exception e) {
// 空
}
}
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
// 空
}
}
}
}
}
给PDF文件添加图片水印
最新推荐文章于 2023-03-06 09:53:32 发布