首先我用Java代码实现:
/**
* 缴费小票
*
* @param payPrintParam 配置文件
*
* @return BufferedImage对象
*
* @throws Exception 异常
*/
public static BufferedImage payPrting(PayPrintParam payPrintParam) throws Exception {
//1.画布
BufferedImage bi = new BufferedImage(300, 400, BufferedImage.TYPE_BYTE_GRAY);
//2.画笔
Graphics2D g2d = bi.createGraphics();
g2d.setBackground(Color.WHITE);//设置背景色
g2d.clearRect(0, 0, 300, 400);//通过使用当前绘图表面的背景色进行填充来清除指定的矩形
//2.4重设透明度,开始画图
//g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1));
//2.5设置画笔颜色
g2d.setPaint( Color.BLACK);
g2d.setFont(new Font("Default", Font.PLAIN, 20));
g2d.drawString("凤梨一号自助机缴费凭条", 30, 20);
g2d.drawString("---------------------------------------", 7, 45);
g2d.setFont(new Font("Default", Font.PLAIN, 18));
Map<String, String> map = payPrintParam.getMap();
Integer y=75;
for (String s : map.keySet()) {
g2d.drawString(s+":" + String.valueOf(map.get(s)), 5, y);
y+=30;
}
if(payPrintParam.getFoot()!=null){
g2d.setFont(new Font("Default", Font.PLAIN, 20));
g2d.drawString("---------------------------------------", 7, y);
// g2d.drawString(payPrintParam.getFoot(), 5, y+30);
String[] fontTexts = payPrintParam.getFoot().split("\n");
if(fontTexts.length>1){
for (String fontText : fontTexts) {
y=y+30;
g2d.drawString(fontText, 5, y);
}
}else{
g2d.drawString(payPrintParam.getFoot(), 5, y+30);
}
}
g2d.dispose();
return bi;
}
/**
* 生成bmp图片
*
* @param image BufferedImage对象
*
* @return byte数组
*
* @throws IOException 异常
*/
public static byte[] buildBytesbmp(BufferedImage image) throws Exception {
try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) {
//bufferedImage转为byte数组
ImageIO.write(image, "png", outStream);
return outStream.toByteArray();
}
}
/**
* 将byte数组保存为本地文件
*
* @param buf byte数组
* @param fullPath 文件全路径
*
* @throws IOException 异常
*/
private static void storeBytes(byte[] buf, String fullPath) throws IOException {
File file = new File(fullPath);
try (FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
//1.如果父目录不存在,则创建
File dir = file.getParentFile();
if (!dir.exists()) {
dir.mkdirs();
}
//2.写byte数组到文件
bos.write(buf);
}
}
/**
* 打印小票
*
* @param payPrintParam 配置文件F
* @param fullPath 保存全路径
*
* @throws Exception 异常
*/
public static void buildAndSmallTicket(PayPrintParam payPrintParam, String fullPath) throws Exception {
storeBytes(buildBytesbmp(payPrting(payPrintParam)), fullPath);
}
设置图片头信息,图片位数,通过 x,y设置图片样式,通过ImageIO.write(image, "png", outStream);将BufferedImage 转换为baty数组再用BufferedOutputStream将数组写入文件