package com.xian.util;
import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
/**
* 給PDF 加水印功能(文字水印和圖片水印)
*
* @author yangxp
*/
public class PdfUtil {
/**
* 添加圖片和文字水印
*
* @param srcFile 待加水印文件
* @param destFile 加水印後存放地址
* @param text 加水印的文本內容
* @param textWidth 文字橫座標
* @param textHeight 文字縱座標
* @param imgFile 加水印圖片文件
* @param imgWidth 圖片橫座標
* @param imgHeight 圖片縱座標
* @throws IOException
* @throws DocumentException
*/
public static void addWaterMark(String srcFile, String destFile, String text, int textWidth, int textHeight,
String imgFile, int imgWidth, int imgHeight) throws IOException, DocumentException {
// 待加水印的文件
PdfReader reader = new PdfReader(srcFile);
// 加完水印的文件
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));
// 設置字體
BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
// PDF總頁數
int total = reader.getNumberOfPages() + 1;
// 循環對每頁插入水印
PdfContentByte content;
for (int i = 1; i < total; i++) {
// 水印在之前文本之上
content = stamper.getOverContent(i);
// 圖片水印
if (imgFile != null) {
Image image = null;
if (imgFile != null) {
image = Image.getInstance(imgFile);
image.setAbsolutePosition(imgWidth, imgHeight);
// 設置圖片的顯示大小
image.scaleToFit(100, 125);
}
content.addImage(image);
}
// 文字水印
if (text != null) {
content.beginText();
// 設置顏色 默認爲藍色
content.setColorFill(Color.BLUE);
// 設置字體及字號
content.setFontAndSize(font, 38);
// 設置起始位置
content.setTextMatrix(textWidth, textHeight);
// 中間水印
content.showTextAligned(Element.ALIGN_LEFT, text, textWidth, textHeight, 45);
// 底部水印
for (int k = 0; k < text.length(); k++) {
// 距離底邊的距離
content.setTextRise(10);
// 將char轉成字符串
content.showText(String.valueOf(text.charAt(k)));
}
content.endText();
}
}
stamper.close();
}
public static void main(String[] args) throws DocumentException, IOException {
String iconPath = "d:/test/icon/icon.png";
String srcImgPath = "d:/test/upload/temp/test.pdf";
String targerPath = "d:/test/upload/file/test.pdf";
PdfUtil.addWaterMark(srcImgPath, targerPath, "得瑟的ERP", 200, 300, iconPath, 400, 100);
}
}
使用lowagie給pdf添加文字和圖片水印
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.