手机识别二维码生成到pdf中

Java生成手机可识别的二维码的开源包很多,但把生成的二维码放到pdf中不是很容易。

Java生成pdf的方式有两种:直接生成pdf的document,然后输出到outputStream;另一种使用pdf的模板,通过AcroFields form = stamper.getAcroFields()获取模板中各个字段,然后动态填充各个字段值来生成pdf。

通过模板生成pdf的好处是模板可以按照需求进行修改。

本文采用了iText的生成二维码的对象,并填充到模板,进而生成了pdf

private void fillPDFForm(Map<String, Object> model, PdfStamper stamper)
			throws IOException, DocumentException {
		AcroFields form = stamper.getAcroFields();

		Iterator<Entry<String, Object>> keyIt = model.entrySet().iterator();
		while (keyIt.hasNext()) {
			Entry<String, Object> entry = keyIt.next();
			if(entry.getKey().equals("snBarCode"))continue;
			form.setField(entry.getKey(), entry.getValue().toString());
		}
		if (model.containsKey("snBarCode")) {
			try {
				BarcodeQRCode qrcode = new BarcodeQRCode(model.get("snBarCode").toString(), 1, 1, null);
				Image img = qrcode.getImage();
				PushbuttonField bt = form.getNewPushbuttonFromField("snBarCode");
				bt.setLayout(PushbuttonField.LAYOUT_ICON_ONLY);
				bt.setProportionalIcon(false);
				bt.setImage(img);
				form.replacePushbuttonField("snBarCode", bt.getField());
			} catch (Exception e) {
				// not a valid code, do nothing
			}
		}
	}


其中,创建pdf模板时,必须把要存放二维码的字段定义为button,在这里就是PushbuttonField ,而后去用生成的二维码图像填充该button


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值