使用java实现对PDF增加文字水印功能
使用iText处理PDF文件非常强大,本章节描述如何实现对现有PDF文件增加文字水印功能。
?
第一步:创建一个新工程,引入附件中的所有jar包。
??????????? iText-2.0.8.jar
??????????? iTextAsian.jar
????????????iTextAsianCmaps.jar
?
第二步:代码实现。
/** * This file created at 2012-6-14. * * Copyright (c) 2002-2012, Inc. All rights reserved. */package com.bingosoft.test;import java.awt.Color;import java.io.FileOutputStream;import java.io.IOException;import com.lowagie.text.DocumentException;import com.lowagie.text.pdf.BaseFont;import com.lowagie.text.pdf.PdfContentByte;import com.lowagie.text.pdf.PdfReader;import com.lowagie.text.pdf.PdfStamper;/** * <code>{@link Test}</code> * * TODO : document me * * @author huangjinping */public class Test { public static void main(String[] args) throws DocumentException,IOException {// 待加水印的文件PdfReader reader = new PdfReader("file:/F:/pdfTest/WebContent/IKAnalyzer.pdf");// 加完水印的文件PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("F:/pdfTest/WebContent/IKAnalyzer_water.pdf"));int total = reader.getNumberOfPages() + 1;PdfContentByte content;// 设置字体BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED);// 水印文字String waterText = "水印文字!";int j = waterText.length(); // 文字长度char c = 0;int high = 0;// 高度// 循环对每页插入水印for (int i = 1; i < total; i++) {// 水印的起始high = 500;content = stamper.getUnderContent(i);// 开始content.beginText();// 设置颜色content.setColorFill(Color.GRAY);// 设置字体及字号content.setFontAndSize(base, 18);// 设置起始位置content.setTextMatrix(400, 780);// 开始写入水印for (int k = 0; k < j; k++) {content.setTextRise(14);c = waterText.charAt(k);// 将char转成字符串content.showText(c + "");high -= 5;}content.endText();}stamper.close();}}
?
?