package com.brilliance.utils; import com.brilliance.bo.Receipt; import com.itextpdf.forms.fields.PdfFormField; import com.itextpdf.io.source.ByteArrayOutputStream; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.Phrase; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.*; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; public class ReceiptUtils { public static void main(String[] args) throws Exception { // 创建一个Date对象,表示当前日期和时间 Date now = new Date(); // 创建一个SimpleDateFormat对象,并定义日期格式 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); // 使用format方法格式化日期 String formattedDate = dateFormat.format(now); String str = new Date().getTime()+""; String id = formattedDate + str.substring(str.length()-8); String templateFilePath = ".\\doc\\receipt.pdf"; String pdfFilePath = "C:\\Users\\zhaojg\\.m2\\repository\\cn\\receipt"+id+".pdf"; Receipt receipt = new Receipt(); receipt.setReceiptNum(id); receipt.setReceiptNo(id); receipt.setBuyDate("2022/3/12"); receipt.setStartDate("2022/3/12"); receipt.setSeal("印密"); receipt.setYear("2022"); receipt.setPeriod("01"); receipt.setDeadline("三年"); receipt.setRate("3.45%"); receipt.setEndDate("2025/3/12"); receipt.setTellerNum("9527"); receipt.setAccountNum("130503196701010001"); receipt.setAccountName("张三"); receipt.setMoney("人民币壹百万元整 RMB1,000,000.00"); receipt.setRedemptionDate("2023/3/12"); receipt.setInterestAccDays("365"); receipt.setInterest("34500"); receipt.setOperator("经办员"); receipt.setStatus("有效"); receipt.setRecordNum("NO."+id); buildPdf(templateFilePath,pdfFilePath,receipt); } /** * 根据PDF模版生成PDF文件 * * @param templateFilePath PDF模版文件路径 * @param pdfFilePath pdf文件保存路径 * @param receipt */ public static void buildPdf(String templateFilePath, String pdfFilePath, Receipt receipt) throws Exception { // 表单域数据填充 HashMap<String, String> data = new HashMap<>(); data.put("receiptNum", receipt.receiptNum); data.put("receiptNo", receipt.receiptNo); data.put("buyDate", receipt.buyDate); data.put("startDate", receipt.startDate); data.put("seal", receipt.seal); data.put("year", receipt.year); data.put("period", receipt.period); data.put("deadline", receipt.deadline); data.put("rate", receipt.rate); data.put("endDate", receipt.endDate); data.put("tellerNum", receipt.tellerNum); data.put("accountNum", receipt.accountNum); data.put("accountName", receipt.accountName); data.put("money", receipt.money); data.put("redemptionDate", receipt.redemptionDate); data.put("interestAccDays", receipt.interestAccDays); data.put("interest", receipt.interest); data.put("operator", receipt.operator); data.put("status", receipt.status); data.put("recordNum", receipt.recordNum); createPDF(templateFilePath, data, true, pdfFilePath); } /** * 根据PDF模版生成PDF文件 * * @param templateFilePath PDF模版文件路径 * @param data 表单域数据 * @param formFlattening false:生成后的PDF文件表单域仍然可编辑 true:生成后的PDF文件表单域不可编辑 * @param pdfFilePath 生成PDF的文件路径 */ private static void createPDF(String templateFilePath, HashMap<String, String> data, boolean formFlattening, String pdfFilePath) throws Exception { PdfReader reader = null; ByteArrayOutputStream bos = null; PdfStamper pdfStamper = null; FileOutputStream fos = null; try { // 读取PDF模版文件 reader = new PdfReader(templateFilePath); // 输出流 bos = new ByteArrayOutputStream(); // 构建PDF对象 pdfStamper = new PdfStamper(reader, bos); // 获取表单数据 AcroFields form = pdfStamper.getAcroFields(); // 使用中文字体 使用 AcroFields填充值的不需要在程序中设置字体,在模板文件中设置字体为中文字体 Adobe 宋体 std L //BaseFont bfChinese = BaseFont.createFont("STKaiti-Std-Regular", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); //com.itextpdf.text.Font font = new com.itextpdf.text.Font(bfChinese, 12, com.itextpdf.text.Font.NORMAL); //form.addSubstitutionFont(bfChinese); // 表单赋值 for (String key : data.keySet()) { form.setField(key, data.get(key)); //form.setFieldProperty(key, "textfont", bfChinese, null); //form.setFieldProperty(key, "textalignment", PdfFormField.ALIGN_CENTER, null); // 也可以指定字体 //form.setFieldProperty(key, "textfont", bfChinese, null); //form.setFieldProperty(key, "textalignment",1, null); // 获取文本框的矩形区域(用于计算居中位置) /*Rectangle rect = form.getFieldPositions(key).get(0).position; float x = rect.getLeft() + (rect.getRight() - rect.getLeft()) / 2; float y = rect.getBorder() + (rect.getTop() - rect.getBottom()) / 2; // 设置文本框的文本对齐方式为居中(在iText中,对齐方式的值为左对齐:0, 居中:1, 右对齐:2) form.setFieldProperty(key, "textalignment", 1, null); // 填充汉字内容(这里以"张三"为例) form.setField(key, data.get(key)); // 设置内容的位置为计算得到的居中位置 form.setFieldProperty(key, "textx", x, null); form.setFieldProperty(key, "texty", y, null);*/ } //设置生成的PDF文件不可编辑 pdfStamper.setFormFlattening(true); pdfStamper.close(); fos = new FileOutputStream(pdfFilePath); fos.write(bos.toByteArray()); fos.flush(); } finally { if (null != fos) { try { fos.close(); } catch (Exception e) { e.printStackTrace(); } } if (null != bos) { try { bos.close(); } catch (Exception e) { e.printStackTrace(); } } if (null != reader) { try { reader.close(); } catch (Exception e) { e.printStackTrace(); } } } } private static void addTextToPdfCenter(AcroFields form, PdfStamper stamper, String text,String fieldName,BaseFont baseFont){ // 通过模板表单单元格名获取所在页和坐标,左下角为起点 int pageNo = form.getFieldPositions(fieldName).get(0).page; Rectangle signRect = form.getFieldPositions(fieldName).get(0).position; // 获取操作的页面 PdfContentByte contentByte = stamper.getOverContent(pageNo); //创建表单 PdfPTable table = new PdfPTable(1); //获取当前模板表单宽度 float totalWidth = signRect.getRight() - signRect.getLeft() - 1; //设置新表单宽度 table.setTotalWidth(totalWidth); //设置中文格式 Font font = new Font(baseFont); //设置单元格格式 PdfPCell cell = new PdfPCell(new Phrase(text,font)); //设置单元格高度 cell.setFixedHeight(signRect.getTop()-signRect.getBottom()-1); cell.setBorderWidth(0); //设置垂直居中 cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //设置水平居中 cell.setHorizontalAlignment(Element.ALIGN_CENTER); //添加到表单中 table.addCell(cell); //写入pdf table.writeSelectedRows(0, -1, signRect.getLeft(), signRect.getTop(), contentByte); } }