使用itext加图片水印或文字水印

概述:使用itext 技术给pdf加水印方法。

实现原理:在不管是流还是临时pdf 预览之前。需先  生成不带水印的pdf,然后在通过itext工具方法生成带水印的pdf 

依赖jar包:i-text-asian.jar   , itextpdf-5.5.10.jar

步骤一:做成工具类。

工具类代码及说明:分图片水印和文字水印,可根据具体需求使用。

package com.test.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSmartCopy;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;

public class ProcessPDF {
	
	public static void main(String[] args) {
        try {
//            List<InputStream> pdfs = new ArrayList<InputStream>();
//            pdfs.add(new FileInputStream("e:\\123.pdf"));
//            pdfs.add(new FileInputStream("e:\\456.pdf"));
//            OutputStream output = new FileOutputStream("e:\\789.pdf");
//            concatPDFs(pdfs, output, true);
        	
        	ProcessPDF.addPdfImgMark("E:\\file2\\1502349579058.pdf", 
					  "E:\\file2" + File.separator + "mark" + File.separator + "mark1111upGRAY.pdf", 
		              "C:\\Users\\Administrator\\Desktop\\1127.png",
		              300,350);
        	ProcessPDF.addPdfTextMark("E:\\file2\\1502349579058.pdf", 
					"E:\\file2" + File.separator + "mark" + File.separator + "mark2222upGRAY.pdf", "水印文字", 300,
					350);
        	
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	
    public static File mergeFiles(String[] files, String result, boolean smart) throws IOException, DocumentException {
        Document document = new Document();
        PdfCopy copy;
        if (smart)
            copy = new PdfSmartCopy(document, new FileOutputStream(result));
        else
            copy = new PdfCopy(document, new FileOutputStream(result));
        document.open();
        PdfReader[] reader = new PdfReader[files.length];
        for (int i = 0; i < files.length; i++) {
            reader[i] = new PdfReader(files[i]);
            copy.addDocument(reader[i]);
            copy.freeReader(reader[i]);
            reader[i].close();
        }
        document.close();
        return new File(result);
    }
	
	/**
	 * 合并pdf
	 * 
	 * @param streamOfPDFFiles
	 * @param outputStream
	 * @param paginate
	 */
	public static void concatPDFs(List<InputStream> streamOfPDFFiles,
            OutputStream outputStream, boolean paginate) {

        Document document = new Document();
        try {
            List<InputStream> pdfs = streamOfPDFFiles;
            List<PdfReader> readers = new ArrayList<PdfReader>();
            int totalPages = 0;
            Iterator<InputStream> iteratorPDFs = pdfs.iterator();

            // Create Readers for the pdfs.
            while (iteratorPDFs.hasNext()) {
                InputStream pdf = iteratorPDFs.next();
                PdfReader pdfReader = new PdfReader(pdf);
                readers.add(pdfReader);
                totalPages += pdfReader.getNumberOfPages();
            }
            // Create a writer for the outputstream
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);

            document.open();
            BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
                    BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
            // data

            PdfImportedPage page;
            int currentPageNumber = 0;
            int pageOfCurrentReaderPDF = 0;
            Iterator<PdfReader> iteratorPDFReader = readers.iterator();

            // Loop through the PDF files and add to the output.
            while (iteratorPDFReader.hasNext()) {
                PdfReader pdfReader = iteratorPDFReader.next();

                // Create a new page in the target for each source page.
                while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                    document.newPage();
                    pageOfCurrentReaderPDF++;
                    currentPageNumber++;
                    page = writer.getImportedPage(pdfReader,
                            pageOfCurrentReaderPDF);
                    cb.addTemplate(page, 0, 0);

                    // Code for pagination.
                    if (paginate) {
                        cb.beginText();
                        cb.setFontAndSize(bf, 9);
                        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
                                + currentPageNumber + " of " + totalPages, 520,
                                5, 0);
                        cb.endText();
                    }
                }
                pageOfCurrentReaderPDF = 0;
            }
            outputStream.flush();
            document.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (document.isOpen())
                document.close();
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
	
	/**
	 * 
	 * <br>
	 * <p>
	 * Description: 给pdf文件添加水印 <br>
	 * <p><br/>
	 * <p>
	 * 
	 * @param InPdfFile
	 *            要加水印的原pdf文件路径
	 * @param outPdfFile
	 *            加了水印后要输出的路径
	 * @param markImagePath
	 *            水印图片路径
	 * @param imgWidth
	 *            图片横坐标
	 * @param imgHeight
	 *            图片纵坐标
	 * @throws Exception
	 * @see void
	 */
	public static void addPdfImgMark(String InPdfFile, String outPdfFile, String markImagePath,int imgWidth, int imgHeight) throws Exception {  
		PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());  
		PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(new File(outPdfFile)));  
		
		PdfContentByte under;
		
		PdfGState gs1 = new PdfGState();  
		gs1.setFillOpacity(0.3f);// 透明度设置
	    
		Image img = Image.getInstance(markImagePath);// 插入图片水印
		
		img.setAbsolutePosition(imgWidth, imgHeight); // 坐标
		img.setRotation(-20);// 旋转 弧度
		img.setRotationDegrees(45);// 旋转 角度
		// img.scaleAbsolute(200,100);//自定义大小
		// img.scalePercent(50);//依照比例缩放
		
		int pageSize = reader.getNumberOfPages();// 原pdf文件的总页数
		for(int i = 1; i <= pageSize; i++) {  
			under = stamp.getUnderContent(i);// 水印在之前文本下
			// under = stamp.getOverContent(i);//水印在之前文本上
			under.setGState(gs1);// 图片水印 透明度
			under.addImage(img);// 图片水印
		}  
		
		stamp.close();// 关闭
		// // 删除不带水印文件
//		File tempfile = new File(InPdfFile);  		
//		if(tempfile.exists()) {  		
//			tempfile.delete();  
//		}  
		
	}  
	
	/**
	 * 
	 * <br>
	 * <p>
	 * Description: 给pdf文件添加水印<br>
	 * 
	 * @param InPdfFile
	 *            要加水印的原pdf文件路径
	 * @param outPdfFile
	 *            加了水印后要输出的路径
	 * @param textMark
	 *            水印文字
	 * @param textWidth
	 *            文字横坐标
	 * @param textHeight
	 *            文字纵坐标
	 * @throws Exception
	 * @see void
	 */
	public static void addPdfTextMark(String InPdfFile, String outPdfFile, String textMark,int textWidth,  
            int textHeight) throws Exception {  
		PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());  
		PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(new File(outPdfFile)));  
		
		PdfContentByte under;
	    
		BaseFont font = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", "Identity-H", true);// 使用系统字体
	    
		int pageSize = reader.getNumberOfPages();// 原pdf文件的总页数
		for(int i = 1; i <= pageSize; i++) {  
			under = stamp.getUnderContent(i);// 水印在之前文本下
			// under = stamp.getOverContent(i);//水印在之前文本上
			under.beginText();  
			under.setColorFill(BaseColor.GRAY);// 文字水印 颜色
			under.setFontAndSize(font, 38);// 文字水印 字体及字号
			under.setTextMatrix(textWidth, textHeight);// 文字水印 起始位置
			under.showTextAligned(Element.ALIGN_CENTER, textMark, textWidth, textHeight, 45);
			under.endText();
		}  
		
		stamp.close();// 关闭
	}  
	
	
}


注意事项:文字水印方法中,字体的文件路径

步骤二:在合适的地方调用上述工具方法

public static void main(String[] args) {
        try {
//            List<InputStream> pdfs = new ArrayList<InputStream>();
//            pdfs.add(new FileInputStream("e:\\123.pdf"));
//            pdfs.add(new FileInputStream("e:\\456.pdf"));
//            OutputStream output = new FileOutputStream("e:\\789.pdf");
//            concatPDFs(pdfs, output, true);
        	
        	ProcessPDF.addPdfImgMark("E:\\file2\\1502349579058.pdf", 
					  "E:\\file2" + File.separator + "mark" + File.separator + "mark1111upGRAY.pdf", 
		              "C:\\Users\\Administrator\\Desktop\\1127(图片水印).png",
		              300,350);
        	ProcessPDF.addPdfTextMark("E:\\file2\\1502349579058.pdf", 
					  "E:\\file2" + File.separator + "mark" + File.separator + "mark2222upGRAY.pdf", "要加的水印文字", 300, 350);
        	
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值