首页>代码>java生成pdf,加水印,加页眉页脚,使用itext 5+版本>/PdfConvertor/src/com/hz/weep/PdfConvertor.java
package com.hz.weep;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * 文本转PDF加水印。 整理自网络:http://pirateyk.iteye.com/blog/196100
 * 
 * @author weep
 * 
 */
public class PdfConvertor {
	// txt原始文件的路径
	private static final String txtFilePath = "d:/Itext/test.txt";
	// 生成的pdf文件路径
	private static final String pdfFilePath = "d:/Itext/test.pdf";
	// 添加水印图片路径
	private static final String imageFilePath = "D:/Itext/20.jpg";
	// 生成临时文件前缀
	private static final String prefix = "tempFile";
	// 所有者密码
	private static final String OWNERPASSWORD = "12345678";

	/**
	 * txt文件转换为pdf文件
	 * 
	 * @param txtFile
	 *            txt文件路径
	 * @param pdfFile
	 *            pdf文件路径
	 * @param userPassWord
	 *            用户密码
	 * @param waterMarkName
	 *            水印内容
	 * @param permission
	 *            操作权限
	 */
	public static void generatePDFWithTxt(String txtFile, String pdfFile, String userPassWord, String waterMarkName,
			int permission) {
		try {
			// 生成临时文件
			File file = File.createTempFile(prefix, ".pdf");
			// 创建pdf文件到临时文件
			if (createPDFFile(txtFile, file)) {
				// 增加水印和加密
				waterMark(file.getPath(), pdfFile, userPassWord, OWNERPASSWORD, waterMarkName, permission);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 创建PDF文档
	 * 
	 * @param txtFilePath
	 *            txt文件路径(源文件)
	 * @param pdfFilePath
	 *            pdf文件路径(新文件)
	 */
	private static boolean createPDFFile(String txtFilePath, File file) {
		// 设置纸张
		// step1
		Document doc = new Document(PageSize.A4.rotate(), 50, 50, 50, 50);

		try {
			FileReader fileRead = new FileReader(txtFilePath);
			BufferedReader read = new BufferedReader(fileRead);
			// 设置pdf文件生成路径 step2
			PdfWriter pdfWriter = PdfWriter.getInstance(doc, new FileOutputStream(file));

			// 设置页码
			Rectangle rect = new Rectangle(36, 54, 559, 788);
			rect.setBorderColor(BaseColor.GRAY);
			pdfWriter.setBoxSize("art", rect);
			HeaderFooter header = new HeaderFooter();
			pdfWriter.setPageEvent(header);
			// 打开pdf文件 step3
			doc.open();
			// 实例化Paragraph 获取写入pdf文件的内容,调用支持中文的方法. step4
			while (read.ready()) {
				// 添加内容到pdf(这里将会按照txt文件的原始样式输出)
				doc.add(new Paragraph(read.readLine(), PdfConvertor.setChineseFont()));
			}
			// 关闭pdf文件 step5
			doc.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 在pdf文件中添加水印
	 * 
	 * @param inputFile
	 *            原始文件
	 * @param outputFile
	 *            水印输出文件
	 * @param waterMarkName
	 *            水印名字
	 */
	private static void waterMark(String inputFile, String outputFile, String userPassWord, String ownerPassWord,
			String waterMarkName, int permission) {
		try {
			PdfReader reader = new PdfReader(inputFile);
			PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
			// 设置密码
			stamper.setEncryption(userPassWord.getBytes(), ownerPassWord.getBytes(), permission, false);
			BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			int total = reader.getNumberOfPages() + 1;
			Image image = Image.getInstance(imageFilePath);
			image.setAbsolutePosition(200, 400);
			PdfContentByte under;
			int j = waterMarkName.length();
			char c = 0;
			int rise = 0;
			for (int i = 1; i < total; i++) {
				rise = 500;
				under = stamper.getUnderContent(i);
				// 添加图片
				// under.addImage(image);
				under.beginText();
				under.setColorFill(BaseColor.CYAN);
				under.setFontAndSize(base, 30);
				// 设置水印文字字体倾斜 开始
				if (j >= 15) {
					under.setTextMatrix(200, 0);
					for (int k = 0; k < j; k++) {
						under.setTextRise(rise);
						c = waterMarkName.charAt(k);
						under.showText(c + "");
						rise -= 20;
					}
				} else {
					under.setTextMatrix(180, 0);
					for (int k = 0; k < j; k++) {
						under.setTextRise(rise);
						c = waterMarkName.charAt(k);
						under.showText(c + "");
						rise -= 18;
					}
				}
				// 字体设置结束
				under.endText();
				// 画一个圆
				// under.ellipse(250, 450, 350, 550);
				// under.setLineWidth(1f);
				// under.stroke();
			}
			stamper.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 设置中文
	 * 
	 * @return Font
	 */
	private static Font setChineseFont() {
		BaseFont base = null;
		Font fontChinese = null;
		try {
			base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
			fontChinese = new Font(base, 12, Font.NORMAL);
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fontChinese;
	}

	public static void main(String[] args) {
		// PdfWriter.ALLOW_PRINTING为无法复制- -
		generatePDFWithTxt(txtFilePath, pdfFilePath, "123", "一个测试用的水印", PdfWriter.ALLOW_PRINTING);
	}
}
最近下载更多
微信网友_6569863629787136  LV1 2023年7月20日
18120344519  LV4 2023年3月20日
1358849392  LV21 2022年11月11日
bearloadprogress  LV7 2022年7月15日
703129100  LV2 2021年12月13日
nyb4613  LV8 2021年11月15日
8战魂5无双8  LV43 2021年10月30日
thenyoucan  LV2 2021年5月17日
1145304128  LV12 2021年5月14日
myielm  LV1 2021年1月27日
最近浏览更多
微信网友_6569863629787136  LV1 2023年7月20日
18120344519  LV4 2023年3月20日
zj0010722  LV2 2023年3月2日
SJIGNKLI  LV2 2022年12月15日
1358849392  LV21 2022年11月11日
whfuai  LV14 2022年7月22日
bearloadprogress  LV7 2022年7月15日
benyan  LV8 2022年6月23日
ma小跳  LV5 2022年5月19日
xytthy  LV3 2022年4月25日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友