java 使用itext导出PDF(带水印)清晰易懂

看到同事做了一个导出pdf的功能,以前没接触过,记录一下留作后用。
项目使用了maven管理工具,pom文件加入相关依赖如下:

		
			com.itextpdf
			itextpdf
			5.4.2
		
		
			com.itextpdf.tool
			xmlworker
			5.4.1
		
		
			com.itextpdf
			itext-asian
			5.2.0
		
		
			org.xhtmlrenderer
			flying-saucer-pdf
			9.0.3
		

相关js如下:
function exportPDF() {

top.$.jBox.confirm("确认要导出用户数据吗?", "系统提示", function(v, h, f) {
				if (v == "ok") {
					var URL="${ctx}/employeemark/employeeMark/getPdf?id=${employeeMark.id}";
					location.href=URL;
				}
			}, {
				buttonsFocus : 1
			});
			top.$('.jbox-body .jbox-icon').css('top', '55px');
		
	}

web层如下:

@RequestMapping(value = "getPdf")
public String getPdf(HttpServletRequest request,HttpServletResponse response, RedirectAttributes redirectAttributes)       throws Exception {
	String strId = request.getParameter("id");
			if (strId != null && strId.length() > 0) {
		EmployeeMark employeeMark = employeeMarkService.get(strId);
		
		String date = DateUtil.dateToStrEn(new Date(), DateUtil.DEFAULT_PATTERN);
	
		String filePath = Global.getAdminPath()+"/tempFile";
	
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		 String inPutPath = filePath+"/tempPDF"+System.currentTimeMillis()+".pdf";
	
    	 String outPutPath = filePath+"/PDFWater"+System.currentTimeMillis()+".pdf";
  
         File exportFile = new File(inPutPath);  
         exportFile.createNewFile();  
         System.err.println(exportFile);
         PdfUtil p =  new PdfUtil(exportFile);
         //生成pdf临时文件  未添加水印
         p.generatePDF(employeeMark); 
         //给pdf文件添加水印
         String waterStr="保密保密";
         PdfUtil.waterMark(inPutPath, outPutPath, waterStr);
         //导出pdf文件
         PdfUtil.exportPDF(request, response, outPutPath, employeeMark.getTitle(),inPutPath);
    	 return null;
		
	} else {
		addMessage(redirectAttributes, "未获得当前记录的有效标识!");
	}
	return "redirect:" + Global.getAdminPath() + "/employeemark/employeeMark/form?id="+strId;

}

许多业务都是在until里面实现的,
import java.awt.FontMetrics;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JLabel;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.jgly.oa.common.utils.StringUtils;
import com.jgly.oa.modules.mark.employeemark.entity.EmployeeMark;
import com.jgly.oa.modules.mark.employeemark.entity.EmployeeMarkDetail;
import com.jgly.oa.modules.mark.markitem.entity.MarkItem;
import com.jgly.oa.modules.mark.markitem.entity.MarkItemDetail;
import com.jgly.oa.modules.sys.utils.DictUtils;
public class PdfUtil {

Document document;
private static Font headfont;// 设置字体大小

private static Font keyfont;// 设置字体大小

private static Font textfont;// 设置字体大小

int maxWidth = 520;

static {

	BaseFont bfChinese;

	try {

		// bfChinese =
		// BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);

		bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

		headfont = new Font(bfChinese, 10, Font.BOLD);// 设置字体大小

		keyfont = new Font(bfChinese, 8, Font.BOLD);// 设置字体大小

		textfont = new Font(bfChinese, 8, Font.NORMAL);// 设置字体大小

	} catch (Exception e) {

		e.printStackTrace();

	}

}

public PdfUtil(File file) {
	document = new Document();// 建立一个Document对象
	document.setPageSize(PageSize.A4);// 设置页面大小

	try {

		PdfWriter.getInstance(document, new FileOutputStream(file));

		document.open();

	} catch (Exception e) {

		e.printStackTrace();

	}

}

public PdfPCell createCell(String value, Font font, int align) {

	PdfPCell cell = new PdfPCell();

	cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

	cell.setHorizontalAlignment(align);

	cell.setPhrase(new Phrase(value, font));

	return cell;

}

public PdfPCell createCell(String value, Font font, int align, float width) {

	PdfPCell cell = new PdfPCell();

	cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

	cell.setHorizontalAlignment(align);

	cell.setPhrase(new Phrase(value, font));

	return cell;

}

public PdfPCell createCell(String value, Font keyfont2) {

	PdfPCell cell = new PdfPCell();

	cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

	cell.setHorizontalAlignment(Element.ALIGN_CENTER);

	cell.setPhrase(new Phrase(value, keyfont2));

	return cell;

}

public PdfPCell createCell(String value, Font font, int align, int colspan) {

	PdfPCell cell = new PdfPCell();

	cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

	cell.setHorizontalAlignment(align);

	cell.setRowspan(colspan);

	cell.setPhrase(new Phrase(value, font));

	return cell;

}

public PdfPCell createCell(String value, Font font, int align, int colspan, boolean boderFlag) {

	PdfPCell cell = new PdfPCell();

	cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

	cell.setHorizontalAlignment(align);

	cell.setColspan(colspan);

	cell.setPhrase(new Phrase(value, font));

	cell.setPadding(3.0f);

	if (!boderFlag) {

		cell.setBorder(0);

		cell.setPaddingTop(15.0f);

		cell.setPaddingBottom(8.0f);

	}

	return cell;

}

public PdfPTable createTable(int colNumber) {

	PdfPTable table = new PdfPTable(colNumber);

	try {

		table.setTotalWidth(maxWidth);

		table.setLockedWidth(true);

		table.setHorizontalAlignment(Element.ALIGN_CENTER);

		table.getDefaultCell().setBorder(1);

	} catch (Exception e) {

		e.printStackTrace();

	}

	return table;

}

public PdfPTable createTable(float[] widths) {

	PdfPTable table = new PdfPTable(widths);

	try {

		table.setTotalWidth(maxWidth);

		table.setLockedWidth(true);

		table.setHorizontalAlignment(Element.ALIGN_CENTER);

		table.getDefaultCell().setBorder(1);

	} catch (Exception e) {

		e.printStackTrace();

	}

	return table;

}

public PdfPTable createBlankTable() {

	PdfPTable table = new PdfPTable(1);

	table.getDefaultCell().setBorder(0);

	table.addCell(createCell("", keyfont));

	table.setSpacingAfter(20.0f);

	table.setSpacingBefore(20.0f);

	return table;

}

public void generatePDF(EmployeeMark employeeMark) throws Exception {
	float[] columnWidths = { 30, 50, 10, 10 };

	PdfPTable table = createTable(columnWidths);

	table.setLockedWidth(true);
	// 标题
	table.addCell(createCell(employeeMark.getTitle(), headfont, Element.ALIGN_CENTER, 4, false));
	// 评分人员类型

	// 员工信息
	String nameStr1 = "";
	String type = employeeMark.getType();
	if (StringUtils.equals(type, "0")) {
		nameStr1 = employeeMark.getTalentPoolInfo().getName() + "(待入职)(" + employeeMark.getOfficeName() + ")";
	} else {
		nameStr1 = employeeMark.getUser().getName() + "(" + employeeMark.getOfficeName() + ")";
	}
	String nameStr2 = employeeMark.getCreateBy().getName();
	if (employeeMark.getCreateBy().getOffice() != null && !"".equals(employeeMark.getCreateBy().getOffice().getName())) {
		nameStr2 += "(" + employeeMark.getCreateBy().getOffice().getName() + ")";
	}
	table.addCell(createCell("员工:" + nameStr1, keyfont, Element.ALIGN_LEFT, 1, false));
	table.addCell(createCell("评分人:" + "1111111", keyfont, Element.ALIGN_LEFT, 1, false));
	// table.addCell(createCell("描 述:"+employeeMark.getDescribe(),
	// keyfont,Element.ALIGN_LEFT,2,false));//描述
	DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	String date = format.format(employeeMark.getCreateDate());
	table.addCell(createCell("日期:" + date, keyfont, Element.ALIGN_RIGHT, 2, false));
	// 表格明细
	List detailList = employeeMark.getEmployeeMarkDetailList();
	if (detailList != null && detailList.size() > 0) {

		for (int i = 0; i < detailList.size(); i++) {
			EmployeeMarkDetail employeeMarkDetail = detailList.get(i);
			MarkItem item = employeeMarkDetail.getMainDetailId();
			if (item != null && item.getMarkItemDetailList() != null && item.getMarkItemDetailList().size() > 0) {
				List itemDetailList = item.getMarkItemDetailList();
				// item表头
				String dictLabel = DictUtils.getDictLabel(item.getItemType(), "modelItemType", "");

				table.addCell(createCell(item.getItemTitle() + "(" + dictLabel + ")", keyfont, Element.ALIGN_CENTER));
				table.addCell(createCell("描述", keyfont, Element.ALIGN_CENTER));
				table.addCell(createCell("分数", keyfont, Element.ALIGN_CENTER));
				table.addCell(createCell("评分", keyfont, Element.ALIGN_CENTER));

				// item内容
				table.addCell(createCell(item.getDescribe(), textfont, Element.ALIGN_CENTER, itemDetailList.size()));
				for (int j = 0; j < itemDetailList.size(); j++) {
					MarkItemDetail itemDetail = itemDetailList.get(j);
					table.addCell(createCell(itemDetail.getDescribe(), textfont, Element.ALIGN_LEFT));
					table.addCell(createCell(itemDetail.getScore(), textfont, Element.ALIGN_CENTER));
					if (j == 0) {
						table.addCell(createCell(employeeMarkDetail.getScores(), textfont, Element.ALIGN_CENTER, itemDetailList.size()));
					}
				}
			}
		}
	} else {
		table.addCell(createCell("暂无数据", headfont, Element.ALIGN_CENTER, 4, true));
	}

	table.addCell(createCell("总分:" + employeeMark.getScores(), keyfont, Element.ALIGN_CENTER, 1, true));
	String describe = employeeMark.getDescribe();
	String remarks = employeeMark.getRemarks();
	if (!"".equals(describe)) {
		remarks += "\n" + describe;
	}
	table.addCell(createCell(remarks, keyfont, Element.ALIGN_LEFT, 3, true));
	document.add(table);
	document.close();

}

/**
 * 添加水印
 * 
 * @param inputFile
 *            原PDF文件路径
 * @param outputFile
 *            添加水印后的PDF文件路径
 * @param waterMarkName
 *            水印文字
 */
public static void waterMark(String inputFile, String outputFile, String waterMarkName) {
	int interval = -5;
	try {
		PdfReader reader = new PdfReader(inputFile);
		PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));

		BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);

		Rectangle pageRect = null;
		PdfGState gs = new PdfGState();
		// 设置透明度
		gs.setFillOpacity(0.1f);
		gs.setStrokeOpacity(0.4f);
		int total = reader.getNumberOfPages() + 1;

		JLabel label = new JLabel();
		FontMetrics metrics;
		int textH = 0;
		int textW = 0;
		label.setText(waterMarkName);
		metrics = label.getFontMetrics(label.getFont());
		textH = metrics.getHeight();
		textW = metrics.stringWidth(label.getText());

		PdfContentByte under;
		for (int i = 1; i < total; i++) {
			pageRect = reader.getPageSizeWithRotation(i);
			under = stamper.getOverContent(i);
			under.saveState();
			under.setGState(gs);
			under.beginText();
			under.setFontAndSize(base, 20);

			// 水印文字成30度角倾斜
			// 你可以随心所欲的改你自己想要的角度
			for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 3) {
				for (int width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW * 2) {
					under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, 30);
				}
			}
			// 添加水印文字
			under.endText();
		}

		// 一定不要忘记关闭流
		stamper.close();
		reader.close();

	} catch (Exception e) {
		e.printStackTrace();
	}
}

/**
 * 导出PDF
 * 
 * @param req
 * @param resp
 * @param downloadFile
 *            要下载的文件的文件路径 (路径到文件名称:.../XXX.pdf)
 * @param filename
 *            下载到本地的文件名称
 */
public static void exportPDF(HttpServletRequest req, HttpServletResponse resp, String downloadFile, String filename, String tempFile) {

	DataInputStream in = null;
	OutputStream out = null;
	try {
		resp.reset();// 清空输出流

		String resultFileName = filename + System.currentTimeMillis() + ".pdf";
		resultFileName = URLEncoder.encode(resultFileName, "UTF-8");
		resp.setCharacterEncoding("UTF-8");
		resp.setHeader("Content-disposition", "attachment; filename=" + resultFileName);// 设定输出文件头
		resp.setContentType("application/pdf");// 定义输出类型
		// 输入流:本地文件路径
		in = new DataInputStream(new FileInputStream(new File(downloadFile)));
		// 输出流
		out = resp.getOutputStream();
		// 输出文件
		int bytes = 0;
		byte[] bufferOut = new byte[1024];
		while ((bytes = in.read(bufferOut)) != -1) {
			out.write(bufferOut, 0, bytes);
		}
	} catch (Exception e) {
		e.printStackTrace();
		resp.reset();
		try {
			OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream(), "UTF-8");
			String data = "";
			writer.write(data);
			writer.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	} finally {
		if (null != in) {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (null != out) {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// 删除临时文件
	File file = new File(downloadFile);
	file.delete();
	File file2 = new File(tempFile);
	file2.delete();

}

}

效果如下
java 使用itext导出PDF(带水印)清晰易懂_第1张图片

你可能感兴趣的:(java 使用itext导出PDF(带水印)清晰易懂)