在开发中,很多客户要求对pdf文档和相关图片进行水印文字添加。
可能我现在水平有限,在对pdf文件添加的时候,先将pdf文件转为了图片格式,然后再进行的水印添加,之后再转回pdf格式文档。以下就是代码。
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.imageio.ImageIO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.util.GraphicsRenderingHints;
import com.eos.system.annotation.Bizlet;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.mln.frame.CompressFile;
import com.mln.wateroa.files.filesdataset.AtFileupload;
import commonj.sdo.DataObject;
import org.gocom.components.coframe.tools.CoframeDASDaoSupport;
/**
* @author admin
* @date 2018-08-13 16:03:30
*
*/
public class PdfWaterMarkUtil extends CoframeDASDaoSupport{
String uuid = UUID.randomUUID().toString().replace("-", "");
//测试
public static void main(String[] args) throws PDFException, PDFSecurityException, IOException, InterruptedException {
PdfWaterMarkUtil pwm = new PdfWaterMarkUtil();
ArrayList imageUrllist = new ArrayList();
String logoText = "此文件仅对投标有效TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST";
String srcImgPath = "G:\\22-1xxxxxxx.pdf";
pwm.waterMark(srcImgPath, logoText);
}
/**
* pdf水印添加
* @param srcImgPath原文件地址
* @param logoText水印文字
* @return 添加水印后的pdf路径
* @throws InterruptedException
* @throws IOException
* @throws PDFSecurityException
* @throws PDFException
*/
public String PdfWaterMarks (String srcImgPath,String logoText) throws PDFException, PDFSecurityException, IOException, InterruptedException{
PdfWaterMarkUtil pwm = new PdfWaterMarkUtil();
ArrayList imageUrllist = new ArrayList();
String pngpath = pwm.pdfToPic(srcImgPath);//pdf转图片后的路径
String targerTextPath = pwm.markImageByText(logoText, pngpath, -20);//给转的图片添加水印
imageUrllist.add(targerTextPath);
String newPdfPath = srcImgPath.substring(0,srcImgPath.lastIndexOf("."))+uuid;
String newPdfUrl = newPdfPath+"new.pdf";
File file = pwm.PngToPdf(imageUrllist, newPdfUrl); //把添加完水印的图片重新生成pdf
pwm.deleteFile(pngpath);
pwm.deleteFile(targerTextPath);
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newPdfUrl;
}
/**
* 图片添加水印
* @param srcImgPath
* @param logoText
* @return 添加水印后的图片路径
*/
public String JpgWaterMarks(String srcImgPath,String logoText){
String targerTextPath = markImageByText(logoText, srcImgPath, -20);//图片添加水印
return targerTextPath;
}
/**
* 判断是为图片添加水印还是pdf添加水印
* @param srcImgPath 源路径
* @param logoText 水印文字
* @return 添加水印后的图片路径
*/
public String waterMark(String srcImgPath,String logoText) throws PDFException, PDFSecurityException, IOException, InterruptedException{
String imgType = srcImgPath.substring(srcImgPath.lastIndexOf(".")+ 1).toLowerCase();
PdfWaterMarkUtil pwm = new PdfWaterMarkUtil();
String newPath = null;
System.out.println(imgType);
if (imgType.contains("pdf")){//图片类型为pdf格式时候
System.out.println("pdf格式添加水印");
newPath = PdfWaterMarks(srcImgPath,logoText);
}else
if(imgType.contains("bmp")||imgType.contains("pcx")||imgType.contains("tiff")||imgType.contains("gif")||imgType.contains("jpeg")
||imgType.contains("tga")||imgType.contains("exif")||imgType.contains("fpx")||imgType.contains("svg")||imgType.contains("psd")
||imgType.contains("cdr")||imgType.contains("pcd")||imgType.contains("dxf")||imgType.contains("ufo")||imgType.contains("eps")
||imgType.contains("png")||imgType.contains("hdri")||imgType.contains("ai")||imgType.contains("raw")||imgType.contains("raw")
||imgType.contains("ico")||imgType.contains("webp")||imgType.contains("flic")||imgType.contains("emf")||imgType.contains("jpg")){//图片类型
System.out.println("图片格式添加水印");
newPath = pwm.JpgWaterMarks(srcImgPath, logoText);
}else{
newPath = srcImgPath;
}
return newPath;
}
/**
* 图片添加水印
* @param srcImgPath原文件地址
* @param logoText水印文字
* @return 添加水印后的图片路径
*/
@Bizlet("")
public String PicWaterMark(String srcImgPath,String logoText){
PdfWaterMarkUtil a = new PdfWaterMarkUtil();
String targerTextPath = a.markImageByText(logoText, srcImgPath, -20);
return targerTextPath;
}
// 水印透明度
private static float alpha = 0.5f;
// 水印文字颜色
private static Color color = Color.gray;
/*
* pdf转图片
*/
public String pdfToPic(String pdfPath) throws PDFException, PDFSecurityException, IOException, InterruptedException{
String newPath1 = pdfPath.substring(0,pdfPath.lastIndexOf("."))+uuid;
//String newPath2 = pdfPath.substring(pdfPath.lastIndexOf("."));
String newPath = newPath1+".png";
org.icepdf.core.pobjects.Document document = new org.icepdf.core.pobjects.Document();
document.setFile(pdfPath);
float scale = 2.5f;//缩放比例
float rotation = 0f;//旋转角度
for (int i = 0; i < document.getNumberOfPages(); i++) {
BufferedImage image = (BufferedImage)
document.getPageImage(i, GraphicsRenderingHints.SCREEN, org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
RenderedImage rendImage = image;
try {
// String imgName = i + ".png";
System.out.println(newPath);
File file = new File(newPath);
ImageIO.write(rendImage, "png", file);
} catch (IOException e) {
e.printStackTrace();
}
image.flush();
}
document.dispose();
return newPath;
}
//图片转pdf
public File PngToPdf(ArrayList imageUrllist,String mOutputPdfFileName) {
Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
try {
PdfWriter
.getInstance(doc, new FileOutputStream(mOutputPdfFileName));
doc.open();
for (int i = 0; i < imageUrllist.size(); i++) {
//doc.newPage();
//doc.add(new Paragraph("简单使用iText"));
Image png1 = Image.getInstance(imageUrllist.get(i));
float heigth = png1.getHeight();
float width = png1.getWidth();
int percent = getPercent2(heigth, width);
png1.setAlignment(Image.MIDDLE);
png1.scalePercent(percent+3);// 表示是原来图像的比例;
doc.add(png1);
}
doc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
File mOutputPdfFile = new File(mOutputPdfFileName);
if (!mOutputPdfFile.exists()) {
mOutputPdfFile.deleteOnExit();
return null;
}
System.out.println("水印图片转PDF完成");
return mOutputPdfFile;
}
/**
* 第二种解决方案,统一按照宽度压缩 这样来的效果是,所有图片的宽度是相等的,自我认为给客户的效果是最好的
*
* @param args
*/
public static int getPercent2(float h, float w) {
int p = 0;
float p2 = 0.0f;
p2 = 530 / w * 100;
p = Math.round(p2);
return p;
}
/*
* 图片添加水印
*/
public String markImageByText(String logoText, String srcImgPath, Integer degree) {
String newPath1 = srcImgPath.substring(0,srcImgPath.lastIndexOf("."));
String newPath2 = srcImgPath.substring(srcImgPath.lastIndexOf("."));
String targerPath = newPath1+"new" +newPath2;
System.out.println(targerPath);
InputStream is = null;
OutputStream os = null;
try {
// 1、源图片
File file = new File(srcImgPath);
BufferedImage bi = null;
try {
bi = ImageIO.read(file);
} catch (Exception e) {
e.printStackTrace();
}
int width = bi.getWidth(); // 宽像素
int height = bi.getHeight(); // 高像素
java.awt.Image srcImg = ImageIO.read(file);
BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
// 2、得到画笔对象
Graphics2D g = buffImg.createGraphics();
// 3、设置对线段的锯齿状边缘处理
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(
srcImg.getScaledInstance(srcImg.getWidth(null),
srcImg.getHeight(null), java.awt.Image.SCALE_SMOOTH), 0, 0,
null);
// 4、设置水印旋转
if (null != degree) {
g.rotate(Math.toRadians(degree),(double) buffImg.getWidth() / 2,(double) buffImg.getHeight()/ 2);
}
// 水印文字字体
Font font = new Font("宋体", Font.BOLD, width/30);
// 5、设置水印文字颜色
g.setColor(color);
g.setFont(font);
// 7、设置水印文字透明度
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,alpha));
// 8、第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)
FontMetrics fm = g.getFontMetrics(font);
int textWidth = fm.stringWidth(logoText);
int widthX = (width - textWidth) / 2;
g.drawString(logoText, widthX, height/2); // 水印位置
// 9、释放资源
g.dispose();
// 10、生成图片
os = new FileOutputStream(targerPath);
System.out.println(os);
ImageIO.write(buffImg, "JPG", os);
System.out.println("图片添加水印文字完成");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != is)
is.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (null != os)
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return targerPath;
}
}
附上相关的jar包下载地址 相关PDF工具jar包下载