使用iText填充pdf表单

最近项目中用到了下载pdf回单的功能。需要把内容动态的填入pdf并打印,觉得这个功能挺实用的,所以决定用博客记录一下方便以后使用。

一、首先我们需要安装Adoble Acrobat XI Pro,因为Adodle Reader没有表单编辑功能。

     1、先用word只做好模板,另存为pdf格式,然后用pdf打开,启用表单编辑功能,设置好表单域。效果如图:

        

 2、将项目src下讲一个template文件夹,将这个模板放入template文件夹中。

 3、下载两个jar包iText.jar和iTextAsian.jar包放入lib中


二编写代码如下:

public class CreatePDF {
	

	@Test
	public void testCreatePDF() throws Exception{
		Map map=new HashMap();
		List list=new ArrayList();
		map.put("UserName", "张三");
		map.put("Account","657676767766727272");
		map.put("Date", "1997-09-18");
		map.put("Balance", "1000");
		list.add(map);
		convertTransData(list);
		System.out.println("执行完毕");
	}
	
	/**
	 * 将数据转换为输入字节流
	 * */
	protected InputStream convertTransData(List input)
			throws Exception {
			if (input == null || input.isEmpty() || input.get(0) == null)
				return null;
			String template="/template/FinanceBuy.pdf";
			try {
				InputStream in =
					this.getClass().getResourceAsStream(template);
				ByteArrayOutputStream out =
					(ByteArrayOutputStream)generate(
							new PdfReader(in),
						(Map) input.get(0));

				ByteArrayInputStream ret =
					new ByteArrayInputStream(out.toByteArray());
				//将pdf字节流输出到文件流
				OutputStream fos = new FileOutputStream("D:/FinanceBuy.pdf");
				fos.write(out.toByteArray());
				fos.close();
				out.close();
				return ret;
			} catch (Exception e) {
				throw new Exception(e);
			}
		}
	
	/**
	 *  将数据,填入pdf表单域
	 * 
	 * */
	public static OutputStream generate(PdfReader template, Map data)
			throws Exception {

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

		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();

			PdfStamper stamp = new PdfStamper(template, out);
			AcroFields form = stamp.getAcroFields();

			// set the field values in the pdf form
			for (Iterator it = data.keySet().iterator(); it.hasNext();) {
				String key = (String) it.next();
				String value = (String) data.get(key);
				form.setFieldProperty(key, "textfont", bfChinese, null);
				form.setField(key, value);

			}

			stamp.setFormFlattening(true);
			stamp.close();
			template.close();
			
			return out;

		}

		catch (Exception e) {

			e.printStackTrace();

			return null;
		}

	}

}



运行test,在D盘中可看到pdf文件打开效果如下:



  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值