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

本文档介绍了如何在Java项目中利用iText库生成PDF文件,并添加水印。首先,在pom.xml文件中添加iText依赖。然后,通过示例代码展示从web层到业务层的实现过程,包括创建PDF文档、设置页面大小、添加内容、创建水印等步骤。最后,展示了生成的PDF效果。
摘要由CSDN通过智能技术生成

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

		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itextpdf</artifactId>
			<version>5.4.2</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf.tool</groupId>
			<artifactId>xmlworker</artifactId>
			<version>5.4.1</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>itext-asian</artifactId>
			<version>5.2.0</version>
		</dependency>
		<dependency>
			<groupId>org.xhtmlrenderer</groupId>
			<artifactId>flying-saucer-pdf</artifactId>
			<version>9.0.3</version>
		</dependency>

相关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;
imp

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值