根据模板生成pdf

必备: 1.Adobe Acrobat pro软件(其它pdf编辑器也行,我最初用的迅捷pdf编辑器) 2.itext的jar包

制作模板: 1.用word把文档编辑好,若用的word2007,直接可以另存为pdf文件,暂定名为test.pdf。(网上也可以直接word转pdf:http://app.xunjiepdf.com/word2pdf) 2.用Adobe Acrobat pro打开test.pdf,点击 ‘准备表单’,再点击 ‘选择文件’,进行编辑 输入图片说明

制作文本域,并设置属性,字体等。

输入图片说明

制作好模板demo.pdf好,开始写代码。

// 利用模板生成pdf
public static void fillTemplate() {
	// 模板路径
	String templatePath = "D/demo.pdf";
	// 生成的新文件路径
	String newPDFPath = "D/new.pdf";
	PdfReader reader;
	FileOutputStream out;
	ByteArrayOutputStream bos;
	PdfStamper stamper;
	try {
		out = new FileOutputStream(newPDFPath);// 输出流
		reader = new PdfReader(templatePath);// 读取pdf模板
		bos = new ByteArrayOutputStream();
		stamper = new PdfStamper(reader, bos);
		AcroFields form = stamper.getAcroFields();
                    BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",                 BaseFont.NOT_EMBEDDED);
                    form.addSubstitutionFont(baseFont);

		String[] str = { "qewqe", "3242", "中国" };
		int i = 0;
		Iterator<String> it = form.getFields().keySet().iterator();
		while (it.hasNext()) {
			String name = it.next().toString();
			System.out.println(name);
			form.setField(name, str[i++]);
		}
                    );
                    // 设为true不可再编辑
		stamper.setFormFlattening(true);
		stamper.close();

		Document doc = new Document();
		PdfCopy copy = new PdfCopy(doc, out);
		doc.open();
		PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
		copy.addPage(importPage);
		doc.close();

	} catch (IOException e) {
		System.out.println(e);
	} catch (DocumentException e) {
		System.out.println(e);
	}

}

其中遇到文本域内为中文不显示,添加 BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

转载于:https://my.oschina.net/u/3529861/blog/1505284

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值