java根据模板导出pdf(带源码)

前言

最近做项目有个功能需要跟据pdf模板然后填充数据导出,所以就研究了下。

准备工作

  • 1.准备包
        <dependency>
               <groupId>com.itextpdf</groupId>
               <artifactId>itext-asian</artifactId>
               <version>5.2.0</version>
        </dependency>

		<dependency>
		<groupId>com.itextpdf</groupId>
		<artifactId>itextpdf</artifactId>
		<version>5.5.10</version>
	  </dependency>
  • 2.制作模板
    1.使用word做好模板另存为pdf
    在这里插入图片描述
    2.使用AdobeAcrobat打开pdf文档
    在这里插入图片描述
    3.设计表单
    这一步导入后它会自动识别哪些是表单项
    在这里插入图片描述
    双击表单项可以编辑,设置字体,多行,以及表单名等等。
    在这里插入图片描述

编码

记得把模板放入程序中,我是放在resourse目录下

1.根据模板填充数据

/**
	 * 根据pdf模板输出流
	 * @param templateFilePath
	 * @param templateFileName
	 * @param resultMap
	 * @return
	 */
	public static ByteArrayOutputStream createPdfStream(String templateFilePath, String templateFileName,
														 Map<String, String> resultMap) {

		ByteArrayOutputStream ba = new ByteArrayOutputStream();
		try {

			PdfReader reader = new PdfReader(templateFilePath + "\\" + templateFileName);
			PdfStamper stamp = new PdfStamper(reader, ba);

			//使用字体
			BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

			/* 获取模版中的字段 */
			AcroFields form = stamp.getAcroFields();

			//填充表单
			if (resultMap != null) {
				for (Map.Entry<String, String> entry : resultMap.entrySet()) {
					form.setFieldProperty(entry.getKey(), "textfont", bf, null);
					form.setField(entry.getKey(), entry.getValue());
				}
			}

			stamp.setFormFlattening(true);//不能编辑
			stamp.close();

			reader.close();
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} catch (DocumentException documentException) {
			documentException.printStackTrace();
		}
		return ba;
	}

2.导出方法

//1.准备数据源
		Map<String, String> resultMap=new HashMap<>();
		resultMap.put("name","张三");
		resultMap.put("idCard","123456789123456789");


		//2.根据模板填充数据源
		ByteArrayOutputStream pdf = createPdfStream(ClassLoader.getSystemResource("pdf").getPath(), "测试.pdf", resultMap);


		//3.输出填充后的文件
		String newPadPath="E:\\com.Janhe\\SpringBoot_v2\\src\\main\\resources\\pdf"+"\\11.pdf";
		FileOutputStream out = new FileOutputStream(newPadPath);

		out.write(pdf.toByteArray());
		out.flush();
		out.close();
		pdf.close();

之后去地址查看是否有这个文件就OK了。

本篇首发于橙寂博客转载请加上此标示。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值