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