生成二维码PDF文件
public class JitQrCodeUtil {
private static final String FONT_URL = ServletHelper.BootPath() + "/resources/pdf/MSYH.TTF";
public static void createQrCodePdf(AList entityList, LinkedHashMap<String,String> contentMap,String pdfPath){
BaseFont baseFont;
try {
baseFont = BaseFont.createFont(FONT_URL, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font font = new Font(baseFont, 8, Font.NORMAL);
int height = PdfUnitConversion.mm2points(60 - 3);
int width = PdfUnitConversion.mm2points(80 - 4);
Rectangle pageSize = new Rectangle(width, height);
Document document = new Document(pageSize, 10, 10, 10, 0);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfPath));
document.open();
PdfContentByte cb = writer.getDirectContent();
for (AData entity : entityList.getList()) {
document.newPage();
String keyName = entity.getString("key_name");
PdfPTable table = getPdfPTable(2, new int[]{65, 35});
table.setWidthPercentage(100);
PdfPTable msgTable = new PdfPTable(1);
Phrase phrase = new Phrase();
int contentLen = 0;
for (Map.Entry<String, String> contentEntry : contentMap.entrySet()) {
String aValue = entity.getString(contentEntry.getKey());
if (aValue != null){
String value = contentEntry.getValue();
phrase.add(new Chunk(value + ":" + aValue,font));
phrase.add(Chunk.NEWLINE);
if (++contentLen >= 9){
break;
}
}
}
PdfPCell msgPhrase = new PdfPCell();
msgPhrase.addElement(phrase);
msgPhrase.setBorder(0);
msgPhrase.setHorizontalAlignment(Element.ALIGN_CENTER);
msgPhrase.setVerticalAlignment(Element.ALIGN_CENTER);
msgTable.addCell(msgPhrase);
table.addCell(msgTable);
PdfPTable qrCodeTable = new PdfPTable(1);
Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BarcodeQRCode qrcode = new BarcodeQRCode(keyName, 1, 1, hints);
Image img = qrcode.getImage();
qrCodeTable.addCell(img);
Font keyNameFont = new Font(baseFont, 10, Font.NORMAL);
Phrase keyNameParse = new Phrase(keyName,keyNameFont);
PdfPCell codeCell = new PdfPCell(keyNameParse);
codeCell.setBorder(0);
codeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
qrCodeTable.addCell(codeCell);
table.addCell(qrCodeTable);
document.add(table);
}
document.close();
} catch (DocumentException | IOException e) {
e.printStackTrace();
}
}
public static PdfPTable getPdfPTable(int column, int[] tableWidth) throws DocumentException {
PdfPTable table = new PdfPTable(column);
table.setWidths(tableWidth);
table.getDefaultCell().setBorder(0);
table.setWidthPercentage(100);
return table;
}
}