使用iText填充pdf表单

  • Post author:
  • Post category:其他


最近项目中用到了下载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文件打开效果如下:




版权声明:本文为polo_longsan原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。