日期:2014-05-16 浏览次数:20476 次
package com.fruitking.testpdf.util; import java.awt.Color; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import com.lowagie.text.BadElementException; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Element; import com.lowagie.text.Font; import com.lowagie.text.Image; import com.lowagie.text.Paragraph; import com.lowagie.text.Phrase; import com.lowagie.text.pdf.BaseFont; import com.lowagie.text.pdf.ColumnText; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfGState; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfPageEventHelper; import com.lowagie.text.pdf.PdfReader; import com.lowagie.text.pdf.PdfStamper; import com.lowagie.text.pdf.PdfWriter; public class PDFCreate2WaterMark { /** * 根据图片文件路径构建一个图片对象 * @param waterMarkFullFilePath * @param xPosition * @param yPosition * @return * @throws BadElementException * @throws MalformedURLException * @throws IOException */ private Image getWaterMarkImage(String waterMarkFullFilePath,float xPosition,float yPosition)throws BadElementException, MalformedURLException, IOException{ Image waterMarkImage = Image.getInstance(waterMarkFullFilePath); waterMarkImage.setAbsolutePosition(xPosition, yPosition);//坐标 waterMarkImage.setRotation(-20);//旋转 弧度 waterMarkImage.setRotationDegrees(-45);//旋转 角度 waterMarkImage.scalePercent(100);//依照比例缩放 return waterMarkImage; } /** * 对一个图片对象设置展示位置等信息,该对象重复利用,减少PDF文件大小 * @param waterMarkImage * @param xPosition * @param yPosition * @return */ private Image getSingletonWaterMarkImage(Image waterMarkImage,float xPosition,float yPosition){ waterMarkImage.setAbsolutePosition(xPosition, yPosition);//坐标 waterMarkImage.setRotation(-20);//旋转 弧度 waterMarkImage.setRotationDegrees(-45);//旋转 角度 waterMarkImage.scalePercent(100);//依照比例缩放 return waterMarkImage; } /** * 对于已存在的PDF文件增加图片水印 * 图片水印按照两列三行模式,并旋转45度正斜形式添加水印图片 * @param pdfInputFile * @param pdfOutputFile * @param waterMarkFullFilePath */ public void addPictureWaterMark(String pdfInputFile,String pdfOutputFile,String waterMarkFullFilePath) { PdfStamper pdfStamper = null; PdfReader reader = null; try { //构造需要添加水印的PDF文件对象 reader = new PdfReader(pdfInputFile); int pdfFileTotalPages = reader.getNumberOfPages() + 1; //创建添加水印后的PDF文件对象 OutputStream pdfOutputStream =